Skip to main content

reth_rpc_server_types/
module.rs

1use std::{collections::HashSet, fmt, str::FromStr};
2
3use serde::{Deserialize, Serialize, Serializer};
4use strum::{ParseError, VariantNames};
5
6/// Describes the modules that should be installed.
7///
8/// # Example
9///
10/// Create a [`RpcModuleSelection`] from a selection.
11///
12/// ```
13/// use reth_rpc_server_types::{RethRpcModule, RpcModuleSelection};
14/// let config: RpcModuleSelection = vec![RethRpcModule::Eth].into();
15/// ```
16#[derive(Debug, Default, Clone, Eq, PartialEq)]
17pub enum RpcModuleSelection {
18    /// Use all modules except `testing`, which requires an explicit selection.
19    All,
20    /// The default modules `eth`, `net`, `web3`
21    #[default]
22    Standard,
23    /// Only use the configured modules.
24    Selection(HashSet<RethRpcModule>),
25}
26
27// === impl RpcModuleSelection ===
28
29impl RpcModuleSelection {
30    /// The standard modules to instantiate by default `eth`, `net`, `web3`
31    pub const STANDARD_MODULES: [RethRpcModule; 3] =
32        [RethRpcModule::Eth, RethRpcModule::Net, RethRpcModule::Web3];
33
34    /// Returns all modules that do not require an explicit selection.
35    pub fn all_modules() -> HashSet<RethRpcModule> {
36        Self::all_modules_iter().collect()
37    }
38
39    /// Returns the [`RpcModuleSelection::STANDARD_MODULES`] as a selection.
40    pub fn standard_modules() -> HashSet<RethRpcModule> {
41        HashSet::from(Self::STANDARD_MODULES)
42    }
43
44    /// All modules that are available by default on IPC, excluding `testing`.
45    pub fn default_ipc_modules() -> HashSet<RethRpcModule> {
46        Self::all_modules()
47    }
48
49    /// Creates a new _unique_ [`RpcModuleSelection::Selection`] from the given items.
50    ///
51    /// # Note
52    ///
53    /// This will dedupe the selection and remove duplicates while preserving the order.
54    ///
55    /// # Example
56    ///
57    /// Create a selection from the [`RethRpcModule`] string identifiers
58    ///
59    /// ```
60    /// use reth_rpc_server_types::{RethRpcModule, RpcModuleSelection};
61    /// let selection = vec!["eth", "admin"];
62    /// let config = RpcModuleSelection::try_from_selection(selection).unwrap();
63    /// assert_eq!(config, RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Admin]));
64    /// ```
65    ///
66    /// Create a unique selection from the [`RethRpcModule`] string identifiers
67    ///
68    /// ```
69    /// use reth_rpc_server_types::{RethRpcModule, RpcModuleSelection};
70    /// let selection = vec!["eth", "admin", "eth", "admin"];
71    /// let config = RpcModuleSelection::try_from_selection(selection).unwrap();
72    /// assert_eq!(config, RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Admin]));
73    /// ```
74    pub fn try_from_selection<I, T>(selection: I) -> Result<Self, T::Error>
75    where
76        I: IntoIterator<Item = T>,
77        T: TryInto<RethRpcModule>,
78    {
79        selection.into_iter().map(TryInto::try_into).collect()
80    }
81
82    /// Returns the number of modules in the selection
83    pub fn len(&self) -> usize {
84        match self {
85            Self::All => Self::all_modules_iter().count(),
86            Self::Standard => Self::STANDARD_MODULES.len(),
87            Self::Selection(s) => s.len(),
88        }
89    }
90
91    /// Returns true if no selection is configured
92    pub fn is_empty(&self) -> bool {
93        match self {
94            Self::Selection(sel) => sel.is_empty(),
95            _ => false,
96        }
97    }
98
99    /// Returns true if all modules are selected
100    pub const fn is_all(&self) -> bool {
101        matches!(self, Self::All)
102    }
103
104    /// Returns an iterator over all configured [`RethRpcModule`]
105    pub fn iter_selection(&self) -> Box<dyn Iterator<Item = RethRpcModule> + '_> {
106        match self {
107            Self::All => Box::new(Self::all_modules_iter()),
108            Self::Standard => Box::new(Self::STANDARD_MODULES.iter().cloned()),
109            Self::Selection(s) => Box::new(s.iter().cloned()),
110        }
111    }
112
113    /// Clones the set of configured [`RethRpcModule`].
114    pub fn to_selection(&self) -> HashSet<RethRpcModule> {
115        match self {
116            Self::All => Self::all_modules(),
117            Self::Standard => Self::standard_modules(),
118            Self::Selection(s) => s.clone(),
119        }
120    }
121
122    /// Converts the selection into a [`HashSet`].
123    pub fn into_selection(self) -> HashSet<RethRpcModule> {
124        match self {
125            Self::All => Self::all_modules(),
126            Self::Standard => Self::standard_modules(),
127            Self::Selection(s) => s,
128        }
129    }
130
131    /// Returns true if both selections are identical.
132    pub fn are_identical(http: Option<&Self>, ws: Option<&Self>) -> bool {
133        match (http, ws) {
134            // If either side is disabled, then the other must be empty
135            (Some(some), None) | (None, Some(some)) => some.is_empty(),
136
137            (Some(http), Some(ws)) => http.to_selection() == ws.to_selection(),
138            (None, None) => true,
139        }
140    }
141
142    /// Returns true if the selection contains the given module.
143    pub fn contains(&self, module: &RethRpcModule) -> bool {
144        match self {
145            Self::All => !matches!(module, RethRpcModule::Testing),
146            Self::Standard => Self::STANDARD_MODULES.contains(module),
147            Self::Selection(s) => s.contains(module),
148        }
149    }
150
151    /// Adds a module to the selection.
152    ///
153    /// If the selection is `All`, this is a no-op.
154    /// Otherwise, converts to a `Selection` and adds the module.
155    pub fn push(&mut self, module: RethRpcModule) {
156        if !self.is_all() {
157            let mut modules = self.to_selection();
158            modules.insert(module);
159            *self = Self::Selection(modules);
160        }
161    }
162
163    /// Returns a new selection with the given module added.
164    ///
165    /// If the selection is `All`, returns `All`.
166    /// Otherwise, converts to a `Selection` and adds the module.
167    pub fn append(self, module: RethRpcModule) -> Self {
168        if self.is_all() {
169            Self::All
170        } else {
171            let mut modules = self.into_selection();
172            modules.insert(module);
173            Self::Selection(modules)
174        }
175    }
176
177    /// Extends the selection with modules from an iterator.
178    ///
179    /// If the selection is `All`, this is a no-op.
180    /// Otherwise, converts to a `Selection` and adds the modules.
181    pub fn extend<I>(&mut self, iter: I)
182    where
183        I: IntoIterator<Item = RethRpcModule>,
184    {
185        if !self.is_all() {
186            let mut modules = self.to_selection();
187            modules.extend(iter);
188            *self = Self::Selection(modules);
189        }
190    }
191
192    /// Returns a new selection with modules from an iterator added.
193    ///
194    /// If the selection is `All`, returns `All`.
195    /// Otherwise, converts to a `Selection` and adds the modules.
196    pub fn extended<I>(self, iter: I) -> Self
197    where
198        I: IntoIterator<Item = RethRpcModule>,
199    {
200        if self.is_all() {
201            Self::All
202        } else {
203            let mut modules = self.into_selection();
204            modules.extend(iter);
205            Self::Selection(modules)
206        }
207    }
208
209    fn all_modules_iter() -> impl Iterator<Item = RethRpcModule> {
210        RethRpcModule::modules().into_iter().filter(|module| *module != RethRpcModule::Testing)
211    }
212}
213
214impl From<&HashSet<RethRpcModule>> for RpcModuleSelection {
215    fn from(s: &HashSet<RethRpcModule>) -> Self {
216        Self::from(s.clone())
217    }
218}
219
220impl From<HashSet<RethRpcModule>> for RpcModuleSelection {
221    fn from(s: HashSet<RethRpcModule>) -> Self {
222        Self::Selection(s)
223    }
224}
225
226impl From<&[RethRpcModule]> for RpcModuleSelection {
227    fn from(s: &[RethRpcModule]) -> Self {
228        Self::Selection(s.iter().cloned().collect())
229    }
230}
231
232impl From<Vec<RethRpcModule>> for RpcModuleSelection {
233    fn from(s: Vec<RethRpcModule>) -> Self {
234        Self::Selection(s.into_iter().collect())
235    }
236}
237
238impl<const N: usize> From<[RethRpcModule; N]> for RpcModuleSelection {
239    fn from(s: [RethRpcModule; N]) -> Self {
240        Self::Selection(s.into_iter().collect())
241    }
242}
243
244impl<'a> FromIterator<&'a RethRpcModule> for RpcModuleSelection {
245    fn from_iter<I>(iter: I) -> Self
246    where
247        I: IntoIterator<Item = &'a RethRpcModule>,
248    {
249        iter.into_iter().cloned().collect()
250    }
251}
252
253impl FromIterator<RethRpcModule> for RpcModuleSelection {
254    fn from_iter<I>(iter: I) -> Self
255    where
256        I: IntoIterator<Item = RethRpcModule>,
257    {
258        Self::Selection(iter.into_iter().collect())
259    }
260}
261
262impl FromStr for RpcModuleSelection {
263    type Err = ParseError;
264
265    fn from_str(s: &str) -> Result<Self, Self::Err> {
266        if s.is_empty() {
267            return Ok(Self::Selection(Default::default()))
268        }
269        // Empty items, such as from a trailing comma in "eth,", are ignored.
270        let modules = s.split(',').map(str::trim).filter(|m| !m.is_empty());
271        // The keywords are matched case-insensitively, so "all", "ALL", "aLl" etc. are accepted.
272        //
273        // They select the whole set and are only valid on their own: mixing them with module
274        // names, such as "all,testing" or "eth,none", is rejected instead of silently dropping
275        // or misinterpreting some of the names.
276        let is_keyword = |m: &str| m.eq_ignore_ascii_case("all") || m.eq_ignore_ascii_case("none");
277        if modules.clone().count() > 1 && modules.clone().any(is_keyword) {
278            return Err(ParseError::VariantNotFound)
279        }
280        let single = modules.clone().next().unwrap_or_default();
281        if single.eq_ignore_ascii_case("all") {
282            Ok(Self::All)
283        } else if single.eq_ignore_ascii_case("none") {
284            Ok(Self::Selection(Default::default()))
285        } else {
286            Self::try_from_selection(modules)
287        }
288    }
289}
290
291impl fmt::Display for RpcModuleSelection {
292    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
293        write!(
294            f,
295            "[{}]",
296            self.iter_selection().map(|s| s.to_string()).collect::<Vec<_>>().join(", ")
297        )
298    }
299}
300
301/// Represents RPC modules that are supported by reth
302#[derive(Debug, Clone, Eq, PartialEq, Hash, VariantNames, Deserialize)]
303#[serde(rename_all = "snake_case")]
304#[strum(serialize_all = "kebab-case")]
305pub enum RethRpcModule {
306    /// `admin_` module
307    Admin,
308    /// `debug_` module
309    Debug,
310    /// `eth_` module
311    Eth,
312    /// `net_` module
313    Net,
314    /// `trace_` module
315    Trace,
316    /// `txpool_` module
317    Txpool,
318    /// `web3_` module
319    Web3,
320    /// `rpc_` module
321    Rpc,
322    /// `reth_` module
323    Reth,
324    /// `ots_` module
325    Ots,
326    /// `flashbots_` module
327    Flashbots,
328    /// `miner_` module
329    Miner,
330    /// `mev_` module
331    Mev,
332    /// `testing_` module
333    Testing,
334    /// Custom RPC module not part of the standard set
335    #[strum(default)]
336    #[serde(untagged)]
337    Other(String),
338}
339
340// === impl RethRpcModule ===
341
342impl RethRpcModule {
343    /// All standard variants (excludes Other)
344    const STANDARD_VARIANTS: &'static [Self] = &[
345        Self::Admin,
346        Self::Debug,
347        Self::Eth,
348        Self::Net,
349        Self::Trace,
350        Self::Txpool,
351        Self::Web3,
352        Self::Rpc,
353        Self::Reth,
354        Self::Ots,
355        Self::Flashbots,
356        Self::Miner,
357        Self::Mev,
358        Self::Testing,
359    ];
360
361    /// Returns the number of standard variants (excludes Other)
362    pub const fn variant_count() -> usize {
363        Self::STANDARD_VARIANTS.len()
364    }
365
366    /// Returns all variant names including Other (for parsing)
367    pub const fn all_variant_names() -> &'static [&'static str] {
368        <Self as VariantNames>::VARIANTS
369    }
370
371    /// Returns standard variant names (excludes "other") for CLI display
372    pub fn standard_variant_names() -> impl Iterator<Item = &'static str> {
373        <Self as VariantNames>::VARIANTS.iter().copied().filter(|&name| name != "other")
374    }
375
376    /// Returns all standard variants (excludes Other)
377    pub const fn all_variants() -> &'static [Self] {
378        Self::STANDARD_VARIANTS
379    }
380
381    /// Returns iterator over standard modules only
382    pub fn modules() -> impl IntoIterator<Item = Self> + Clone {
383        Self::STANDARD_VARIANTS.iter().cloned()
384    }
385
386    /// Returns the string representation of the module.
387    pub fn as_str(&self) -> &str {
388        match self {
389            Self::Other(s) => s.as_str(),
390            _ => self.as_ref(), // Uses AsRefStr trait
391        }
392    }
393
394    /// Returns true if this is an `Other` variant.
395    pub const fn is_other(&self) -> bool {
396        matches!(self, Self::Other(_))
397    }
398}
399
400impl AsRef<str> for RethRpcModule {
401    fn as_ref(&self) -> &str {
402        match self {
403            Self::Other(s) => s.as_str(),
404            // For standard variants, use the derive-generated static strings
405            Self::Admin => "admin",
406            Self::Debug => "debug",
407            Self::Eth => "eth",
408            Self::Net => "net",
409            Self::Trace => "trace",
410            Self::Txpool => "txpool",
411            Self::Web3 => "web3",
412            Self::Rpc => "rpc",
413            Self::Reth => "reth",
414            Self::Ots => "ots",
415            Self::Flashbots => "flashbots",
416            Self::Miner => "miner",
417            Self::Mev => "mev",
418            Self::Testing => "testing",
419        }
420    }
421}
422
423impl FromStr for RethRpcModule {
424    type Err = ParseError;
425
426    fn from_str(s: &str) -> Result<Self, Self::Err> {
427        Ok(match s {
428            "admin" => Self::Admin,
429            "debug" => Self::Debug,
430            "eth" => Self::Eth,
431            "net" => Self::Net,
432            "trace" => Self::Trace,
433            "txpool" => Self::Txpool,
434            "web3" => Self::Web3,
435            "rpc" => Self::Rpc,
436            "reth" => Self::Reth,
437            "ots" => Self::Ots,
438            "flashbots" => Self::Flashbots,
439            "miner" => Self::Miner,
440            "mev" => Self::Mev,
441            "testing" => Self::Testing,
442            // Any unknown module becomes Other
443            other => Self::Other(other.to_string()),
444        })
445    }
446}
447
448impl TryFrom<&str> for RethRpcModule {
449    type Error = ParseError;
450    fn try_from(s: &str) -> Result<Self, <Self as TryFrom<&str>>::Error> {
451        FromStr::from_str(s)
452    }
453}
454
455impl fmt::Display for RethRpcModule {
456    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
457        f.pad(self.as_ref())
458    }
459}
460
461impl Serialize for RethRpcModule {
462    fn serialize<S>(&self, s: S) -> Result<S::Ok, S::Error>
463    where
464        S: Serializer,
465    {
466        s.serialize_str(self.as_str())
467    }
468}
469
470/// Trait for validating RPC module selections.
471///
472/// This allows customizing how RPC module names are validated when parsing
473/// CLI arguments or configuration.
474pub trait RpcModuleValidator: Clone + Send + Sync + 'static {
475    /// Parse and validate an RPC module selection string.
476    fn parse_selection(s: &str) -> Result<RpcModuleSelection, String>;
477
478    /// Validates RPC module selection that was already parsed.
479    ///
480    /// This is used to validate modules that were parsed as `Other` variants
481    /// to ensure they meet the validation rules of the specific implementation.
482    fn validate_selection(modules: &RpcModuleSelection, arg_name: &str) -> Result<(), String> {
483        // Re-validate the modules using the parser's validator
484        // This is necessary because the clap value parser accepts any input
485        // and we need to validate according to the specific parser's rules
486        let RpcModuleSelection::Selection(module_set) = modules else {
487            // All or Standard variants are always valid
488            return Ok(());
489        };
490
491        for module in module_set {
492            let RethRpcModule::Other(name) = module else {
493                // Standard modules are always valid
494                continue;
495            };
496
497            // Try to parse and validate using the configured validator
498            // This will check for typos and other validation rules. A name must parse back to
499            // exactly this module: keywords like `all`, lists like "eth,eth", and padded names
500            // like " eth " parse to something else, which would not be served.
501            let selection = Self::parse_selection(name)
502                .map_err(|e| format!("Invalid RPC module '{name}' in {arg_name}: {e}"))?;
503            if !matches!(&selection, RpcModuleSelection::Selection(s) if s.len() == 1 && s.contains(module))
504            {
505                return Err(format!("Invalid RPC module '{name}' in {arg_name}: not a module name"))
506            }
507        }
508
509        Ok(())
510    }
511}
512
513/// Default validator that rejects unknown module names.
514///
515/// This validator only accepts known RPC module names.
516#[derive(Debug, Clone, Copy)]
517pub struct DefaultRpcModuleValidator;
518
519impl RpcModuleValidator for DefaultRpcModuleValidator {
520    fn parse_selection(s: &str) -> Result<RpcModuleSelection, String> {
521        // First try standard parsing
522        let selection = RpcModuleSelection::from_str(s)
523            .map_err(|e| format!("Failed to parse RPC modules: {}", e))?;
524
525        // Validate each module in the selection
526        if let RpcModuleSelection::Selection(modules) = &selection {
527            for module in modules {
528                if let RethRpcModule::Other(name) = module {
529                    return Err(format!("Unknown RPC module: '{}'", name));
530                }
531            }
532        }
533
534        Ok(selection)
535    }
536}
537
538/// Lenient validator that accepts any module name without validation.
539///
540/// This validator accepts any module name, including unknown ones.
541#[derive(Debug, Clone, Copy)]
542pub struct LenientRpcModuleValidator;
543
544impl RpcModuleValidator for LenientRpcModuleValidator {
545    fn parse_selection(s: &str) -> Result<RpcModuleSelection, String> {
546        RpcModuleSelection::from_str(s).map_err(|e| format!("Failed to parse RPC modules: {}", e))
547    }
548}
549
550#[cfg(test)]
551mod test {
552    use super::*;
553
554    #[test]
555    fn test_all_modules() {
556        let all_modules = RpcModuleSelection::all_modules();
557        assert_eq!(all_modules.len(), RethRpcModule::variant_count() - 1);
558        assert!(!all_modules.contains(&RethRpcModule::Testing));
559    }
560
561    #[test]
562    fn test_testing_requires_explicit_selection() {
563        let all = RpcModuleSelection::All;
564        let explicit = RpcModuleSelection::from([RethRpcModule::Testing]);
565
566        assert!(!all.contains(&RethRpcModule::Testing));
567        assert!(!all.to_selection().contains(&RethRpcModule::Testing));
568        assert!(!all.into_selection().contains(&RethRpcModule::Testing));
569        assert!(explicit.contains(&RethRpcModule::Testing));
570        assert!(explicit.iter_selection().any(|module| module == RethRpcModule::Testing));
571    }
572
573    #[test]
574    fn test_standard_modules() {
575        let standard_modules = RpcModuleSelection::standard_modules();
576        let expected_modules: HashSet<RethRpcModule> =
577            HashSet::from([RethRpcModule::Eth, RethRpcModule::Net, RethRpcModule::Web3]);
578        assert_eq!(standard_modules, expected_modules);
579    }
580
581    #[test]
582    fn test_default_ipc_modules() {
583        let default_ipc_modules = RpcModuleSelection::default_ipc_modules();
584        assert_eq!(default_ipc_modules, RpcModuleSelection::all_modules());
585        assert!(!default_ipc_modules.contains(&RethRpcModule::Testing));
586    }
587
588    #[test]
589    fn test_try_from_selection_success() {
590        let selection = vec!["eth", "admin"];
591        let config = RpcModuleSelection::try_from_selection(selection).unwrap();
592        assert_eq!(config, RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Admin]));
593    }
594
595    #[test]
596    fn test_rpc_module_selection_len() {
597        let all_modules = RpcModuleSelection::All;
598        let standard = RpcModuleSelection::Standard;
599        let selection = RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Admin]);
600
601        assert_eq!(all_modules.len(), RethRpcModule::variant_count() - 1);
602        assert_eq!(standard.len(), 3);
603        assert_eq!(selection.len(), 2);
604    }
605
606    #[test]
607    fn test_rpc_module_selection_is_empty() {
608        let empty_selection = RpcModuleSelection::from(HashSet::new());
609        assert!(empty_selection.is_empty());
610
611        let non_empty_selection = RpcModuleSelection::from([RethRpcModule::Eth]);
612        assert!(!non_empty_selection.is_empty());
613    }
614
615    #[test]
616    fn test_rpc_module_selection_iter_selection() {
617        let all_modules = RpcModuleSelection::All;
618        let standard = RpcModuleSelection::Standard;
619        let selection = RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Admin]);
620
621        assert_eq!(all_modules.iter_selection().count(), RethRpcModule::variant_count() - 1);
622        assert!(!all_modules.iter_selection().any(|module| module == RethRpcModule::Testing));
623        assert_eq!(standard.iter_selection().count(), 3);
624        assert_eq!(selection.iter_selection().count(), 2);
625    }
626
627    #[test]
628    fn test_rpc_module_selection_to_selection() {
629        let all_modules = RpcModuleSelection::All;
630        let standard = RpcModuleSelection::Standard;
631        let selection = RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Admin]);
632
633        assert_eq!(all_modules.to_selection(), RpcModuleSelection::all_modules());
634        assert_eq!(standard.to_selection(), RpcModuleSelection::standard_modules());
635        assert_eq!(
636            selection.to_selection(),
637            HashSet::from([RethRpcModule::Eth, RethRpcModule::Admin])
638        );
639    }
640
641    #[test]
642    fn test_rpc_module_selection_are_identical() {
643        // Test scenario: both selections are `All`
644        //
645        // Both selections include the same modules, excluding `testing`.
646        let all_modules = RpcModuleSelection::All;
647        assert!(RpcModuleSelection::are_identical(Some(&all_modules), Some(&all_modules)));
648
649        // Test scenario: both `http` and `ws` are `None`
650        //
651        // When both arguments are `None`, the function should return `true` because no modules are
652        // selected.
653        assert!(RpcModuleSelection::are_identical(None, None));
654
655        // Test scenario: both selections contain identical sets of specific modules
656        //
657        // In this case, both selections contain the same modules (`Eth` and `Admin`),
658        // so they should be considered identical.
659        let selection1 = RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Admin]);
660        let selection2 = RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Admin]);
661        assert!(RpcModuleSelection::are_identical(Some(&selection1), Some(&selection2)));
662
663        // Test scenario: one selection is `All`, the other is `Standard`
664        //
665        // `All` includes all possible modules, while `Standard` includes a specific set of modules.
666        // Since `Standard` does not cover all modules, these two selections should not be
667        // considered identical.
668        let standard = RpcModuleSelection::Standard;
669        assert!(!RpcModuleSelection::are_identical(Some(&all_modules), Some(&standard)));
670
671        // Test scenario: one is `None`, the other is an empty selection
672        //
673        // When one selection is `None` and the other is an empty selection (no modules),
674        // they should be considered identical because neither selects any modules.
675        let empty_selection = RpcModuleSelection::Selection(HashSet::new());
676        assert!(RpcModuleSelection::are_identical(None, Some(&empty_selection)));
677        assert!(RpcModuleSelection::are_identical(Some(&empty_selection), None));
678
679        // Test scenario: one is `None`, the other is a non-empty selection
680        //
681        // If one selection is `None` and the other contains modules, they should not be considered
682        // identical because `None` represents no selection, while the other explicitly
683        // selects modules.
684        let non_empty_selection = RpcModuleSelection::from([RethRpcModule::Eth]);
685        assert!(!RpcModuleSelection::are_identical(None, Some(&non_empty_selection)));
686        assert!(!RpcModuleSelection::are_identical(Some(&non_empty_selection), None));
687
688        // Test scenario: `All` vs. non-full selection
689        //
690        // If one selection is `All` (which includes all modules) and the other contains only a
691        // subset of modules, they should not be considered identical.
692        let partial_selection = RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Net]);
693        assert!(!RpcModuleSelection::are_identical(Some(&all_modules), Some(&partial_selection)));
694
695        // Test scenario: full selection vs `All`
696        //
697        // An explicit selection of the same modules is identical to `All`.
698        let full_selection = RpcModuleSelection::from(RpcModuleSelection::all_modules());
699        assert!(RpcModuleSelection::are_identical(Some(&all_modules), Some(&full_selection)));
700
701        // Explicitly including `testing` makes the selections different.
702        let mut testing_selection = RpcModuleSelection::all_modules();
703        testing_selection.insert(RethRpcModule::Testing);
704        let testing_selection = RpcModuleSelection::from(testing_selection);
705        assert!(!RpcModuleSelection::are_identical(Some(&all_modules), Some(&testing_selection),));
706
707        // Test scenario: different non-empty selections
708        //
709        // If the two selections contain different sets of modules, they should not be considered
710        // identical.
711        let selection3 = RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Net]);
712        let selection4 = RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Web3]);
713        assert!(!RpcModuleSelection::are_identical(Some(&selection3), Some(&selection4)));
714
715        // Test scenario: `Standard` vs an equivalent selection
716        // The `Standard` selection includes a predefined set of modules. If we explicitly create
717        // a selection with the same set of modules, they should be considered identical.
718        let matching_standard =
719            RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Net, RethRpcModule::Web3]);
720        assert!(RpcModuleSelection::are_identical(Some(&standard), Some(&matching_standard)));
721
722        // Test scenario: `Standard` vs non-matching selection
723        //
724        // If the selection does not match the modules included in `Standard`, they should not be
725        // considered identical.
726        let non_matching_standard =
727            RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Net]);
728        assert!(!RpcModuleSelection::are_identical(Some(&standard), Some(&non_matching_standard)));
729    }
730
731    #[test]
732    fn test_rpc_module_selection_append() {
733        // Test append on Standard selection
734        let selection = RpcModuleSelection::Standard;
735        let new_selection = selection.append(RethRpcModule::Admin);
736        assert!(new_selection.contains(&RethRpcModule::Eth));
737        assert!(new_selection.contains(&RethRpcModule::Net));
738        assert!(new_selection.contains(&RethRpcModule::Web3));
739        assert!(new_selection.contains(&RethRpcModule::Admin));
740
741        // Test append on empty Selection
742        let selection = RpcModuleSelection::Selection(HashSet::new());
743        let new_selection = selection.append(RethRpcModule::Eth);
744        assert!(new_selection.contains(&RethRpcModule::Eth));
745        assert_eq!(new_selection.len(), 1);
746
747        // Test append on All (should return All)
748        let selection = RpcModuleSelection::All;
749        let new_selection = selection.append(RethRpcModule::Eth);
750        assert_eq!(new_selection, RpcModuleSelection::All);
751    }
752
753    #[test]
754    fn test_rpc_module_selection_extend() {
755        // Test extend on Standard selection
756        let mut selection = RpcModuleSelection::Standard;
757        selection.extend(vec![RethRpcModule::Admin, RethRpcModule::Debug]);
758        assert!(selection.contains(&RethRpcModule::Eth));
759        assert!(selection.contains(&RethRpcModule::Net));
760        assert!(selection.contains(&RethRpcModule::Web3));
761        assert!(selection.contains(&RethRpcModule::Admin));
762        assert!(selection.contains(&RethRpcModule::Debug));
763
764        // Test extend on empty Selection
765        let mut selection = RpcModuleSelection::Selection(HashSet::new());
766        selection.extend(vec![RethRpcModule::Eth, RethRpcModule::Admin]);
767        assert!(selection.contains(&RethRpcModule::Eth));
768        assert!(selection.contains(&RethRpcModule::Admin));
769        assert_eq!(selection.len(), 2);
770
771        // Test extend on All (should be no-op)
772        let mut selection = RpcModuleSelection::All;
773        selection.extend(vec![RethRpcModule::Eth, RethRpcModule::Admin]);
774        assert_eq!(selection, RpcModuleSelection::All);
775    }
776
777    #[test]
778    fn test_rpc_module_selection_from_str() {
779        // Test empty string returns default selection
780        let result = RpcModuleSelection::from_str("");
781        assert!(result.is_ok());
782        assert_eq!(result.unwrap(), RpcModuleSelection::Selection(Default::default()));
783
784        // Test "all" (case insensitive) returns All variant
785        let result = RpcModuleSelection::from_str("all");
786        assert!(result.is_ok());
787        assert_eq!(result.unwrap(), RpcModuleSelection::All);
788
789        let result = RpcModuleSelection::from_str("All");
790        assert!(result.is_ok());
791        assert_eq!(result.unwrap(), RpcModuleSelection::All);
792
793        let result = RpcModuleSelection::from_str("ALL");
794        assert!(result.is_ok());
795        assert_eq!(result.unwrap(), RpcModuleSelection::All);
796
797        // Test "none" (case insensitive) returns empty selection
798        let result = RpcModuleSelection::from_str("none");
799        assert!(result.is_ok());
800        assert_eq!(result.unwrap(), RpcModuleSelection::Selection(Default::default()));
801
802        let result = RpcModuleSelection::from_str("None");
803        assert!(result.is_ok());
804        assert_eq!(result.unwrap(), RpcModuleSelection::Selection(Default::default()));
805
806        let result = RpcModuleSelection::from_str("NONE");
807        assert!(result.is_ok());
808        assert_eq!(result.unwrap(), RpcModuleSelection::Selection(Default::default()));
809
810        // Keywords mixed with module names are rejected in any position.
811        for s in ["all,testing", "none,eth", "eth,all", "eth, NONE", "all,all", "eth,all,admin"] {
812            assert!(RpcModuleSelection::from_str(s).is_err(), "{s}");
813            assert!(DefaultRpcModuleValidator::parse_selection(s).is_err(), "{s}");
814        }
815        // Empty items are ignored rather than mixed with keywords or rejected as modules.
816        assert_eq!(RpcModuleSelection::from_str("all,").unwrap(), RpcModuleSelection::All);
817        assert!(RpcModuleSelection::from_str(",none").unwrap().is_empty());
818        for s in ["eth,", "eth,,admin"] {
819            let selection = DefaultRpcModuleValidator::parse_selection(s).unwrap();
820            assert!(DefaultRpcModuleValidator::validate_selection(&selection, "http.api").is_ok());
821        }
822
823        // Lenient accepts unknown names such as "[eth" as custom modules, the default does not.
824        let bracketed = RpcModuleSelection::from([RethRpcModule::Other("[eth".to_string())]);
825        assert!(DefaultRpcModuleValidator::validate_selection(&bracketed, "http.api").is_err());
826
827        for name in ["all", "NONE", "eth,eth", " eth ", "eth\t"] {
828            let selection = RpcModuleSelection::from([
829                RethRpcModule::Eth,
830                RethRpcModule::Other(name.to_string()),
831            ]);
832            assert!(DefaultRpcModuleValidator::validate_selection(&selection, "http.api").is_err());
833            assert!(LenientRpcModuleValidator::validate_selection(&selection, "http.api").is_err());
834        }
835
836        // Test valid selections: "eth,admin"
837        let result = RpcModuleSelection::from_str("eth,admin");
838        assert!(result.is_ok());
839        let expected_selection =
840            RpcModuleSelection::from([RethRpcModule::Eth, RethRpcModule::Admin]);
841        assert_eq!(result.unwrap(), expected_selection);
842
843        // Test valid selection with extra spaces: " eth , admin "
844        let result = RpcModuleSelection::from_str(" eth , admin ");
845        assert!(result.is_ok());
846        assert_eq!(result.unwrap(), expected_selection);
847
848        // Test custom module selections now work (no longer return errors)
849        let result = RpcModuleSelection::from_str("invalid,unknown");
850        assert!(result.is_ok());
851        let selection = result.unwrap();
852        assert!(selection.contains(&RethRpcModule::Other("invalid".to_string())));
853        assert!(selection.contains(&RethRpcModule::Other("unknown".to_string())));
854
855        // Test single valid selection: "eth"
856        let result = RpcModuleSelection::from_str("eth");
857        assert!(result.is_ok());
858        let expected_selection = RpcModuleSelection::from([RethRpcModule::Eth]);
859        assert_eq!(result.unwrap(), expected_selection);
860
861        // Test single custom module selection: "unknown" now becomes Other
862        let result = RpcModuleSelection::from_str("unknown");
863        assert!(result.is_ok());
864        let expected_selection =
865            RpcModuleSelection::from([RethRpcModule::Other("unknown".to_string())]);
866        assert_eq!(result.unwrap(), expected_selection);
867    }
868
869    #[test]
870    fn test_rpc_module_other_variant() {
871        // Test parsing custom module
872        let custom_module = RethRpcModule::from_str("myCustomModule").unwrap();
873        assert_eq!(custom_module, RethRpcModule::Other("myCustomModule".to_string()));
874
875        // Test as_str for Other variant
876        assert_eq!(custom_module.as_str(), "myCustomModule");
877
878        // Test as_ref for Other variant
879        assert_eq!(custom_module.as_ref(), "myCustomModule");
880
881        // Test Display impl
882        assert_eq!(custom_module.to_string(), "myCustomModule");
883    }
884
885    #[test]
886    fn test_rpc_module_selection_with_mixed_modules() {
887        // Test selection with both standard and custom modules
888        let result = RpcModuleSelection::from_str("eth,admin,myCustomModule,anotherCustom");
889        assert!(result.is_ok());
890
891        let selection = result.unwrap();
892        assert!(selection.contains(&RethRpcModule::Eth));
893        assert!(selection.contains(&RethRpcModule::Admin));
894        assert!(selection.contains(&RethRpcModule::Other("myCustomModule".to_string())));
895        assert!(selection.contains(&RethRpcModule::Other("anotherCustom".to_string())));
896    }
897
898    #[test]
899    fn test_rpc_module_all_excludes_custom() {
900        // Test that All selection doesn't include custom modules
901        let all_selection = RpcModuleSelection::All;
902
903        // All should contain standard modules
904        assert!(all_selection.contains(&RethRpcModule::Eth));
905        assert!(all_selection.contains(&RethRpcModule::Admin));
906
907        // But All doesn't explicitly contain custom modules
908        // (though contains() returns true for all modules when selection is All)
909        assert_eq!(all_selection.len(), RethRpcModule::variant_count() - 1);
910    }
911
912    #[test]
913    fn test_rpc_module_equality_with_other() {
914        let other1 = RethRpcModule::Other("custom".to_string());
915        let other2 = RethRpcModule::Other("custom".to_string());
916        let other3 = RethRpcModule::Other("different".to_string());
917
918        assert_eq!(other1, other2);
919        assert_ne!(other1, other3);
920        assert_ne!(other1, RethRpcModule::Eth);
921    }
922
923    #[test]
924    fn test_rpc_module_is_other() {
925        // Standard modules should return false
926        assert!(!RethRpcModule::Eth.is_other());
927        assert!(!RethRpcModule::Admin.is_other());
928        assert!(!RethRpcModule::Debug.is_other());
929
930        // Other variants should return true
931        assert!(RethRpcModule::Other("custom".to_string()).is_other());
932        assert!(RethRpcModule::Other("mycustomrpc".to_string()).is_other());
933    }
934
935    #[test]
936    fn test_standard_variant_names_excludes_other() {
937        let standard_names: Vec<_> = RethRpcModule::standard_variant_names().collect();
938
939        // Verify "other" is not in the list
940        assert!(!standard_names.contains(&"other"));
941
942        // Should have exactly as many names as STANDARD_VARIANTS
943        assert_eq!(standard_names.len(), RethRpcModule::STANDARD_VARIANTS.len());
944
945        // Verify all standard variants have their names in the list
946        for variant in RethRpcModule::STANDARD_VARIANTS {
947            assert!(standard_names.contains(&variant.as_ref()));
948        }
949    }
950
951    #[test]
952    fn test_default_validator_accepts_standard_modules() {
953        // Should accept standard modules
954        let result = DefaultRpcModuleValidator::parse_selection("eth,admin,debug");
955        assert!(result.is_ok());
956
957        let selection = result.unwrap();
958        assert!(matches!(selection, RpcModuleSelection::Selection(_)));
959    }
960
961    #[test]
962    fn test_default_validator_rejects_unknown_modules() {
963        // Should reject unknown module names
964        let result = DefaultRpcModuleValidator::parse_selection("eth,mycustom");
965        assert!(result.is_err());
966        assert!(result.unwrap_err().contains("Unknown RPC module: 'mycustom'"));
967
968        let result = DefaultRpcModuleValidator::parse_selection("unknownmodule");
969        assert!(result.is_err());
970        assert!(result.unwrap_err().contains("Unknown RPC module: 'unknownmodule'"));
971
972        let result = DefaultRpcModuleValidator::parse_selection("eth,admin,xyz123");
973        assert!(result.is_err());
974        assert!(result.unwrap_err().contains("Unknown RPC module: 'xyz123'"));
975    }
976
977    #[test]
978    fn test_default_validator_all_selection() {
979        // Should accept "all" selection
980        let result = DefaultRpcModuleValidator::parse_selection("all");
981        assert!(result.is_ok());
982        assert_eq!(result.unwrap(), RpcModuleSelection::All);
983    }
984
985    #[test]
986    fn test_default_validator_none_selection() {
987        // Should accept "none" selection
988        let result = DefaultRpcModuleValidator::parse_selection("none");
989        assert!(result.is_ok());
990        assert_eq!(result.unwrap(), RpcModuleSelection::Selection(Default::default()));
991    }
992
993    #[test]
994    fn test_lenient_validator_accepts_unknown_modules() {
995        // Lenient validator should accept any module name without validation
996        let result = LenientRpcModuleValidator::parse_selection("eht,adimn,xyz123,customrpc");
997        assert!(result.is_ok());
998
999        let selection = result.unwrap();
1000        if let RpcModuleSelection::Selection(modules) = selection {
1001            assert!(modules.contains(&RethRpcModule::Other("eht".to_string())));
1002            assert!(modules.contains(&RethRpcModule::Other("adimn".to_string())));
1003            assert!(modules.contains(&RethRpcModule::Other("xyz123".to_string())));
1004            assert!(modules.contains(&RethRpcModule::Other("customrpc".to_string())));
1005        } else {
1006            panic!("Expected Selection variant");
1007        }
1008    }
1009
1010    #[test]
1011    fn test_default_validator_mixed_standard_and_custom() {
1012        // Should reject mix of standard and custom modules
1013        let result = DefaultRpcModuleValidator::parse_selection("eth,admin,mycustom,debug");
1014        assert!(result.is_err());
1015        assert!(result.unwrap_err().contains("Unknown RPC module: 'mycustom'"));
1016    }
1017}