alloy_eips/eip4844/
env_settings.rs

1use crate::eip4844::trusted_setup_points::{G1_POINTS, G2_POINTS};
2use alloc::sync::Arc;
3use core::hash::{Hash, Hasher};
4
5// Re-export for convenience
6pub use c_kzg::KzgSettings;
7
8/// KZG settings.
9#[derive(Clone, Debug, Default, Eq)]
10pub enum EnvKzgSettings {
11    /// Default mainnet trusted setup.
12    #[default]
13    Default,
14    /// Custom trusted setup.
15    Custom(Arc<KzgSettings>),
16}
17
18// Implement PartialEq and Hash manually because `c_kzg::KzgSettings` does not implement them.
19impl PartialEq for EnvKzgSettings {
20    fn eq(&self, other: &Self) -> bool {
21        match (self, other) {
22            (Self::Default, Self::Default) => true,
23            (Self::Custom(a), Self::Custom(b)) => Arc::ptr_eq(a, b),
24            _ => false,
25        }
26    }
27}
28
29impl Hash for EnvKzgSettings {
30    fn hash<H: Hasher>(&self, state: &mut H) {
31        core::mem::discriminant(self).hash(state);
32        match self {
33            Self::Default => {}
34            Self::Custom(settings) => Arc::as_ptr(settings).hash(state),
35        }
36    }
37}
38
39impl EnvKzgSettings {
40    /// Returns the KZG settings.
41    ///
42    /// This will initialize the default settings if it is not already loaded.
43    #[inline]
44    pub fn get(&self) -> &KzgSettings {
45        match self {
46            Self::Default => {
47                let load = || {
48                    KzgSettings::load_trusted_setup(&G1_POINTS.0, &G2_POINTS.0)
49                        .expect("failed to load default trusted setup")
50                };
51                #[cfg(feature = "std")]
52                {
53                    use once_cell as _;
54                    use std::sync::OnceLock;
55                    static DEFAULT: OnceLock<KzgSettings> = OnceLock::new();
56                    DEFAULT.get_or_init(load)
57                }
58                #[cfg(not(feature = "std"))]
59                {
60                    use once_cell::race::OnceBox;
61                    static DEFAULT: OnceBox<KzgSettings> = OnceBox::new();
62                    DEFAULT.get_or_init(|| alloc::boxed::Box::new(load()))
63                }
64            }
65            Self::Custom(settings) => settings,
66        }
67    }
68
69    /// Load custom KZG settings from a trusted setup file.
70    #[cfg(feature = "std")]
71    pub fn load_from_trusted_setup_file(
72        trusted_setup_file: &std::path::Path,
73    ) -> Result<Self, c_kzg::Error> {
74        let settings = KzgSettings::load_trusted_setup_file(trusted_setup_file)?;
75        Ok(Self::Custom(Arc::new(settings)))
76    }
77}