1use crate::{error::StageError, StageCheckpoint, StageId};
2use alloy_primitives::{BlockNumber, TxNumber};
3use reth_provider::{BlockReader, ProviderError, StaticFileProviderFactory, StaticFileSegment};
4use std::{
5 cmp::{max, min},
6 future::{poll_fn, Future},
7 ops::{Range, RangeInclusive},
8 task::{Context, Poll},
9};
10use tracing::instrument;
11
12#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
14pub struct ExecInput {
15 pub target: Option<BlockNumber>,
17 pub checkpoint: Option<StageCheckpoint>,
19}
20
21#[derive(Debug, PartialEq, Eq, Clone)]
23pub struct BlockRangeOutput {
24 pub block_range: RangeInclusive<BlockNumber>,
26 pub is_final_range: bool,
28}
29
30#[derive(Debug, PartialEq, Eq, Clone)]
32pub struct TransactionRangeOutput {
33 pub tx_range: Range<TxNumber>,
35 pub block_range: RangeInclusive<BlockNumber>,
37 pub is_final_range: bool,
39}
40
41impl ExecInput {
42 pub fn checkpoint(&self) -> StageCheckpoint {
44 self.checkpoint.unwrap_or_default()
45 }
46
47 pub fn next_block(&self) -> BlockNumber {
50 let current_block = self.checkpoint();
51 current_block.block_number + 1
52 }
53
54 pub fn target_reached(&self) -> bool {
56 self.checkpoint().block_number >= self.target()
57 }
58
59 pub fn target(&self) -> BlockNumber {
61 self.target.unwrap_or_default()
62 }
63
64 pub fn next_block_range(&self) -> RangeInclusive<BlockNumber> {
66 self.next_block_range_with_threshold(u64::MAX).block_range
67 }
68
69 pub const fn is_first_range(&self) -> bool {
71 self.checkpoint.is_none()
72 }
73
74 pub fn next_block_range_with_threshold(&self, threshold: u64) -> BlockRangeOutput {
76 let current_block = self.checkpoint();
77 let start = current_block.block_number + 1;
78 let target = self.target();
79
80 let end = min(target, current_block.block_number.saturating_add(threshold));
81
82 let is_final_range = end == target;
83 BlockRangeOutput { block_range: start..=end, is_final_range }
84 }
85
86 #[instrument(level = "debug", target = "sync::stages", skip(provider), ret)]
92 pub fn next_block_range_with_transaction_threshold<Provider>(
93 &self,
94 provider: &Provider,
95 tx_threshold: u64,
96 ) -> Result<Option<TransactionRangeOutput>, StageError>
97 where
98 Provider: StaticFileProviderFactory + BlockReader,
99 {
100 let Some(lowest_transactions_block) =
102 provider.static_file_provider().get_lowest_range_start(StaticFileSegment::Transactions)
103 else {
104 return Ok(None)
105 };
106
107 let start_block = self.next_block().max(lowest_transactions_block);
114 let target_block = self.target();
115
116 if start_block > target_block {
120 return Ok(None)
121 }
122
123 let start_block_body = provider
124 .block_body_indices(start_block)?
125 .ok_or(ProviderError::BlockBodyIndicesNotFound(start_block))?;
126 let first_tx_num = start_block_body.first_tx_num();
127
128 let target_block_body = provider
129 .block_body_indices(target_block)?
130 .ok_or(ProviderError::BlockBodyIndicesNotFound(target_block))?;
131
132 let all_tx_cnt = target_block_body.next_tx_num() - first_tx_num;
134
135 if all_tx_cnt == 0 {
136 return Ok(None)
138 }
139
140 let (end_block, is_final_range, next_tx_num) = if all_tx_cnt <= tx_threshold {
142 (target_block, true, target_block_body.next_tx_num())
143 } else {
144 let end_block_number = provider
147 .block_by_transaction_id(first_tx_num + tx_threshold)?
148 .expect("block of tx must exist");
149 let end_block_body = provider
152 .block_body_indices(end_block_number)?
153 .ok_or(ProviderError::BlockBodyIndicesNotFound(end_block_number))?;
154 (end_block_number, false, end_block_body.next_tx_num())
155 };
156
157 let tx_range = first_tx_num..next_tx_num;
158 Ok(Some(TransactionRangeOutput {
159 tx_range,
160 block_range: start_block..=end_block,
161 is_final_range,
162 }))
163 }
164}
165
166#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
168pub struct UnwindInput {
169 pub checkpoint: StageCheckpoint,
171 pub unwind_to: BlockNumber,
173 pub bad_block: Option<BlockNumber>,
175}
176
177impl UnwindInput {
178 pub fn unwind_block_range(&self) -> RangeInclusive<BlockNumber> {
180 self.unwind_block_range_with_threshold(u64::MAX).0
181 }
182
183 pub fn unwind_block_range_with_threshold(
185 &self,
186 threshold: u64,
187 ) -> (RangeInclusive<BlockNumber>, BlockNumber, bool) {
188 let end = self.checkpoint.block_number;
189 let unwind_to = max(self.unwind_to, end.saturating_sub(threshold.max(1)));
191 (unwind_to + 1..=end, unwind_to, unwind_to == self.unwind_to)
192 }
193}
194
195#[derive(Debug, PartialEq, Eq, Clone)]
197pub struct ExecOutput {
198 pub checkpoint: StageCheckpoint,
200 pub done: bool,
202}
203
204impl ExecOutput {
205 pub const fn in_progress(checkpoint: StageCheckpoint) -> Self {
207 Self { checkpoint, done: false }
208 }
209
210 pub const fn done(checkpoint: StageCheckpoint) -> Self {
212 Self { checkpoint, done: true }
213 }
214}
215
216#[derive(Debug, PartialEq, Eq, Clone)]
218pub struct UnwindOutput {
219 pub checkpoint: StageCheckpoint,
221}
222
223#[auto_impl::auto_impl(Box)]
235pub trait Stage<Provider>: Send {
236 fn id(&self) -> StageId;
240
241 fn poll_execute_ready(
266 &mut self,
267 _cx: &mut Context<'_>,
268 _input: ExecInput,
269 ) -> Poll<Result<(), StageError>> {
270 Poll::Ready(Ok(()))
271 }
272
273 fn execute(&mut self, provider: &Provider, input: ExecInput) -> Result<ExecOutput, StageError>;
277
278 fn post_execute_commit(&mut self) -> Result<(), StageError> {
284 Ok(())
285 }
286
287 fn unwind(
289 &mut self,
290 provider: &Provider,
291 input: UnwindInput,
292 ) -> Result<UnwindOutput, StageError>;
293
294 fn post_unwind_commit(&mut self) -> Result<(), StageError> {
300 Ok(())
301 }
302
303 fn validate_unwind(
309 &mut self,
310 _provider: &Provider,
311 _input: UnwindInput,
312 ) -> Result<(), StageError> {
313 Ok(())
314 }
315}
316
317pub trait StageExt<Provider>: Stage<Provider> {
319 fn execute_ready(
322 &mut self,
323 input: ExecInput,
324 ) -> impl Future<Output = Result<(), StageError>> + Send {
325 poll_fn(move |cx| self.poll_execute_ready(cx, input))
326 }
327}
328
329impl<Provider, S: Stage<Provider> + ?Sized> StageExt<Provider> for S {}
330
331#[cfg(test)]
332mod tests {
333 use reth_chainspec::MAINNET;
334 use reth_db::test_utils::{
335 create_test_rocksdb_dir, create_test_rw_db, create_test_static_files_dir,
336 };
337 use reth_db_api::{models::StoredBlockBodyIndices, tables, transaction::DbTxMut};
338 use reth_provider::{
339 providers::RocksDBProvider, test_utils::MockNodeTypesWithDB, ProviderFactory,
340 StaticFileProviderBuilder, StaticFileProviderFactory, StaticFileSegment,
341 };
342 use reth_stages_types::StageCheckpoint;
343 use reth_storage_overlay::OverlayManager;
344 use reth_testing_utils::generators::{self, random_signed_tx};
345
346 use crate::ExecInput;
347
348 #[test]
349 fn test_exec_input_next_block_range_with_transaction_threshold() {
350 let mut rng = generators::rng();
351 let provider_factory = ProviderFactory::<MockNodeTypesWithDB>::new(
352 create_test_rw_db(),
353 MAINNET.clone(),
354 StaticFileProviderBuilder::read_write(create_test_static_files_dir().0.keep())
355 .with_blocks_per_file(1)
356 .build()
357 .unwrap(),
358 RocksDBProvider::builder(create_test_rocksdb_dir().0.keep()).build().unwrap(),
359 OverlayManager::default(),
360 reth_tasks::Runtime::test(),
361 )
362 .unwrap();
363
364 {
366 let exec_input = ExecInput { target: Some(100), checkpoint: None };
367
368 let range_output = exec_input
369 .next_block_range_with_transaction_threshold(&provider_factory, 10)
370 .unwrap();
371 assert!(range_output.is_none());
372 }
373
374 {
376 let exec_input =
377 ExecInput { target: Some(1), checkpoint: Some(StageCheckpoint::new(10)) };
378
379 let range_output = exec_input
380 .next_block_range_with_transaction_threshold(&provider_factory, 10)
381 .unwrap();
382 assert!(range_output.is_none());
383 }
384
385 {
387 let exec_input = ExecInput { target: Some(1), checkpoint: None };
388
389 let mut provider_rw = provider_factory.provider_rw().unwrap();
390 provider_rw
391 .tx_mut()
392 .put::<tables::BlockBodyIndices>(
393 1,
394 StoredBlockBodyIndices { first_tx_num: 0, tx_count: 2 },
395 )
396 .unwrap();
397 let mut writer =
398 provider_rw.get_static_file_writer(0, StaticFileSegment::Transactions).unwrap();
399 writer.increment_block(0).unwrap();
400 writer.increment_block(1).unwrap();
401 writer.append_transaction(0, &random_signed_tx(&mut rng)).unwrap();
402 writer.append_transaction(1, &random_signed_tx(&mut rng)).unwrap();
403 drop(writer);
404 provider_rw.commit().unwrap();
405
406 let range_output = exec_input
407 .next_block_range_with_transaction_threshold(&provider_factory, 10)
408 .unwrap()
409 .unwrap();
410 assert_eq!(range_output.tx_range, 0..2);
411 assert_eq!(range_output.block_range, 1..=1);
412 assert!(range_output.is_final_range);
413 }
414
415 {
417 let exec_input =
418 ExecInput { target: Some(2), checkpoint: Some(StageCheckpoint::new(1)) };
419
420 let mut provider_rw = provider_factory.provider_rw().unwrap();
421 provider_rw
422 .tx_mut()
423 .put::<tables::BlockBodyIndices>(
424 2,
425 StoredBlockBodyIndices { first_tx_num: 2, tx_count: 1 },
426 )
427 .unwrap();
428 let mut writer =
429 provider_rw.get_static_file_writer(1, StaticFileSegment::Transactions).unwrap();
430 writer.increment_block(2).unwrap();
431 writer.append_transaction(2, &random_signed_tx(&mut rng)).unwrap();
432 drop(writer);
433 provider_rw.commit().unwrap();
434
435 let range_output = exec_input
436 .next_block_range_with_transaction_threshold(&provider_factory, 10)
437 .unwrap()
438 .unwrap();
439 assert_eq!(range_output.tx_range, 2..3);
440 assert_eq!(range_output.block_range, 2..=2);
441 assert!(range_output.is_final_range);
442 }
443
444 {
446 let exec_input = ExecInput { target: Some(2), checkpoint: None };
447
448 provider_factory
449 .static_file_provider()
450 .delete_jar(StaticFileSegment::Transactions, 0)
451 .unwrap();
452 provider_factory
453 .static_file_provider()
454 .delete_jar(StaticFileSegment::Transactions, 1)
455 .unwrap();
456
457 let range_output = exec_input
458 .next_block_range_with_transaction_threshold(&provider_factory, 10)
459 .unwrap()
460 .unwrap();
461 assert_eq!(range_output.tx_range, 2..3);
462 assert_eq!(range_output.block_range, 2..=2);
463 assert!(range_output.is_final_range);
464 }
465
466 {
468 let exec_input =
469 ExecInput { target: Some(3), checkpoint: Some(StageCheckpoint::new(2)) };
470
471 let mut provider_rw = provider_factory.provider_rw().unwrap();
472 provider_rw
473 .tx_mut()
474 .put::<tables::BlockBodyIndices>(
475 3,
476 StoredBlockBodyIndices { first_tx_num: 3, tx_count: 1 },
477 )
478 .unwrap();
479 let mut writer =
480 provider_rw.get_static_file_writer(1, StaticFileSegment::Transactions).unwrap();
481 writer.increment_block(3).unwrap();
482 writer.append_transaction(3, &random_signed_tx(&mut rng)).unwrap();
483 drop(writer);
484 provider_rw.commit().unwrap();
485
486 let range_output = exec_input
487 .next_block_range_with_transaction_threshold(&provider_factory, 10)
488 .unwrap()
489 .unwrap();
490 assert_eq!(range_output.tx_range, 3..4);
491 assert_eq!(range_output.block_range, 3..=3);
492 assert!(range_output.is_final_range);
493 }
494 }
495}