alloy_eips/eip4844/env_settings.rs
1use alloc::sync::Arc;
2use core::hash::{Hash, Hasher};
3
4// Re-export for convenience
5pub use c_kzg::KzgSettings;
6
7/// Precompute value that optimizes computing cell kzg proofs.
8///
9/// Set to 8 as the recommended default for computing proofs.
10///
11/// Learn more: <https://github.com/ethereum/c-kzg-4844/blob/dffa18ee350aeef38f749ffad24a27c1645fb4f8/README.md?plain=1#L112>
12const PRECOMPUTE: u64 = 8;
13
14/// KZG settings.
15#[derive(Clone, Debug, Default, Eq)]
16pub enum EnvKzgSettings {
17 /// Default mainnet trusted setup.
18 #[default]
19 Default,
20 /// Custom trusted setup.
21 Custom(Arc<KzgSettings>),
22}
23
24// Implement PartialEq and Hash manually because `c_kzg::KzgSettings` does not implement them.
25impl PartialEq for EnvKzgSettings {
26 fn eq(&self, other: &Self) -> bool {
27 match (self, other) {
28 (Self::Default, Self::Default) => true,
29 (Self::Custom(a), Self::Custom(b)) => Arc::ptr_eq(a, b),
30 _ => false,
31 }
32 }
33}
34
35impl Hash for EnvKzgSettings {
36 fn hash<H: Hasher>(&self, state: &mut H) {
37 core::mem::discriminant(self).hash(state);
38 match self {
39 Self::Default => {}
40 Self::Custom(settings) => Arc::as_ptr(settings).hash(state),
41 }
42 }
43}
44
45impl EnvKzgSettings {
46 /// Returns the KZG settings.
47 ///
48 /// If this is [`EnvKzgSettings::Default`], this will initialize the default settings if it is
49 /// not already loaded, see also [`c_kzg::ethereum_kzg_settings`].
50 ///
51 /// To configure a different [precompute] value, [`c_kzg::ethereum_kzg_settings`] must be called
52 /// directly once. The default precompute value is `0`.
53 ///
54 /// [precompute]: https://github.com/ethereum/c-kzg-4844/blob/dffa18ee350aeef38f749ffad24a27c1645fb4f8/README.md?plain=1#L112
55 #[inline]
56 pub fn get(&self) -> &KzgSettings {
57 match self {
58 Self::Default => c_kzg::ethereum_kzg_settings(PRECOMPUTE),
59 Self::Custom(settings) => settings,
60 }
61 }
62
63 /// Load custom KZG settings from a trusted setup file.
64 #[cfg(feature = "std")]
65 pub fn load_from_trusted_setup_file(
66 trusted_setup_file: &std::path::Path,
67 ) -> Result<Self, c_kzg::Error> {
68 let settings = KzgSettings::load_trusted_setup_file(trusted_setup_file, PRECOMPUTE)?;
69 Ok(Self::Custom(Arc::new(settings)))
70 }
71}