Skip to main content

reth_config/
config.rs

1//! Configuration files.
2use reth_network_peers::TrustedPeer;
3use reth_network_types::{PeersConfig, SessionsConfig};
4use reth_prune_types::{PruneMode, PruneModes, MINIMUM_UNWIND_SAFE_DISTANCE};
5use reth_stages_types::ExecutionStageThresholds;
6use reth_static_file_types::{
7    blocks_per_file_for_prune_distance, StaticFileMap, StaticFileSegment,
8};
9use std::{
10    path::{Path, PathBuf},
11    time::Duration,
12};
13use url::Url;
14
15#[cfg(feature = "serde")]
16use jiff::fmt::serde::unsigned_duration::friendly::compact;
17
18#[cfg(feature = "serde")]
19const EXTENSION: &str = "toml";
20
21/// The default prune block interval
22pub const DEFAULT_BLOCK_INTERVAL: usize = 5;
23
24/// Configuration for the reth node.
25#[derive(Debug, Clone, Default, PartialEq, Eq)]
26#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
27#[cfg_attr(feature = "serde", serde(default))]
28pub struct Config {
29    /// Nodes to bootstrap P2P discovery with, as `enode://` URLs or `enr:` records.
30    ///
31    /// Takes precedence over the chain spec bootnodes, and is overridden by `--bootnodes`.
32    pub bootnodes: Vec<TrustedPeer>,
33    /// Configuration for each stage in the pipeline.
34    pub stages: StageConfig,
35    /// Configuration for pruning.
36    #[cfg_attr(feature = "serde", serde(default))]
37    pub prune: PruneConfig,
38    /// Configuration for the discovery service.
39    pub peers: PeersConfig,
40    /// Configuration for peer sessions.
41    pub sessions: SessionsConfig,
42    /// Configuration for static files.
43    #[cfg_attr(feature = "serde", serde(default))]
44    pub static_files: StaticFilesConfig,
45}
46
47impl Config {
48    /// Sets the pruning configuration.
49    pub fn set_prune_config(&mut self, prune_config: PruneConfig) {
50        self.prune = prune_config;
51    }
52}
53
54#[cfg(feature = "serde")]
55impl Config {
56    /// Load a [`Config`] from a specified path.
57    ///
58    /// A new configuration file is created with default values if none
59    /// exists.
60    pub fn from_path(path: impl AsRef<Path>) -> eyre::Result<Self> {
61        Self::from_path_inner(path.as_ref())
62    }
63
64    /// Non-generic body of [`Self::from_path`], so the TOML code compiles once in this crate.
65    fn from_path_inner(path: &Path) -> eyre::Result<Self> {
66        match std::fs::read_to_string(path) {
67            Ok(cfg_string) => {
68                toml::from_str(&cfg_string).map_err(|e| eyre::eyre!("Failed to parse TOML: {e}"))
69            }
70            Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
71                if let Some(parent) = path.parent() {
72                    std::fs::create_dir_all(parent)
73                        .map_err(|e| eyre::eyre!("Failed to create directory: {e}"))?;
74                }
75                let cfg = Self::default();
76                let s = toml::to_string_pretty(&cfg)
77                    .map_err(|e| eyre::eyre!("Failed to serialize to TOML: {e}"))?;
78                std::fs::write(path, s)
79                    .map_err(|e| eyre::eyre!("Failed to write configuration file: {e}"))?;
80                Ok(cfg)
81            }
82            Err(e) => Err(eyre::eyre!("Failed to load configuration: {e}")),
83        }
84    }
85
86    /// Returns the [`PeersConfig`] for the node.
87    ///
88    /// If a peers file is provided, the basic nodes from the file are added to the configuration.
89    pub fn peers_config_with_basic_nodes_from_file(
90        &self,
91        peers_file: Option<&Path>,
92    ) -> PeersConfig {
93        self.peers
94            .clone()
95            .with_basic_nodes_from_file(peers_file)
96            .unwrap_or_else(|_| self.peers.clone())
97    }
98
99    /// Save the configuration to toml file.
100    pub fn save(&self, path: &Path) -> Result<(), std::io::Error> {
101        if path.extension() != Some(std::ffi::OsStr::new(EXTENSION)) {
102            return Err(std::io::Error::new(
103                std::io::ErrorKind::InvalidInput,
104                format!("reth config file extension must be '{EXTENSION}'"),
105            ));
106        }
107
108        std::fs::write(
109            path,
110            toml::to_string(self)
111                .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e.to_string()))?,
112        )
113    }
114}
115
116/// Configuration for each stage in the pipeline.
117#[derive(Debug, Clone, Default, PartialEq, Eq)]
118#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
119#[cfg_attr(feature = "serde", serde(default))]
120pub struct StageConfig {
121    /// ERA stage configuration.
122    pub era: EraConfig,
123    /// Header stage configuration.
124    pub headers: HeadersConfig,
125    /// Body stage configuration.
126    pub bodies: BodiesConfig,
127    /// Sender Recovery stage configuration.
128    pub sender_recovery: SenderRecoveryConfig,
129    /// Execution stage configuration.
130    pub execution: ExecutionConfig,
131    /// Prune stage configuration.
132    pub prune: PruneStageConfig,
133    /// Account Hashing stage configuration.
134    pub account_hashing: HashingConfig,
135    /// Storage Hashing stage configuration.
136    pub storage_hashing: HashingConfig,
137    /// Merkle stage configuration.
138    pub merkle: MerkleConfig,
139    /// Transaction Lookup stage configuration.
140    pub transaction_lookup: TransactionLookupConfig,
141    /// Index Account History stage configuration.
142    pub index_account_history: IndexHistoryConfig,
143    /// Index Storage History stage configuration.
144    pub index_storage_history: IndexHistoryConfig,
145    /// Common ETL related configuration.
146    pub etl: EtlConfig,
147}
148
149impl StageConfig {
150    /// The highest threshold (in number of blocks) for switching between incremental and full
151    /// calculations across `MerkleStage`, `AccountHashingStage` and `StorageHashingStage`. This is
152    /// required to figure out if can prune or not changesets on subsequent pipeline runs during
153    /// `ExecutionStage`
154    pub fn execution_external_clean_threshold(&self) -> u64 {
155        self.merkle
156            .incremental_threshold
157            .max(self.account_hashing.clean_threshold)
158            .max(self.storage_hashing.clean_threshold)
159    }
160}
161
162/// ERA stage configuration.
163#[derive(Debug, Clone, Default, PartialEq, Eq)]
164#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
165#[cfg_attr(feature = "serde", serde(default))]
166pub struct EraConfig {
167    /// Path to a local directory where ERA1 files are located.
168    ///
169    /// Conflicts with `url`.
170    pub path: Option<PathBuf>,
171    /// The base URL of an ERA1 file host to download from.
172    ///
173    /// Conflicts with `path`.
174    pub url: Option<Url>,
175    /// Path to a directory where files downloaded from `url` will be stored until processed.
176    ///
177    /// Required for `url`.
178    pub folder: Option<PathBuf>,
179}
180
181impl EraConfig {
182    /// Sets `folder` for temporary downloads as a directory called "era" inside `dir`.
183    pub fn with_datadir(mut self, dir: impl AsRef<Path>) -> Self {
184        self.folder = Some(dir.as_ref().join("era"));
185        self
186    }
187}
188
189/// Header stage configuration.
190#[derive(Debug, Clone, Copy, PartialEq, Eq)]
191#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
192#[cfg_attr(feature = "serde", serde(default))]
193pub struct HeadersConfig {
194    /// The maximum number of requests to send concurrently.
195    ///
196    /// Default: 100
197    pub downloader_max_concurrent_requests: usize,
198    /// The minimum number of requests to send concurrently.
199    ///
200    /// Default: 5
201    pub downloader_min_concurrent_requests: usize,
202    /// Maximum amount of responses to buffer internally.
203    /// The response contains multiple headers.
204    pub downloader_max_buffered_responses: usize,
205    /// The maximum number of headers to request from a peer at a time.
206    pub downloader_request_limit: u64,
207    /// The maximum number of headers to download before committing progress to the database.
208    pub commit_threshold: u64,
209}
210
211impl Default for HeadersConfig {
212    fn default() -> Self {
213        Self {
214            commit_threshold: 10_000,
215            downloader_request_limit: 1_000,
216            downloader_max_concurrent_requests: 100,
217            downloader_min_concurrent_requests: 5,
218            downloader_max_buffered_responses: 100,
219        }
220    }
221}
222
223/// Body stage configuration.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
226#[cfg_attr(feature = "serde", serde(default))]
227pub struct BodiesConfig {
228    /// The batch size of non-empty blocks per one request
229    ///
230    /// Default: 200
231    pub downloader_request_limit: u64,
232    /// The maximum number of block bodies returned at once from the stream
233    ///
234    /// Default: `1_000`
235    pub downloader_stream_batch_size: usize,
236    /// The size of the internal block buffer in bytes.
237    ///
238    /// Default: 2GB
239    pub downloader_max_buffered_blocks_size_bytes: usize,
240    /// The minimum number of requests to send concurrently.
241    ///
242    /// Default: 5
243    pub downloader_min_concurrent_requests: usize,
244    /// The maximum number of requests to send concurrently.
245    /// This is equal to the max number of peers.
246    ///
247    /// Default: 100
248    pub downloader_max_concurrent_requests: usize,
249}
250
251impl Default for BodiesConfig {
252    fn default() -> Self {
253        Self {
254            downloader_request_limit: 200,
255            downloader_stream_batch_size: 1_000,
256            downloader_max_buffered_blocks_size_bytes: 2 * 1024 * 1024 * 1024, // ~2GB
257            downloader_min_concurrent_requests: 5,
258            downloader_max_concurrent_requests: 100,
259        }
260    }
261}
262
263/// Sender recovery stage configuration.
264#[derive(Debug, Clone, Copy, PartialEq, Eq)]
265#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
266#[cfg_attr(feature = "serde", serde(default))]
267pub struct SenderRecoveryConfig {
268    /// The maximum number of transactions to process before committing progress to the database.
269    pub commit_threshold: u64,
270}
271
272impl Default for SenderRecoveryConfig {
273    fn default() -> Self {
274        Self { commit_threshold: 5_000_000 }
275    }
276}
277
278/// Execution stage configuration.
279#[derive(Debug, Clone, Copy, PartialEq, Eq)]
280#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
281#[cfg_attr(feature = "serde", serde(default))]
282pub struct ExecutionConfig {
283    /// The maximum number of blocks to process before the execution stage commits.
284    pub max_blocks: Option<u64>,
285    /// The maximum number of state changes to keep in memory before the execution stage commits.
286    pub max_changes: Option<u64>,
287    /// The maximum cumulative amount of gas to process before the execution stage commits.
288    pub max_cumulative_gas: Option<u64>,
289    /// The maximum time spent on blocks processing before the execution stage commits.
290    #[cfg_attr(
291        feature = "serde",
292        serde(
293            serialize_with = "compact::optional::serialize",
294            deserialize_with = "deserialize_duration"
295        )
296    )]
297    pub max_duration: Option<Duration>,
298}
299
300impl Default for ExecutionConfig {
301    fn default() -> Self {
302        Self {
303            max_blocks: Some(500_000),
304            max_changes: Some(5_000_000),
305            // 50k full blocks of 30M gas
306            max_cumulative_gas: Some(30_000_000 * 50_000),
307            // 10 minutes
308            max_duration: Some(Duration::from_secs(10 * 60)),
309        }
310    }
311}
312
313impl From<ExecutionConfig> for ExecutionStageThresholds {
314    fn from(config: ExecutionConfig) -> Self {
315        Self {
316            max_blocks: config.max_blocks,
317            max_changes: config.max_changes,
318            max_cumulative_gas: config.max_cumulative_gas,
319            max_duration: config.max_duration,
320        }
321    }
322}
323
324/// Prune stage configuration.
325#[derive(Debug, Clone, Copy, PartialEq, Eq)]
326#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
327#[cfg_attr(feature = "serde", serde(default))]
328pub struct PruneStageConfig {
329    /// The maximum number of entries to prune before committing progress to the database.
330    pub commit_threshold: usize,
331}
332
333impl Default for PruneStageConfig {
334    fn default() -> Self {
335        Self { commit_threshold: 1_000_000 }
336    }
337}
338
339/// Hashing stage configuration.
340#[derive(Debug, Clone, Copy, PartialEq, Eq)]
341#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
342#[cfg_attr(feature = "serde", serde(default))]
343pub struct HashingConfig {
344    /// The threshold (in number of blocks) for switching between
345    /// incremental hashing and full hashing.
346    pub clean_threshold: u64,
347    /// The maximum number of entities to process before committing progress to the database.
348    pub commit_threshold: u64,
349    /// The maximum number of changeset entries to process before committing progress. The stage
350    /// commits after either `commit_threshold` blocks or `commit_entries` entries, whichever
351    /// comes first. This bounds memory usage when blocks contain many state changes.
352    pub commit_entries: u64,
353}
354
355impl Default for HashingConfig {
356    fn default() -> Self {
357        Self { clean_threshold: 500_000, commit_threshold: 100_000, commit_entries: 30_000_000 }
358    }
359}
360
361/// Merkle stage configuration.
362#[derive(Debug, Clone, Copy, PartialEq, Eq)]
363#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
364#[cfg_attr(feature = "serde", serde(default))]
365pub struct MerkleConfig {
366    /// The number of blocks we will run the incremental root method for when we are catching up on
367    /// the merkle stage for a large number of blocks.
368    ///
369    /// When we are catching up for a large number of blocks, we can only run the incremental root
370    /// for a limited number of blocks, otherwise the incremental root method may cause the node to
371    /// OOM. This number determines how many blocks in a row we will run the incremental root
372    /// method for.
373    pub incremental_threshold: u64,
374    /// The threshold (in number of blocks) for switching from incremental trie building of changes
375    /// to whole rebuild.
376    pub rebuild_threshold: u64,
377}
378
379impl Default for MerkleConfig {
380    fn default() -> Self {
381        Self { incremental_threshold: 7_000, rebuild_threshold: 100_000 }
382    }
383}
384
385/// Transaction Lookup stage configuration.
386#[derive(Debug, Clone, Copy, PartialEq, Eq)]
387#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
388#[cfg_attr(feature = "serde", serde(default))]
389pub struct TransactionLookupConfig {
390    /// The maximum number of transactions to process before writing to disk.
391    pub chunk_size: u64,
392}
393
394impl Default for TransactionLookupConfig {
395    fn default() -> Self {
396        Self { chunk_size: 5_000_000 }
397    }
398}
399
400/// Common ETL related configuration.
401#[derive(Debug, Clone, PartialEq, Eq)]
402#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
403#[cfg_attr(feature = "serde", serde(default))]
404pub struct EtlConfig {
405    /// Data directory where temporary files are created.
406    pub dir: Option<PathBuf>,
407    /// The maximum size in bytes of data held in memory before being flushed to disk as a file.
408    pub file_size: usize,
409}
410
411impl Default for EtlConfig {
412    fn default() -> Self {
413        Self { dir: None, file_size: Self::default_file_size() }
414    }
415}
416
417impl EtlConfig {
418    /// Creates an ETL configuration
419    pub const fn new(dir: Option<PathBuf>, file_size: usize) -> Self {
420        Self { dir, file_size }
421    }
422
423    /// Return default ETL directory from datadir path.
424    pub fn from_datadir(path: &Path) -> PathBuf {
425        path.join("etl-tmp")
426    }
427
428    /// Default size in bytes of data held in memory before being flushed to disk as a file.
429    pub const fn default_file_size() -> usize {
430        // 500 MB
431        500 * (1024 * 1024)
432    }
433}
434
435/// Static files configuration.
436#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
437#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
438#[cfg_attr(feature = "serde", serde(default))]
439pub struct StaticFilesConfig {
440    /// Number of blocks per file for each segment.
441    pub blocks_per_file: BlocksPerFileConfig,
442}
443
444/// Configuration for the number of blocks per file for each segment.
445#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
446#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
447#[cfg_attr(feature = "serde", serde(default))]
448pub struct BlocksPerFileConfig {
449    /// Number of blocks per file for the headers segment.
450    pub headers: Option<u64>,
451    /// Number of blocks per file for the transactions segment.
452    pub transactions: Option<u64>,
453    /// Number of blocks per file for the receipts segment.
454    pub receipts: Option<u64>,
455    /// Number of blocks per file for the transaction senders segment.
456    pub transaction_senders: Option<u64>,
457    /// Number of blocks per file for the account changesets segment.
458    pub account_change_sets: Option<u64>,
459    /// Number of blocks per file for the storage changesets segment.
460    pub storage_change_sets: Option<u64>,
461}
462
463impl StaticFilesConfig {
464    /// Validates the static files configuration.
465    ///
466    /// Returns an error if any blocks per file value is zero.
467    pub fn validate(&self) -> eyre::Result<()> {
468        let BlocksPerFileConfig {
469            headers,
470            transactions,
471            receipts,
472            transaction_senders,
473            account_change_sets,
474            storage_change_sets,
475        } = self.blocks_per_file;
476        eyre::ensure!(headers != Some(0), "Headers segment blocks per file must be greater than 0");
477        eyre::ensure!(
478            transactions != Some(0),
479            "Transactions segment blocks per file must be greater than 0"
480        );
481        eyre::ensure!(
482            receipts != Some(0),
483            "Receipts segment blocks per file must be greater than 0"
484        );
485        eyre::ensure!(
486            transaction_senders != Some(0),
487            "Transaction senders segment blocks per file must be greater than 0"
488        );
489        eyre::ensure!(
490            account_change_sets != Some(0),
491            "Account changesets segment blocks per file must be greater than 0"
492        );
493        eyre::ensure!(
494            storage_change_sets != Some(0),
495            "Storage changesets segment blocks per file must be greater than 0"
496        );
497        Ok(())
498    }
499
500    /// Converts the blocks per file configuration into a [`StaticFileMap`].
501    pub fn as_blocks_per_file_map(&self) -> StaticFileMap<u64> {
502        let BlocksPerFileConfig {
503            headers,
504            transactions,
505            receipts,
506            transaction_senders,
507            account_change_sets,
508            storage_change_sets,
509        } = self.blocks_per_file;
510
511        let mut map = StaticFileMap::default();
512        // Iterating over all possible segments allows us to do an exhaustive match here,
513        // to not forget to configure new segments in the future.
514        for segment in StaticFileSegment::iter() {
515            let blocks_per_file = match segment {
516                StaticFileSegment::Headers => headers,
517                StaticFileSegment::Transactions => transactions,
518                StaticFileSegment::Receipts => receipts,
519                StaticFileSegment::TransactionSenders => transaction_senders,
520                StaticFileSegment::AccountChangeSets => account_change_sets,
521                StaticFileSegment::StorageChangeSets => storage_change_sets,
522            };
523
524            if let Some(blocks_per_file) = blocks_per_file {
525                map.insert(segment, blocks_per_file);
526            }
527        }
528        map
529    }
530
531    /// Returns the configured block counts for new files. When receipts are pruned by distance,
532    /// an unset receipt file size is derived from that distance because pruning deletes whole
533    /// files.
534    pub fn blocks_per_file_with_pruning(
535        &self,
536        receipts_prune_mode: Option<PruneMode>,
537    ) -> StaticFileMap<u64> {
538        let mut sizes = self.as_blocks_per_file_map();
539        if let Some(PruneMode::Distance(distance)) = receipts_prune_mode {
540            sizes
541                .entry(StaticFileSegment::Receipts)
542                .or_insert_with(|| blocks_per_file_for_prune_distance(distance));
543        }
544        sizes
545    }
546}
547
548/// History stage configuration.
549#[derive(Debug, Clone, Copy, PartialEq, Eq)]
550#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
551#[cfg_attr(feature = "serde", serde(default))]
552pub struct IndexHistoryConfig {
553    /// The maximum number of blocks to process before committing progress to the database.
554    pub commit_threshold: u64,
555}
556
557impl Default for IndexHistoryConfig {
558    fn default() -> Self {
559        Self { commit_threshold: 100_000 }
560    }
561}
562
563/// Pruning configuration.
564#[derive(Debug, Clone, PartialEq, Eq)]
565#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
566#[cfg_attr(feature = "serde", serde(default))]
567pub struct PruneConfig {
568    /// Minimum pruning interval measured in blocks.
569    pub block_interval: usize,
570    /// Pruning configuration for every part of the data that can be pruned.
571    #[cfg_attr(feature = "serde", serde(alias = "parts"))]
572    pub segments: PruneModes,
573    /// Minimum distance from the tip required for pruning. Controls the safety margin for
574    /// reorgs and manual unwinds. Defaults to [`MINIMUM_UNWIND_SAFE_DISTANCE`].
575    #[cfg_attr(feature = "serde", serde(default = "default_minimum_pruning_distance"))]
576    pub minimum_pruning_distance: u64,
577}
578
579/// Returns the default minimum pruning distance.
580const fn default_minimum_pruning_distance() -> u64 {
581    MINIMUM_UNWIND_SAFE_DISTANCE
582}
583
584impl Default for PruneConfig {
585    fn default() -> Self {
586        Self {
587            block_interval: DEFAULT_BLOCK_INTERVAL,
588            segments: PruneModes::default(),
589            minimum_pruning_distance: MINIMUM_UNWIND_SAFE_DISTANCE,
590        }
591    }
592}
593
594impl PruneConfig {
595    /// Returns whether this configuration is the default one.
596    pub fn is_default(&self) -> bool {
597        self == &Self::default()
598    }
599
600    /// Returns whether there is any kind of receipt pruning configuration.
601    pub fn has_receipts_pruning(&self) -> bool {
602        self.segments.has_receipts_pruning()
603    }
604
605    /// Merges values from `other` into `self`.
606    /// - `Option<PruneMode>` fields: set from `other` only if `self` is `None`.
607    /// - `block_interval`: set from `other` only if `self.block_interval ==
608    ///   DEFAULT_BLOCK_INTERVAL`.
609    /// - `receipts_log_filter`: set from `other` only if `self` is empty and `other` is non-empty.
610    pub fn merge(&mut self, other: Self) {
611        let Self {
612            block_interval,
613            segments:
614                PruneModes {
615                    sender_recovery,
616                    transaction_lookup,
617                    receipts,
618                    account_history,
619                    storage_history,
620                    bodies_history,
621                    receipts_log_filter,
622                },
623            minimum_pruning_distance,
624        } = other;
625
626        // Merge block_interval, only update if it's the default interval
627        if self.block_interval == DEFAULT_BLOCK_INTERVAL {
628            self.block_interval = block_interval;
629        }
630
631        // Merge minimum_pruning_distance, only update if it's the default
632        if self.minimum_pruning_distance == MINIMUM_UNWIND_SAFE_DISTANCE {
633            self.minimum_pruning_distance = minimum_pruning_distance;
634        }
635
636        // Merge the various segment prune modes
637        self.segments.sender_recovery = self.segments.sender_recovery.or(sender_recovery);
638        self.segments.transaction_lookup = self.segments.transaction_lookup.or(transaction_lookup);
639        self.segments.receipts = self.segments.receipts.or(receipts);
640        self.segments.account_history = self.segments.account_history.or(account_history);
641        self.segments.storage_history = self.segments.storage_history.or(storage_history);
642        self.segments.bodies_history = self.segments.bodies_history.or(bodies_history);
643
644        if self.segments.receipts_log_filter.0.is_empty() && !receipts_log_filter.0.is_empty() {
645            self.segments.receipts_log_filter = receipts_log_filter;
646        }
647    }
648}
649
650/// Helper type to support older versions of Duration deserialization.
651#[cfg(feature = "serde")]
652fn deserialize_duration<'de, D>(deserializer: D) -> Result<Option<Duration>, D::Error>
653where
654    D: serde::de::Deserializer<'de>,
655{
656    #[derive(serde::Deserialize)]
657    #[serde(untagged)]
658    enum AnyDuration {
659        #[serde(deserialize_with = "compact::optional::deserialize")]
660        Human(Option<Duration>),
661        Duration(Option<Duration>),
662    }
663
664    <AnyDuration as serde::Deserialize>::deserialize(deserializer).map(|d| match d {
665        AnyDuration::Human(duration) | AnyDuration::Duration(duration) => duration,
666    })
667}
668
669#[cfg(all(test, feature = "serde"))]
670mod tests {
671    use super::{Config, EXTENSION};
672    use crate::PruneConfig;
673    use alloy_primitives::Address;
674    use reth_network_peers::TrustedPeer;
675    use reth_prune_types::{
676        PruneMode, PruneModes, ReceiptsLogPruneConfig, MINIMUM_UNWIND_SAFE_DISTANCE,
677    };
678    use std::{collections::BTreeMap, path::Path, str::FromStr, time::Duration};
679
680    fn with_tempdir(filename: &str, proc: fn(&std::path::Path)) {
681        let temp_dir = tempfile::tempdir().unwrap();
682        let config_path = temp_dir.path().join(filename).with_extension(EXTENSION);
683
684        proc(&config_path);
685
686        temp_dir.close().unwrap()
687    }
688
689    /// Run a test function with a temporary config path as fixture.
690    fn with_config_path(test_fn: fn(&Path)) {
691        // Create a temporary directory for the config file
692        let config_dir = tempfile::tempdir().expect("creating test fixture failed");
693        // Create the config file path
694        let config_path =
695            config_dir.path().join("example-app").join("example-config").with_extension("toml");
696        // Run the test function with the config path
697        test_fn(&config_path);
698        config_dir.close().expect("removing test fixture failed");
699    }
700
701    #[test]
702    fn test_load_path_works() {
703        with_config_path(|path| {
704            let config = Config::from_path(path).expect("load_path failed");
705            assert_eq!(config, Config::default());
706        })
707    }
708
709    #[test]
710    fn test_load_path_reads_existing_config() {
711        with_config_path(|path| {
712            let config = Config::default();
713
714            // Create the parent directory if it doesn't exist
715            if let Some(parent) = path.parent() {
716                std::fs::create_dir_all(parent).expect("Failed to create directories");
717            }
718
719            // Write the config to the file
720            std::fs::write(path, toml::to_string(&config).unwrap())
721                .expect("Failed to write config");
722
723            // Load the config from the file and compare it
724            let loaded = Config::from_path(path).expect("load_path failed");
725            assert_eq!(config, loaded);
726        })
727    }
728
729    #[test]
730    fn test_load_path_fails_on_invalid_toml() {
731        with_config_path(|path| {
732            let invalid_toml = "invalid toml data";
733
734            // Create the parent directory if it doesn't exist
735            if let Some(parent) = path.parent() {
736                std::fs::create_dir_all(parent).expect("Failed to create directories");
737            }
738
739            // Write invalid TOML data to the file
740            std::fs::write(path, invalid_toml).expect("Failed to write invalid TOML");
741
742            // Attempt to load the config should fail
743            let result = Config::from_path(path);
744            assert!(result.is_err());
745        })
746    }
747
748    #[test]
749    fn test_load_path_creates_directory_if_not_exists() {
750        with_config_path(|path| {
751            // Ensure the directory does not exist
752            let parent = path.parent().unwrap();
753            assert!(!parent.exists());
754
755            // Load the configuration, which should create the directory and a default config file
756            let config = Config::from_path(path).expect("load_path failed");
757            assert_eq!(config, Config::default());
758
759            // The directory and file should now exist
760            assert!(parent.exists());
761            assert!(path.exists());
762        });
763    }
764
765    #[test]
766    fn test_store_config() {
767        with_tempdir("config-store-test", |config_path| {
768            let config = Config::default();
769            std::fs::write(
770                config_path,
771                toml::to_string(&config).expect("Failed to serialize config"),
772            )
773            .expect("Failed to write config file");
774        })
775    }
776
777    #[test]
778    fn test_store_config_method() {
779        with_tempdir("config-store-test-method", |config_path| {
780            let config = Config::default();
781            config.save(config_path).expect("Failed to store config");
782        })
783    }
784
785    #[test]
786    fn test_load_config() {
787        with_tempdir("config-load-test", |config_path| {
788            let config = Config::default();
789
790            // Write the config to a file
791            std::fs::write(
792                config_path,
793                toml::to_string(&config).expect("Failed to serialize config"),
794            )
795            .expect("Failed to write config file");
796
797            // Load the config from the file
798            let loaded_config = Config::from_path(config_path).unwrap();
799
800            // Compare the loaded config with the original config
801            assert_eq!(config, loaded_config);
802        })
803    }
804
805    #[test]
806    fn test_load_execution_stage() {
807        with_tempdir("config-load-test", |config_path| {
808            let mut config = Config::default();
809            config.stages.execution.max_duration = Some(Duration::from_secs(10 * 60));
810
811            // Write the config to a file
812            std::fs::write(
813                config_path,
814                toml::to_string(&config).expect("Failed to serialize config"),
815            )
816            .expect("Failed to write config file");
817
818            // Load the config from the file
819            let loaded_config = Config::from_path(config_path).unwrap();
820
821            // Compare the loaded config with the original config
822            assert_eq!(config, loaded_config);
823        })
824    }
825
826    // ensures config deserialization is backwards compatible
827    #[test]
828    fn test_backwards_compatibility() {
829        let alpha_0_0_8 = r"#
830[stages.headers]
831downloader_max_concurrent_requests = 100
832downloader_min_concurrent_requests = 5
833downloader_max_buffered_responses = 100
834downloader_request_limit = 1000
835commit_threshold = 10000
836
837[stages.bodies]
838downloader_request_limit = 200
839downloader_stream_batch_size = 1000
840downloader_max_buffered_blocks_size_bytes = 2147483648
841downloader_min_concurrent_requests = 5
842downloader_max_concurrent_requests = 100
843
844[stages.sender_recovery]
845commit_threshold = 5000000
846
847[stages.execution]
848max_blocks = 500000
849max_changes = 5000000
850
851[stages.account_hashing]
852clean_threshold = 500000
853commit_threshold = 100000
854
855[stages.storage_hashing]
856clean_threshold = 500000
857commit_threshold = 100000
858
859[stages.merkle]
860clean_threshold = 50000
861
862[stages.transaction_lookup]
863chunk_size = 5000000
864
865[stages.index_account_history]
866commit_threshold = 100000
867
868[stages.index_storage_history]
869commit_threshold = 100000
870
871[peers]
872refill_slots_interval = '1s'
873trusted_nodes = []
874connect_trusted_nodes_only = false
875max_backoff_count = 5
876ban_duration = '12h'
877
878[peers.connection_info]
879max_outbound = 100
880max_inbound = 30
881
882[peers.reputation_weights]
883bad_message = -16384
884bad_block = -16384
885bad_transactions = -16384
886already_seen_transactions = 0
887timeout = -4096
888bad_protocol = -2147483648
889failed_to_connect = -25600
890dropped = -4096
891
892[peers.backoff_durations]
893low = '30s'
894medium = '3m'
895high = '15m'
896max = '1h'
897
898[sessions]
899session_command_buffer = 32
900session_event_buffer = 260
901
902[sessions.limits]
903
904[sessions.initial_internal_request_timeout]
905secs = 20
906nanos = 0
907
908[sessions.protocol_breach_request_timeout]
909secs = 120
910nanos = 0
911
912[prune]
913block_interval = 5
914
915[prune.parts]
916sender_recovery = { distance = 16384 }
917transaction_lookup = 'full'
918receipts = { before = 1920000 }
919account_history = { distance = 16384 }
920storage_history = { distance = 16384 }
921[prune.parts.receipts_log_filter]
922'0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' = { before = 17000000 }
923'0xdac17f958d2ee523a2206206994597c13d831ec7' = { distance = 1000 }
924#";
925        let _conf: Config = toml::from_str(alpha_0_0_8).unwrap();
926
927        let alpha_0_0_11 = r"#
928[prune.segments]
929sender_recovery = { distance = 16384 }
930transaction_lookup = 'full'
931receipts = { before = 1920000 }
932account_history = { distance = 16384 }
933storage_history = { distance = 16384 }
934[prune.segments.receipts_log_filter]
935'0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48' = { before = 17000000 }
936'0xdac17f958d2ee523a2206206994597c13d831ec7' = { distance = 1000 }
937#";
938        let _conf: Config = toml::from_str(alpha_0_0_11).unwrap();
939
940        let alpha_0_0_18 = r"#
941[stages.headers]
942downloader_max_concurrent_requests = 100
943downloader_min_concurrent_requests = 5
944downloader_max_buffered_responses = 100
945downloader_request_limit = 1000
946commit_threshold = 10000
947
948[stages.total_difficulty]
949commit_threshold = 100000
950
951[stages.bodies]
952downloader_request_limit = 200
953downloader_stream_batch_size = 1000
954downloader_max_buffered_blocks_size_bytes = 2147483648
955downloader_min_concurrent_requests = 5
956downloader_max_concurrent_requests = 100
957
958[stages.sender_recovery]
959commit_threshold = 5000000
960
961[stages.execution]
962max_blocks = 500000
963max_changes = 5000000
964max_cumulative_gas = 1500000000000
965[stages.execution.max_duration]
966secs = 600
967nanos = 0
968
969[stages.account_hashing]
970clean_threshold = 500000
971commit_threshold = 100000
972
973[stages.storage_hashing]
974clean_threshold = 500000
975commit_threshold = 100000
976
977[stages.merkle]
978clean_threshold = 50000
979
980[stages.transaction_lookup]
981commit_threshold = 5000000
982
983[stages.index_account_history]
984commit_threshold = 100000
985
986[stages.index_storage_history]
987commit_threshold = 100000
988
989[peers]
990refill_slots_interval = '5s'
991trusted_nodes = []
992connect_trusted_nodes_only = false
993max_backoff_count = 5
994ban_duration = '12h'
995
996[peers.connection_info]
997max_outbound = 100
998max_inbound = 30
999max_concurrent_outbound_dials = 10
1000
1001[peers.reputation_weights]
1002bad_message = -16384
1003bad_block = -16384
1004bad_transactions = -16384
1005already_seen_transactions = 0
1006timeout = -4096
1007bad_protocol = -2147483648
1008failed_to_connect = -25600
1009dropped = -4096
1010bad_announcement = -1024
1011
1012[peers.backoff_durations]
1013low = '30s'
1014medium = '3m'
1015high = '15m'
1016max = '1h'
1017
1018[sessions]
1019session_command_buffer = 32
1020session_event_buffer = 260
1021
1022[sessions.limits]
1023
1024[sessions.initial_internal_request_timeout]
1025secs = 20
1026nanos = 0
1027
1028[sessions.protocol_breach_request_timeout]
1029secs = 120
1030nanos = 0
1031#";
1032        let conf: Config = toml::from_str(alpha_0_0_18).unwrap();
1033        assert_eq!(conf.stages.execution.max_duration, Some(Duration::from_secs(10 * 60)));
1034
1035        let alpha_0_0_19 = r"#
1036[stages.headers]
1037downloader_max_concurrent_requests = 100
1038downloader_min_concurrent_requests = 5
1039downloader_max_buffered_responses = 100
1040downloader_request_limit = 1000
1041commit_threshold = 10000
1042
1043[stages.total_difficulty]
1044commit_threshold = 100000
1045
1046[stages.bodies]
1047downloader_request_limit = 200
1048downloader_stream_batch_size = 1000
1049downloader_max_buffered_blocks_size_bytes = 2147483648
1050downloader_min_concurrent_requests = 5
1051downloader_max_concurrent_requests = 100
1052
1053[stages.sender_recovery]
1054commit_threshold = 5000000
1055
1056[stages.execution]
1057max_blocks = 500000
1058max_changes = 5000000
1059max_cumulative_gas = 1500000000000
1060max_duration = '10m'
1061
1062[stages.account_hashing]
1063clean_threshold = 500000
1064commit_threshold = 100000
1065
1066[stages.storage_hashing]
1067clean_threshold = 500000
1068commit_threshold = 100000
1069
1070[stages.merkle]
1071clean_threshold = 50000
1072
1073[stages.transaction_lookup]
1074commit_threshold = 5000000
1075
1076[stages.index_account_history]
1077commit_threshold = 100000
1078
1079[stages.index_storage_history]
1080commit_threshold = 100000
1081
1082[peers]
1083refill_slots_interval = '5s'
1084trusted_nodes = []
1085connect_trusted_nodes_only = false
1086max_backoff_count = 5
1087ban_duration = '12h'
1088
1089[peers.connection_info]
1090max_outbound = 100
1091max_inbound = 30
1092max_concurrent_outbound_dials = 10
1093
1094[peers.reputation_weights]
1095bad_message = -16384
1096bad_block = -16384
1097bad_transactions = -16384
1098already_seen_transactions = 0
1099timeout = -4096
1100bad_protocol = -2147483648
1101failed_to_connect = -25600
1102dropped = -4096
1103bad_announcement = -1024
1104
1105[peers.backoff_durations]
1106low = '30s'
1107medium = '3m'
1108high = '15m'
1109max = '1h'
1110
1111[sessions]
1112session_command_buffer = 32
1113session_event_buffer = 260
1114
1115[sessions.limits]
1116
1117[sessions.initial_internal_request_timeout]
1118secs = 20
1119nanos = 0
1120
1121[sessions.protocol_breach_request_timeout]
1122secs = 120
1123nanos = 0
1124#";
1125        let _conf: Config = toml::from_str(alpha_0_0_19).unwrap();
1126    }
1127
1128    // ensures prune config deserialization is backwards compatible
1129    #[test]
1130    fn test_backwards_compatibility_prune_full() {
1131        let s = r"#
1132[prune]
1133block_interval = 5
1134
1135[prune.segments]
1136sender_recovery = { distance = 16384 }
1137transaction_lookup = 'full'
1138receipts = { distance = 16384 }
1139#";
1140        let _conf: Config = toml::from_str(s).unwrap();
1141    }
1142
1143    #[test]
1144    fn test_prune_config_merge() {
1145        let mut config1 = PruneConfig {
1146            block_interval: 5,
1147            minimum_pruning_distance: MINIMUM_UNWIND_SAFE_DISTANCE,
1148            segments: PruneModes {
1149                sender_recovery: Some(PruneMode::Full),
1150                transaction_lookup: None,
1151                receipts: Some(PruneMode::Distance(1000)),
1152                account_history: None,
1153                storage_history: Some(PruneMode::Before(5000)),
1154                bodies_history: None,
1155                receipts_log_filter: ReceiptsLogPruneConfig(BTreeMap::from([(
1156                    Address::random(),
1157                    PruneMode::Full,
1158                )])),
1159            },
1160        };
1161
1162        let config2 = PruneConfig {
1163            block_interval: 10,
1164            minimum_pruning_distance: MINIMUM_UNWIND_SAFE_DISTANCE,
1165            segments: PruneModes {
1166                sender_recovery: Some(PruneMode::Distance(500)),
1167                transaction_lookup: Some(PruneMode::Full),
1168                receipts: Some(PruneMode::Full),
1169                account_history: Some(PruneMode::Distance(2000)),
1170                storage_history: Some(PruneMode::Distance(3000)),
1171                bodies_history: None,
1172                receipts_log_filter: ReceiptsLogPruneConfig(BTreeMap::from([
1173                    (Address::random(), PruneMode::Distance(1000)),
1174                    (Address::random(), PruneMode::Before(2000)),
1175                ])),
1176            },
1177        };
1178
1179        let original_filter = config1.segments.receipts_log_filter.clone();
1180        config1.merge(config2);
1181
1182        // Check that the configuration has been merged. Any configuration present in config1
1183        // should not be overwritten by config2
1184        assert_eq!(config1.block_interval, 10);
1185        assert_eq!(config1.segments.sender_recovery, Some(PruneMode::Full));
1186        assert_eq!(config1.segments.transaction_lookup, Some(PruneMode::Full));
1187        assert_eq!(config1.segments.receipts, Some(PruneMode::Distance(1000)));
1188        assert_eq!(config1.segments.account_history, Some(PruneMode::Distance(2000)));
1189        assert_eq!(config1.segments.storage_history, Some(PruneMode::Before(5000)));
1190        assert_eq!(config1.segments.receipts_log_filter, original_filter);
1191    }
1192
1193    #[test]
1194    fn test_conf_trust_nodes_only() {
1195        let trusted_nodes_only = r"#
1196[peers]
1197trusted_nodes_only = true
1198#";
1199        let conf: Config = toml::from_str(trusted_nodes_only).unwrap();
1200        assert!(conf.peers.trusted_nodes_only);
1201
1202        let trusted_nodes_only = r"#
1203[peers]
1204connect_trusted_nodes_only = true
1205#";
1206        let conf: Config = toml::from_str(trusted_nodes_only).unwrap();
1207        assert!(conf.peers.trusted_nodes_only);
1208    }
1209
1210    #[test]
1211    fn test_can_support_dns_in_trusted_nodes() {
1212        let reth_toml = r#"
1213    [peers]
1214    trusted_nodes = [
1215        "enode://0401e494dbd0c84c5c0f72adac5985d2f2525e08b68d448958aae218f5ac8198a80d1498e0ebec2ce38b1b18d6750f6e61a56b4614c5a6c6cf0981c39aed47dc@34.159.32.127:30303",
1216        "enode://e9675164b5e17b9d9edf0cc2bd79e6b6f487200c74d1331c220abb5b8ee80c2eefbf18213989585e9d0960683e819542e11d4eefb5f2b4019e1e49f9fd8fff18@berav2-bootnode.staketab.org:30303"
1217    ]
1218    "#;
1219
1220        let conf: Config = toml::from_str(reth_toml).unwrap();
1221        assert_eq!(conf.peers.trusted_nodes.len(), 2);
1222
1223        let expected_enodes = vec![
1224            "enode://0401e494dbd0c84c5c0f72adac5985d2f2525e08b68d448958aae218f5ac8198a80d1498e0ebec2ce38b1b18d6750f6e61a56b4614c5a6c6cf0981c39aed47dc@34.159.32.127:30303",
1225            "enode://e9675164b5e17b9d9edf0cc2bd79e6b6f487200c74d1331c220abb5b8ee80c2eefbf18213989585e9d0960683e819542e11d4eefb5f2b4019e1e49f9fd8fff18@berav2-bootnode.staketab.org:30303",
1226        ];
1227
1228        for enode in expected_enodes {
1229            let node = TrustedPeer::from_str(enode).unwrap();
1230            assert!(conf.peers.trusted_nodes.contains(&node));
1231        }
1232    }
1233
1234    #[test]
1235    fn test_bootnodes() {
1236        let reth_toml = r#"
1237    bootnodes = [
1238        "enode://0401e494dbd0c84c5c0f72adac5985d2f2525e08b68d448958aae218f5ac8198a80d1498e0ebec2ce38b1b18d6750f6e61a56b4614c5a6c6cf0981c39aed47dc@34.159.32.127:30303",
1239        "enode://e9675164b5e17b9d9edf0cc2bd79e6b6f487200c74d1331c220abb5b8ee80c2eefbf18213989585e9d0960683e819542e11d4eefb5f2b4019e1e49f9fd8fff18@berav2-bootnode.staketab.org:30303",
1240        "enr:-IS4QHCYrYZbAKWCBRlAy5zzaDZXJBGkcnh4MHcBFZntXNFrdvJjX04jRzjzCBOonrkTfj499SZuOh8R33Ls8RRcy5wBgmlkgnY0gmlwhH8AAAGJc2VjcDI1NmsxoQPKY0yuDUmstAHYpMa2_oxVtw0RW_QAdpzBQA8yWM0xOIN1ZHCCdl8"
1241    ]
1242    "#;
1243
1244        let conf: Config = toml::from_str(reth_toml).unwrap();
1245        assert_eq!(conf.bootnodes.len(), 3);
1246        assert_eq!(
1247            conf.bootnodes[1].host,
1248            url::Host::<String>::Domain("berav2-bootnode.staketab.org".to_string())
1249        );
1250        // the ENR omits the tcp key, so the udp port is used for the RLPx dial guess
1251        assert_eq!(
1252            conf.bootnodes[2],
1253            TrustedPeer::from_str("enode://ca634cae0d49acb401d8a4c6b6fe8c55b70d115bf400769cc1400f3258cd31387574077f301b421bc84df7266c44e9e6d569fc56be00812904767bf5ccd1fc7f@127.0.0.1:30303").unwrap()
1254        );
1255
1256        // bootnodes are written back as enode URLs, including the ones read as ENRs
1257        let serialized = toml::to_string(&conf).unwrap();
1258        assert_eq!(toml::from_str::<Config>(&serialized).unwrap(), conf);
1259    }
1260}