1use crate::download::{
2 manifest::{ComponentManifest, ComponentSelection, SnapshotComponentType, SnapshotManifest},
3 SelectionPreset,
4};
5use reth_chainspec::{EthereumHardfork, EthereumHardforks};
6use reth_config::config::{BlocksPerFileConfig, Config, PruneConfig, StaticFilesConfig};
7use reth_db::{mdbx, models::StorageSettings, tables, DatabaseError};
8use reth_db_api::transaction::{DbTx, DbTxMut};
9use reth_node_core::args::DefaultPruningValues;
10use reth_prune_types::{
11 PruneCheckpoint, PruneMode, PruneSegment, MINIMUM_DISTANCE, MINIMUM_UNWIND_SAFE_DISTANCE,
12};
13use reth_stages_types::StageCheckpoint;
14use reth_storage_api::metadata::keys;
15use std::{collections::BTreeMap, path::Path};
16use tracing::info;
17
18pub fn write_config(config: &Config, data_dir: &Path) -> eyre::Result<bool> {
22 write_config_to_path(config, &data_dir.join("reth.toml"))
23}
24
25pub(super) fn write_config_to_path(config: &Config, config_path: &Path) -> eyre::Result<bool> {
27 if config_path.try_exists()? {
28 info!(target: "reth::cli",
29 path = ?config_path,
30 "Config file already exists, skipping config generation"
31 );
32 return Ok(false);
33 }
34
35 let toml_str = toml::to_string_pretty(config)?;
36 if let Some(parent) = config_path.parent() {
37 reth_fs_util::create_dir_all(parent)?;
38 }
39 reth_fs_util::write(config_path, toml_str)?;
40
41 info!(target: "reth::cli",
42 path = ?config_path,
43 "Generated config based on downloaded components"
44 );
45
46 Ok(true)
47}
48
49pub(super) fn write_prune_checkpoints_tx<Tx>(
51 tx: &Tx,
52 config: &Config,
53 selections: &BTreeMap<SnapshotComponentType, ComponentSelection>,
54 manifest: &SnapshotManifest,
55 is_v2: bool,
56 bodies_boundary: Option<u64>,
57 source_bodies: Option<PruneCheckpoint>,
58) -> eyre::Result<()>
59where
60 Tx: DbTx + DbTxMut,
61{
62 let segments = &config.prune.segments;
63
64 let tip_indices = tx.get::<tables::BlockBodyIndices>(manifest.block)?;
65 for (segment, mode) in [
66 (PruneSegment::SenderRecovery, segments.sender_recovery),
67 (PruneSegment::TransactionLookup, segments.transaction_lookup),
68 (PruneSegment::Receipts, segments.receipts),
69 (PruneSegment::AccountHistory, segments.account_history),
70 (PruneSegment::StorageHistory, segments.storage_history),
71 (PruneSegment::Bodies, segments.bodies_history),
72 ] {
73 let restored_checkpoint = |block_number: Option<u64>, tx_number| {
74 let prune_mode = mode.unwrap_or_else(|| {
76 PruneMode::Before(block_number.map_or(0, |block| block.saturating_add(1)))
77 });
78 PruneCheckpoint { block_number, tx_number, prune_mode }
79 };
80 let checkpoint = match segment {
81 PruneSegment::AccountHistory |
84 PruneSegment::StorageHistory |
85 PruneSegment::TransactionLookup
86 if !is_v2 =>
87 {
88 continue
89 }
90 PruneSegment::AccountHistory | PruneSegment::StorageHistory => {
91 let component = if segment == PruneSegment::AccountHistory {
92 SnapshotComponentType::AccountChangesets
93 } else {
94 SnapshotComponentType::StorageChangesets
95 };
96 let target = if manifest.component(component).is_some() &&
97 manifest.chunks_for_distance(component, Some(1)) == 0
98 {
99 Some(manifest.block)
101 } else {
102 match selections.get(&component) {
103 Some(ComponentSelection::All) => None,
104 Some(ComponentSelection::Distance(distance)) => {
105 manifest.block.checked_sub(*distance)
106 }
107 Some(ComponentSelection::Since(block)) => {
108 block.checked_sub(1).map(|n| n.min(manifest.block))
109 }
110 Some(ComponentSelection::None) | None => Some(manifest.block),
111 }
112 };
113 let source = tx.get::<tables::PruneCheckpoints>(segment)?;
114 let (block_number, tx_number) = match (target, source) {
115 (Some(target), source) => {
116 (Some(target).max(source.and_then(|cp| cp.block_number)), None)
117 }
118 (None, Some(source)) => (source.block_number, source.tx_number),
119 (None, None) => continue,
120 };
121 restored_checkpoint(block_number, tx_number)
122 }
123 PruneSegment::Bodies => {
124 let source_block = source_bodies.and_then(|checkpoint| checkpoint.block_number);
125 let block_number = bodies_boundary.max(source_block);
126 if block_number.is_none() && mode.is_none() && source_bodies.is_none() {
127 continue
128 }
129 let mut tx_number = source_bodies.and_then(|checkpoint| checkpoint.tx_number);
130 if let Some(block) = bodies_boundary &&
131 Some(block) > source_block
132 {
133 let indices = if block == manifest.block {
134 tip_indices
135 } else {
136 tx.get::<tables::BlockBodyIndices>(block)?
137 };
138 tx_number =
139 tx_number.max(indices.and_then(|body| body.next_tx_num().checked_sub(1)));
140 }
141 restored_checkpoint(block_number, tx_number)
142 }
143 _ => {
144 let Some(prune_mode) = mode else { continue };
145 PruneCheckpoint {
146 block_number: Some(manifest.block),
147 tx_number: tip_indices.map(|body| body.last_tx_num()),
148 prune_mode,
149 }
150 }
151 };
152 tx.put::<tables::PruneCheckpoints>(segment, checkpoint)?;
153
154 info!(target: "reth::cli",
155 segment = %segment,
156 block = ?checkpoint.block_number,
157 tx = ?checkpoint.tx_number,
158 mode = ?checkpoint.prune_mode,
159 "Set prune checkpoint"
160 );
161 }
162
163 tx.put::<tables::Metadata>(keys::VERIFIED_SNAPSHOT_BODIES.to_owned(), Vec::new())?;
164 Ok(())
165}
166
167pub(super) fn snapshot_uses_v2(
169 tx: &impl DbTx,
170 selections: &BTreeMap<SnapshotComponentType, ComponentSelection>,
171) -> eyre::Result<bool> {
172 let bytes = match tx.get::<tables::Metadata>(keys::STORAGE_SETTINGS.to_owned()) {
173 Ok(Some(bytes)) => bytes,
174 Ok(None) => return Ok(false),
175 Err(DatabaseError::Open(err)) if err == mdbx::Error::NotFound.into() => return Ok(false),
177 Err(err) => return Err(err.into()),
178 };
179 if let Ok(settings) = serde_json::from_slice::<StorageSettings>(&bytes) {
180 return Ok(settings.is_v2())
181 }
182
183 if let Ok(flags) = serde_json::from_slice::<serde_json::Map<String, serde_json::Value>>(&bytes)
186 {
187 for (name, value) in flags {
188 if value.as_bool() != Some(true) {
189 continue
190 }
191 let incompatible = match name.as_str() {
192 "transaction_senders_in_static_files" => matches!(
193 selections.get(&SnapshotComponentType::TransactionSenders),
194 Some(selection) if *selection != ComponentSelection::None
195 ),
196 "storages_history_in_rocksdb" |
197 "transaction_hash_numbers_in_rocksdb" |
198 "account_history_in_rocksdb" |
199 "account_changesets_in_static_files" |
200 "storage_changesets_in_static_files" |
201 "use_hashed_state" => true,
202 _ => false,
203 };
204 eyre::ensure!(
205 !incompatible,
206 "Unsupported legacy snapshot setting for this download: {name}=true"
207 );
208 }
209 }
210 Ok(false)
211}
212
213const INDEX_STAGE_IDS: [&str; 3] =
215 ["TransactionLookup", "IndexAccountHistory", "IndexStorageHistory"];
216
217const INDEX_PRUNE_SEGMENTS: [PruneSegment; 1] = [PruneSegment::TransactionLookup];
223
224pub(crate) fn reset_index_stage_checkpoints_tx<Tx>(tx: &Tx) -> eyre::Result<()>
237where
238 Tx: DbTx + DbTxMut,
239{
240 for stage_id in INDEX_STAGE_IDS {
241 tx.put::<tables::StageCheckpoints>(stage_id.to_string(), StageCheckpoint::default())?;
242
243 tx.delete::<tables::StageCheckpointProgresses>(stage_id.to_string(), None)?;
245
246 info!(target: "reth::cli", stage = stage_id, "Reset stage checkpoint to block 0");
247 }
248
249 for segment in INDEX_PRUNE_SEGMENTS {
252 tx.delete::<tables::PruneCheckpoints>(segment, None)?;
253 }
254
255 Ok(())
256}
257
258pub(crate) fn config_for_selections(
263 selections: &BTreeMap<SnapshotComponentType, ComponentSelection>,
264 manifest: &SnapshotManifest,
265 preset: Option<SelectionPreset>,
266 chain_spec: Option<&impl EthereumHardforks>,
267) -> Config {
268 let selection_for = |ty| selections.get(&ty).copied().unwrap_or(ComponentSelection::None);
269
270 let tx_sel = selection_for(SnapshotComponentType::Transactions);
271 let senders_sel = selection_for(SnapshotComponentType::TransactionSenders);
272 let receipt_sel = selection_for(SnapshotComponentType::Receipts);
273 let account_cs_sel = selection_for(SnapshotComponentType::AccountChangesets);
274 let storage_cs_sel = selection_for(SnapshotComponentType::StorageChangesets);
275
276 let is_archive = [tx_sel, senders_sel, receipt_sel, account_cs_sel, storage_cs_sel]
278 .iter()
279 .all(|s| *s == ComponentSelection::All);
280
281 let blocks_per_file = |ty: SnapshotComponentType| -> Option<u64> {
283 match manifest.component(ty)? {
284 ComponentManifest::Chunked(c) => Some(c.blocks_per_file),
285 ComponentManifest::Single(_) | ComponentManifest::Files(_) => None,
286 }
287 };
288 let static_files = StaticFilesConfig {
289 blocks_per_file: BlocksPerFileConfig {
290 headers: blocks_per_file(SnapshotComponentType::Headers),
291 transactions: blocks_per_file(SnapshotComponentType::Transactions),
292 receipts: blocks_per_file(SnapshotComponentType::Receipts),
293 transaction_senders: blocks_per_file(SnapshotComponentType::TransactionSenders),
294 account_change_sets: blocks_per_file(SnapshotComponentType::AccountChangesets),
295 storage_change_sets: blocks_per_file(SnapshotComponentType::StorageChangesets),
296 },
297 };
298
299 if matches!(preset, Some(SelectionPreset::Archive)) {
300 return Config { static_files, ..Default::default() };
301 }
302
303 if matches!(preset, Some(SelectionPreset::Minimal)) {
304 return Config {
305 prune: PruneConfig {
306 segments: DefaultPruningValues::get_global().minimal_prune_modes.clone(),
307 ..Default::default()
308 },
309 static_files,
310 ..Default::default()
311 };
312 }
313
314 if matches!(preset, Some(SelectionPreset::Full)) {
315 let defaults = DefaultPruningValues::get_global();
316 let mut segments = defaults.full_prune_modes.clone();
317
318 if defaults.full_bodies_history_use_pre_merge {
319 segments.bodies_history = chain_spec.and_then(|chain_spec| {
320 chain_spec
321 .ethereum_fork_activation(EthereumHardfork::Paris)
322 .block_number()
323 .map(PruneMode::Before)
324 });
325 }
326
327 return Config {
328 prune: PruneConfig { segments, ..Default::default() },
329 static_files,
330 ..Default::default()
331 };
332 }
333
334 if is_archive {
335 return Config { static_files, ..Default::default() };
336 }
337
338 let mut config = Config::default();
339 let mut prune = PruneConfig::default();
340
341 if senders_sel != ComponentSelection::All {
342 prune.segments.sender_recovery = Some(PruneMode::Full);
343 }
344 prune.segments.transaction_lookup = Some(PruneMode::Full);
345
346 if let Some(mode) = selection_to_prune_mode(tx_sel, Some(MINIMUM_UNWIND_SAFE_DISTANCE)) {
347 prune.segments.bodies_history = Some(mode);
348 }
349
350 if let Some(mode) = selection_to_prune_mode(receipt_sel, Some(MINIMUM_DISTANCE)) {
351 prune.segments.receipts = Some(mode);
352 }
353
354 if let Some(mode) = selection_to_prune_mode(account_cs_sel, Some(MINIMUM_UNWIND_SAFE_DISTANCE))
355 {
356 prune.segments.account_history = Some(mode);
357 }
358
359 if let Some(mode) = selection_to_prune_mode(storage_cs_sel, Some(MINIMUM_UNWIND_SAFE_DISTANCE))
360 {
361 prune.segments.storage_history = Some(mode);
362 }
363
364 config.prune = prune;
365 config.static_files = static_files;
366 config
367}
368
369pub(super) fn selection_to_prune_mode(
375 sel: ComponentSelection,
376 min_distance: Option<u64>,
377) -> Option<PruneMode> {
378 match sel {
379 ComponentSelection::All => None,
380 ComponentSelection::Distance(d) => {
381 Some(PruneMode::Distance(min_distance.map_or(d, |min| d.max(min))))
382 }
383 ComponentSelection::Since(block) => Some(PruneMode::Before(block)),
384 ComponentSelection::None => Some(min_distance.map_or(PruneMode::Full, PruneMode::Distance)),
385 }
386}
387
388pub(crate) fn describe_prune_config(config: &Config) -> Vec<String> {
390 let segments = &config.prune.segments;
391
392 [
393 ("sender_recovery", segments.sender_recovery),
394 ("transaction_lookup", segments.transaction_lookup),
395 ("bodies_history", segments.bodies_history),
396 ("receipts", segments.receipts),
397 ("account_history", segments.account_history),
398 ("storage_history", segments.storage_history),
399 ]
400 .into_iter()
401 .filter_map(|(name, mode)| mode.map(|m| format!("{name}={}", format_mode(&m))))
402 .collect()
403}
404
405fn format_mode(mode: &PruneMode) -> String {
407 match mode {
408 PruneMode::Full => "\"full\"".to_string(),
409 PruneMode::Distance(d) => format!("{{ distance = {d} }}"),
410 PruneMode::Before(b) => format!("{{ before = {b} }}"),
411 }
412}
413
414#[cfg(test)]
415mod tests {
416 use super::*;
417 use crate::download::tests::{
418 empty_manifest, history_checkpoints, set_history_checkpoints, set_layout,
419 };
420 use reth_db::{models::StoredBlockBodyIndices, test_utils::create_test_rw_db, Database};
421 use reth_prune_types::UnwindTargetPrunedError;
422
423 #[test]
424 fn write_prune_checkpoints_sets_all_segments() -> eyre::Result<()> {
425 let db = create_test_rw_db();
426 let tx = db.tx_mut()?;
427 let tip = 21_000_000;
428 let manifest = SnapshotManifest { block: tip, ..empty_manifest() };
429 let selections = BTreeMap::new();
430 let config =
431 config_for_selections(&selections, &manifest, None, None::<&reth_chainspec::ChainSpec>);
432 write_prune_checkpoints_tx(&tx, &config, &selections, &manifest, true, Some(tip), None)?;
433 for segment in [
434 PruneSegment::SenderRecovery,
435 PruneSegment::TransactionLookup,
436 PruneSegment::Receipts,
437 PruneSegment::AccountHistory,
438 PruneSegment::StorageHistory,
439 PruneSegment::Bodies,
440 ] {
441 let checkpoint = tx
442 .get::<tables::PruneCheckpoints>(segment)?
443 .unwrap_or_else(|| panic!("missing checkpoint for {segment}"));
444 assert_eq!(checkpoint.block_number, Some(manifest.block), "{segment}");
445 assert_eq!(checkpoint.tx_number, None, "{segment}");
446 }
447 Ok(())
448 }
449
450 #[test]
451 fn selections_all_no_pruning() {
452 let mut selections = BTreeMap::new();
453 for ty in SnapshotComponentType::ALL {
454 selections.insert(ty, ComponentSelection::All);
455 }
456 let config = config_for_selections(
457 &selections,
458 &empty_manifest(),
459 None,
460 None::<&reth_chainspec::ChainSpec>,
461 );
462 assert_eq!(config.prune.segments.transaction_lookup, None);
464 assert_eq!(config.prune.segments.sender_recovery, None);
465 assert_eq!(config.prune.segments.bodies_history, None);
466 assert_eq!(config.prune.segments.receipts, None);
467 assert_eq!(config.prune.segments.account_history, None);
468 assert_eq!(config.prune.segments.storage_history, None);
469 }
470
471 #[test]
472 fn selections_none_clamps_to_minimum_distance() {
473 let mut selections = BTreeMap::new();
474 selections.insert(SnapshotComponentType::State, ComponentSelection::All);
475 selections.insert(SnapshotComponentType::Headers, ComponentSelection::All);
476 let config = config_for_selections(
477 &selections,
478 &empty_manifest(),
479 None,
480 None::<&reth_chainspec::ChainSpec>,
481 );
482 assert_eq!(config.prune.segments.transaction_lookup, Some(PruneMode::Full));
483 assert_eq!(config.prune.segments.sender_recovery, Some(PruneMode::Full));
484 assert_eq!(
486 config.prune.segments.bodies_history,
487 Some(PruneMode::Distance(MINIMUM_UNWIND_SAFE_DISTANCE))
488 );
489 assert_eq!(config.prune.segments.receipts, Some(PruneMode::Distance(MINIMUM_DISTANCE)));
490 assert_eq!(
491 config.prune.segments.account_history,
492 Some(PruneMode::Distance(MINIMUM_UNWIND_SAFE_DISTANCE))
493 );
494 assert_eq!(
495 config.prune.segments.storage_history,
496 Some(PruneMode::Distance(MINIMUM_UNWIND_SAFE_DISTANCE))
497 );
498 }
499
500 #[test]
501 fn selections_distance_maps_bodies_history() {
502 let mut selections = BTreeMap::new();
503 selections.insert(SnapshotComponentType::State, ComponentSelection::All);
504 selections.insert(SnapshotComponentType::Headers, ComponentSelection::All);
505 selections
506 .insert(SnapshotComponentType::Transactions, ComponentSelection::Distance(10_064));
507 selections.insert(SnapshotComponentType::Receipts, ComponentSelection::None);
508 selections
509 .insert(SnapshotComponentType::AccountChangesets, ComponentSelection::Distance(10_064));
510 selections
511 .insert(SnapshotComponentType::StorageChangesets, ComponentSelection::Distance(10_064));
512 let config = config_for_selections(
513 &selections,
514 &empty_manifest(),
515 None,
516 None::<&reth_chainspec::ChainSpec>,
517 );
518
519 assert_eq!(config.prune.segments.transaction_lookup, Some(PruneMode::Full));
520 assert_eq!(config.prune.segments.sender_recovery, Some(PruneMode::Full));
521 assert_eq!(config.prune.segments.bodies_history, Some(PruneMode::Distance(10_064)));
523 assert_eq!(config.prune.segments.receipts, Some(PruneMode::Distance(MINIMUM_DISTANCE)));
524 assert_eq!(config.prune.segments.account_history, Some(PruneMode::Distance(10_064)));
525 assert_eq!(config.prune.segments.storage_history, Some(PruneMode::Distance(10_064)));
526 }
527
528 #[test]
529 fn selections_since_maps_to_before_prune_mode() {
530 let mut selections = BTreeMap::new();
531 selections.insert(SnapshotComponentType::State, ComponentSelection::All);
532 selections.insert(SnapshotComponentType::Headers, ComponentSelection::All);
533 selections
534 .insert(SnapshotComponentType::Transactions, ComponentSelection::Since(15_537_394));
535 selections.insert(SnapshotComponentType::Receipts, ComponentSelection::Since(15_537_394));
536 selections.insert(
537 SnapshotComponentType::AccountChangesets,
538 ComponentSelection::Since(15_537_394),
539 );
540 selections.insert(
541 SnapshotComponentType::StorageChangesets,
542 ComponentSelection::Since(15_537_394),
543 );
544
545 let config = config_for_selections(
546 &selections,
547 &empty_manifest(),
548 None,
549 None::<&reth_chainspec::ChainSpec>,
550 );
551
552 assert_eq!(config.prune.segments.bodies_history, Some(PruneMode::Before(15_537_394)));
553 assert_eq!(config.prune.segments.receipts, Some(PruneMode::Before(15_537_394)));
554 assert_eq!(config.prune.segments.account_history, Some(PruneMode::Before(15_537_394)));
555 assert_eq!(config.prune.segments.storage_history, Some(PruneMode::Before(15_537_394)));
556 }
557
558 #[test]
559 fn full_preset_matches_default_full_prune_config() {
560 let mut selections = BTreeMap::new();
561 selections.insert(SnapshotComponentType::State, ComponentSelection::All);
562 selections.insert(SnapshotComponentType::Headers, ComponentSelection::All);
563 selections
564 .insert(SnapshotComponentType::Transactions, ComponentSelection::Distance(500_000));
565 selections.insert(SnapshotComponentType::Receipts, ComponentSelection::Distance(10_064));
566
567 let chain_spec = reth_chainspec::MAINNET.clone();
568 let config = config_for_selections(
569 &selections,
570 &empty_manifest(),
571 Some(SelectionPreset::Full),
572 Some(chain_spec.as_ref()),
573 );
574
575 assert_eq!(config.prune.segments.sender_recovery, Some(PruneMode::Full));
576 assert_eq!(config.prune.segments.transaction_lookup, None);
577 assert_eq!(
578 config.prune.segments.receipts,
579 Some(PruneMode::Distance(MINIMUM_UNWIND_SAFE_DISTANCE))
580 );
581 assert_eq!(
582 config.prune.segments.account_history,
583 Some(PruneMode::Distance(MINIMUM_UNWIND_SAFE_DISTANCE))
584 );
585 assert_eq!(
586 config.prune.segments.storage_history,
587 Some(PruneMode::Distance(MINIMUM_UNWIND_SAFE_DISTANCE))
588 );
589
590 let paris_block = chain_spec
591 .ethereum_fork_activation(EthereumHardfork::Paris)
592 .block_number()
593 .expect("mainnet Paris block should be known");
594 assert_eq!(config.prune.segments.bodies_history, Some(PruneMode::Before(paris_block)));
595 }
596
597 #[test]
598 fn minimal_preset_matches_default_minimal_prune_config() {
599 let config = config_for_selections(
600 &BTreeMap::from([(SnapshotComponentType::AccountChangesets, ComponentSelection::All)]),
601 &empty_manifest(),
602 Some(SelectionPreset::Minimal),
603 None::<&reth_chainspec::ChainSpec>,
604 );
605
606 assert_eq!(&config.prune.segments, &DefaultPruningValues::get_global().minimal_prune_modes);
607 }
608
609 #[test]
610 fn describe_selections_all_no_pruning() {
611 let mut selections = BTreeMap::new();
612 for ty in SnapshotComponentType::ALL {
613 selections.insert(ty, ComponentSelection::All);
614 }
615 let config = config_for_selections(
616 &selections,
617 &empty_manifest(),
618 None,
619 None::<&reth_chainspec::ChainSpec>,
620 );
621 let desc = describe_prune_config(&config);
622 assert!(desc.is_empty());
624 }
625
626 #[test]
627 fn describe_selections_with_distances() {
628 let mut selections = BTreeMap::new();
629 selections.insert(SnapshotComponentType::State, ComponentSelection::All);
630 selections.insert(SnapshotComponentType::Headers, ComponentSelection::All);
631 selections
632 .insert(SnapshotComponentType::Transactions, ComponentSelection::Distance(10_064));
633 selections.insert(SnapshotComponentType::Receipts, ComponentSelection::None);
634 let config = config_for_selections(
635 &selections,
636 &empty_manifest(),
637 None,
638 None::<&reth_chainspec::ChainSpec>,
639 );
640 let desc = describe_prune_config(&config);
641 assert!(desc.iter().any(|d| d == "sender_recovery=\"full\""));
642 assert!(desc.iter().any(|d| d == "bodies_history={ distance = 10064 }"));
644 assert!(desc.iter().any(|d| d == "receipts={ distance = 64 }"));
645 }
646
647 #[test]
648 fn history_checkpoints_do_not_advertise_undownloaded_changesets() -> eyre::Result<()> {
649 let tip = 21_000_000;
650 let manifest = SnapshotManifest { block: tip, ..empty_manifest() };
651 let db = create_test_rw_db();
652 for (selection, expected) in [
653 (ComponentSelection::None, Some(tip)),
654 (ComponentSelection::Distance(1), Some(tip - 1)),
655 (ComponentSelection::Distance(tip + 1), None),
656 (ComponentSelection::Since(tip), Some(tip - 1)),
657 (ComponentSelection::Since(0), None),
658 (ComponentSelection::All, None),
659 ] {
660 let selections = BTreeMap::from([
661 (SnapshotComponentType::AccountChangesets, selection),
662 (SnapshotComponentType::StorageChangesets, selection),
663 ]);
664 let config = config_for_selections(
665 &selections,
666 &manifest,
667 None,
668 None::<&reth_chainspec::ChainSpec>,
669 );
670 let tx = db.tx_mut()?;
671 write_prune_checkpoints_tx(
672 &tx,
673 &config,
674 &selections,
675 &manifest,
676 true,
677 Some(tip),
678 None,
679 )?;
680 for segment in [PruneSegment::AccountHistory, PruneSegment::StorageHistory] {
681 let checkpoint = tx.get::<tables::PruneCheckpoints>(segment)?;
682 assert_eq!(checkpoint.map(|cp| cp.block_number), expected.map(Some), "{segment}");
683 if let (Some(boundary), Some(cp)) = (expected, checkpoint) {
684 let modes = &config.prune.segments;
685 let unwind =
686 |block| modes.ensure_unwind_target_unpruned(tip, block, &[(segment, cp)]);
687 let Err(UnwindTargetPrunedError::TargetBelowPrunedHistory {
688 target_block,
689 pruned_block,
690 ..
691 }) = unwind(boundary - 1)
692 else {
693 panic!("expected {segment} to be pruned through {boundary}");
694 };
695 assert_eq!((target_block, pruned_block), (boundary - 1, boundary));
696 unwind(boundary)?;
697 }
698 }
699 }
700 Ok(())
701 }
702
703 #[test]
704 fn history_checkpoints_preserve_source_pruning_boundary() -> eyre::Result<()> {
705 let snapshot_block = 21_000_000;
706 let manifest = SnapshotManifest { block: snapshot_block, ..empty_manifest() };
707 let selected_boundary = 20_500_000;
708 let distance = snapshot_block - selected_boundary;
709 let since = selected_boundary + 1;
710 let selections = BTreeMap::from([
711 (SnapshotComponentType::AccountChangesets, ComponentSelection::Distance(distance)),
712 (SnapshotComponentType::StorageChangesets, ComponentSelection::Since(since)),
713 ]);
714 let config =
715 config_for_selections(&selections, &manifest, None, None::<&reth_chainspec::ChainSpec>);
716 let db = create_test_rw_db();
717 for (existing_boundary, expected) in [
718 (None, selected_boundary),
719 (Some(20_000_000), selected_boundary),
720 (Some(20_750_000), 20_750_000),
721 ] {
722 let tx = db.tx_mut()?;
723 let source = PruneCheckpoint {
724 block_number: existing_boundary,
725 tx_number: Some(100),
726 prune_mode: PruneMode::Full,
727 };
728 set_history_checkpoints(&tx, source, source);
729 write_prune_checkpoints_tx(&tx, &config, &selections, &manifest, true, None, None)?;
730 let boundary = PruneCheckpoint::pruned_through(expected);
731 assert_eq!(
732 history_checkpoints(&tx)?,
733 [PruneMode::Distance(distance), PruneMode::Before(since)]
734 .map(|prune_mode| Some(PruneCheckpoint { prune_mode, ..boundary }))
735 );
736 }
737 Ok(())
738 }
739
740 #[test]
741 fn snapshot_without_metadata_table_uses_v1() -> eyre::Result<()> {
742 let dir = tempfile::tempdir()?;
743 let db = reth_db::create_db(dir.path(), mdbx::DatabaseArguments::test())?;
744 assert!(!snapshot_uses_v2(&db.tx()?, &BTreeMap::new())?);
745 Ok(())
746 }
747
748 #[test]
749 fn rejects_unsupported_snapshot_layouts() -> eyre::Result<()> {
750 let db = create_test_rw_db();
751 let tx = db.tx_mut()?;
752 let selections =
753 BTreeMap::from([(SnapshotComponentType::TransactionSenders, ComponentSelection::All)]);
754 for bytes in [
755 b"invalid".as_slice(),
756 br#"{}"#,
757 br#"{"future_flag":true,"account_history_in_rocksdb":false}"#,
758 ] {
759 tx.put::<tables::Metadata>(keys::STORAGE_SETTINGS.to_owned(), bytes.to_vec())?;
760 assert!(!snapshot_uses_v2(&tx, &selections)?);
761 }
762 for flag in ["account_history_in_rocksdb", "transaction_senders_in_static_files"] {
763 set_layout(&tx, serde_json::json!({(flag): true, "unknown": [1]}));
764 assert_eq!(
765 snapshot_uses_v2(&tx, &selections).unwrap_err().to_string(),
766 format!("Unsupported legacy snapshot setting for this download: {flag}=true")
767 );
768 }
769 Ok(())
770 }
771
772 #[test]
773 fn bodies_checkpoint_preserves_transaction_progress() -> eyre::Result<()> {
774 let db = create_test_rw_db();
775 let manifest = SnapshotManifest { block: 24, ..empty_manifest() };
776 let mut config = Config::default();
777 config.prune.segments.bodies_history = Some(PruneMode::Before(13));
778 let source = PruneCheckpoint { tx_number: Some(16), ..PruneCheckpoint::pruned_through(15) };
779 for (first_tx_num, prior, block, tx_number) in
780 [(0, None, 9, None), (8, None, 9, Some(7)), (8, Some(source), 15, Some(16))]
781 {
782 let tx = db.tx_mut()?;
783 tx.put::<tables::BlockBodyIndices>(
784 9,
785 StoredBlockBodyIndices { first_tx_num, tx_count: 0 },
786 )?;
787 write_prune_checkpoints_tx(
788 &tx,
789 &config,
790 &BTreeMap::new(),
791 &manifest,
792 true,
793 Some(9),
794 prior,
795 )?;
796 assert_eq!(
797 tx.get::<tables::PruneCheckpoints>(PruneSegment::Bodies)?,
798 Some(PruneCheckpoint {
799 block_number: Some(block),
800 tx_number,
801 prune_mode: PruneMode::Before(13),
802 })
803 );
804 }
805 Ok(())
806 }
807}