Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 18 additions & 50 deletions bindings/rust/src/ethereum_kzg_settings/mod.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
use crate::KzgSettings;
use alloc::{boxed::Box, sync::Arc};
use once_cell::race::OnceBox;
use alloc::sync::Arc;

#[cfg(not(feature = "std"))]
use once_cell::race::OnceBox as OnceLock;
#[cfg(feature = "std")]
use std::sync::OnceLock;

#[cfg(feature = "std")]
use once_cell as _;

/// Default G1 monomial bytes.
const ETH_G1_MONOMIAL_POINTS: &[u8] = include_bytes!("./g1_monomial_bytes.bin");
Expand All @@ -9,31 +16,6 @@ const ETH_G1_LAGRANGE_POINTS: &[u8] = include_bytes!("./g1_lagrange_bytes.bin");
/// Default G2 monomial bytes.
const ETH_G2_MONOMIAL_POINTS: &[u8] = include_bytes!("./g2_monomial_bytes.bin");

macro_rules! create_cache {
($name:ident) => {
static $name: OnceBox<Arc<KzgSettings>> = OnceBox::new();
};
}

// We use separate OnceBox instances for each precompute value.
// This avoids the need for any unsafe code or mutexes.
create_cache!(CACHE_0);
create_cache!(CACHE_1);
create_cache!(CACHE_2);
create_cache!(CACHE_3);
create_cache!(CACHE_4);
create_cache!(CACHE_5);
create_cache!(CACHE_6);
create_cache!(CACHE_7);
create_cache!(CACHE_8);
create_cache!(CACHE_9);
create_cache!(CACHE_10);
create_cache!(CACHE_11);
create_cache!(CACHE_12);
create_cache!(CACHE_13);
create_cache!(CACHE_14);
create_cache!(CACHE_15);

/// Returns default Ethereum mainnet KZG settings.
///
/// If you need a cloneable settings use `ethereum_kzg_settings_arc` instead.
Expand All @@ -53,37 +35,23 @@ pub fn ethereum_kzg_settings_arc(precompute: u64) -> Arc<KzgSettings> {
}

fn ethereum_kzg_settings_inner(precompute: u64) -> &'static Arc<KzgSettings> {
let cache_box = match precompute {
0 => &CACHE_0,
1 => &CACHE_1,
2 => &CACHE_2,
3 => &CACHE_3,
4 => &CACHE_4,
5 => &CACHE_5,
6 => &CACHE_6,
7 => &CACHE_7,
8 => &CACHE_8,
9 => &CACHE_9,
10 => &CACHE_10,
11 => &CACHE_11,
12 => &CACHE_12,
13 => &CACHE_13,
14 => &CACHE_14,
15 => &CACHE_15,
_ => panic!(
"Unsupported precompute value: {precompute}. Only values 0-15 (inclusive) are supported."
),
};
static CACHES: [OnceLock<Arc<KzgSettings>>; 16] = [const { OnceLock::new() }; 16];

assert!(
precompute <= 15,
"Unsupported precompute value: {precompute}. Only values 0-15 (inclusive) are supported."
);

cache_box.get_or_init(|| {
CACHES[precompute as usize].get_or_init(|| {
let settings = KzgSettings::load_trusted_setup(
ETH_G1_MONOMIAL_POINTS,
ETH_G1_LAGRANGE_POINTS,
ETH_G2_MONOMIAL_POINTS,
precompute,
)
.expect("failed to load default trusted setup");
Box::new(Arc::new(settings))
#[allow(clippy::useless_conversion)] // `std`: no-op, `not(std)`: allocates into a `Box`.
Arc::new(settings).into()
})
}

Expand Down
Loading