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