repo stringlengths 6 65 | file_url stringlengths 81 311 | file_path stringlengths 6 227 | content stringlengths 0 32.8k | language stringclasses 1 value | license stringclasses 7 values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:31:58 2026-01-04 20:25:31 | truncated bool 2 classes |
|---|---|---|---|---|---|---|---|---|
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/fk20_proofs.rs | constantine/src/fk20_proofs.rs | extern crate alloc;
use alloc::vec;
use alloc::vec::Vec;
use kzg::{FFTFr, Fr, G1Mul, Poly, FFTG1, G1};
use crate::types::fft_settings::CtFFTSettings;
use crate::types::fr::CtFr;
use crate::types::g1::CtG1;
use crate::types::poly::CtPoly;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
impl CtFFTSettings {
pub fn toeplitz_part_1(&self, x: &[CtG1]) -> Vec<CtG1> {
let n = x.len();
let n2 = n * 2;
let mut x_ext = Vec::with_capacity(n2);
x_ext.extend(x.iter().take(n));
x_ext.resize(n2, CtG1::identity());
self.fft_g1(&x_ext, false).unwrap()
}
/// poly and x_ext_fft should be of same length
pub fn toeplitz_part_2(&self, poly: &CtPoly, x_ext_fft: &[CtG1]) -> Vec<CtG1> {
let coeffs_fft = self.fft_fr(&poly.coeffs, false).unwrap();
#[cfg(feature = "parallel")]
{
coeffs_fft
.into_par_iter()
.zip(x_ext_fft)
.take(poly.len())
.map(|(coeff_fft, x_ext_fft)| x_ext_fft.mul(&coeff_fft))
.collect()
}
#[cfg(not(feature = "parallel"))]
{
coeffs_fft
.into_iter()
.zip(x_ext_fft)
.take(poly.len())
.map(|(coeff_fft, x_ext_fft)| x_ext_fft.mul(&coeff_fft))
.collect()
}
}
pub fn toeplitz_part_3(&self, h_ext_fft: &[CtG1]) -> Vec<CtG1> {
let n2 = h_ext_fft.len();
let n = n2 / 2;
let mut ret = self.fft_g1(h_ext_fft, true).unwrap();
ret[n..n2].copy_from_slice(&vec![CtG1::identity(); n2 - n]);
ret
}
}
impl CtPoly {
pub fn toeplitz_coeffs_stride(&self, offset: usize, stride: usize) -> CtPoly {
let n = self.len();
let k = n / stride;
let k2 = k * 2;
let mut ret = CtPoly::default();
ret.coeffs.push(self.coeffs[n - 1 - offset]);
let num_of_zeroes = if k + 2 < k2 { k + 2 - 1 } else { k2 - 1 };
for _ in 0..num_of_zeroes {
ret.coeffs.push(CtFr::zero());
}
let mut i = k + 2;
let mut j = 2 * stride - offset - 1;
while i < k2 {
ret.coeffs.push(self.coeffs[j]);
i += 1;
j += stride;
}
ret
}
pub fn toeplitz_coeffs_step(&self) -> CtPoly {
self.toeplitz_coeffs_stride(0, 1)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/utils.rs | constantine/src/utils.rs | extern crate alloc;
use alloc::vec::Vec;
use kzg::common_utils::log2_pow2;
use kzg::eip_4844::{hash_to_bls_field, PrecomputationTableManager};
use kzg::eth::c_bindings::CKZGSettings;
use kzg::{eth, FFTSettings, Fr, G1Mul, G2Mul, FFTG1, G1, G2};
use crate::types::fft_settings::CtFFTSettings;
use crate::types::fp::CtFp;
use crate::types::fr::CtFr;
use crate::types::g1::{CtG1, CtG1Affine, CtG1ProjAddAffine};
use crate::types::g2::CtG2;
pub fn generate_trusted_setup(
n: usize,
secret: [u8; 32usize],
) -> (Vec<CtG1>, Vec<CtG1>, Vec<CtG2>) {
let s = hash_to_bls_field(&secret);
let mut s_pow = Fr::one();
let mut g1_monomial_values = Vec::with_capacity(n);
let mut g2_monomial_values = Vec::with_capacity(n);
for _ in 0..n {
g1_monomial_values.push(CtG1::generator().mul(&s_pow));
g2_monomial_values.push(CtG2::generator().mul(&s_pow));
s_pow = s_pow.mul(&s);
}
let s = CtFFTSettings::new(log2_pow2(n)).unwrap();
let g1_lagrange_values = s.fft_g1(&g1_monomial_values, true).unwrap();
(g1_monomial_values, g1_lagrange_values, g2_monomial_values)
}
pub fn ptr_transmute<T, U>(t: &T) -> *const U {
assert_eq!(core::mem::size_of::<T>(), core::mem::size_of::<U>());
t as *const T as *const U
}
pub fn ptr_transmute_mut<T, U>(t: &mut T) -> *mut U {
assert_eq!(core::mem::size_of::<T>(), core::mem::size_of::<U>());
t as *mut T as *mut U
}
pub(crate) fn fft_settings_to_rust(
c_settings: *const CKZGSettings,
) -> Result<CtFFTSettings, String> {
let settings = unsafe { &*c_settings };
let roots_of_unity = unsafe {
core::slice::from_raw_parts(
settings.roots_of_unity,
eth::FIELD_ELEMENTS_PER_EXT_BLOB + 1,
)
.iter()
.map(|r| CtFr::from_blst_fr(*r))
.collect::<Vec<CtFr>>()
};
let brp_roots_of_unity = unsafe {
core::slice::from_raw_parts(
settings.brp_roots_of_unity,
eth::FIELD_ELEMENTS_PER_EXT_BLOB,
)
.iter()
.map(|r| CtFr::from_blst_fr(*r))
.collect::<Vec<CtFr>>()
};
let reverse_roots_of_unity = unsafe {
core::slice::from_raw_parts(
settings.reverse_roots_of_unity,
eth::FIELD_ELEMENTS_PER_EXT_BLOB + 1,
)
.iter()
.map(|r| CtFr::from_blst_fr(*r))
.collect::<Vec<CtFr>>()
};
Ok(CtFFTSettings {
max_width: eth::FIELD_ELEMENTS_PER_EXT_BLOB,
root_of_unity: roots_of_unity[1],
roots_of_unity,
brp_roots_of_unity,
reverse_roots_of_unity,
})
}
pub(crate) static mut PRECOMPUTATION_TABLES: PrecomputationTableManager<
CtFr,
CtG1,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
> = PrecomputationTableManager::new();
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/fft_g1.rs | constantine/src/fft_g1.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::{Fr, G1Mul, FFTG1, G1};
use crate::types::fft_settings::CtFFTSettings;
use crate::types::fr::CtFr;
use crate::types::g1::CtG1;
pub fn fft_g1_fast(
ret: &mut [CtG1],
data: &[CtG1],
stride: usize,
roots: &[CtFr],
roots_stride: usize,
) {
let half = ret.len() / 2;
if half > 0 {
#[cfg(feature = "parallel")]
{
let (lo, hi) = ret.split_at_mut(half);
rayon::join(
|| fft_g1_fast(lo, data, stride * 2, roots, roots_stride * 2),
|| fft_g1_fast(hi, &data[stride..], stride * 2, roots, roots_stride * 2),
);
}
#[cfg(not(feature = "parallel"))]
{
fft_g1_fast(&mut ret[..half], data, stride * 2, roots, roots_stride * 2);
fft_g1_fast(
&mut ret[half..],
&data[stride..],
stride * 2,
roots,
roots_stride * 2,
);
}
for i in 0..half {
let y_times_root = ret[i + half].mul(&roots[i * roots_stride]);
ret[i + half] = ret[i].sub(&y_times_root);
ret[i] = ret[i].add_or_dbl(&y_times_root);
}
} else {
ret[0] = data[0];
}
}
impl FFTG1<CtG1> for CtFFTSettings {
fn fft_g1(&self, data: &[CtG1], inverse: bool) -> Result<Vec<CtG1>, String> {
if data.len() > self.max_width {
return Err(String::from(
"Supplied list is longer than the available max width",
));
} else if !data.len().is_power_of_two() {
return Err(String::from("A list with power-of-two length expected"));
}
let stride = self.max_width / data.len();
let mut ret = vec![CtG1::default(); data.len()];
let roots = if inverse {
&self.reverse_roots_of_unity
} else {
&self.roots_of_unity
};
fft_g1_fast(&mut ret, data, 1, roots, stride);
if inverse {
let inv_fr_len = CtFr::from_u64(data.len() as u64).inverse();
ret[..data.len()]
.iter_mut()
.for_each(|f| *f = f.mul(&inv_fr_len));
}
Ok(ret)
}
}
// Used for testing
pub fn fft_g1_slow(
ret: &mut [CtG1],
data: &[CtG1],
stride: usize,
roots: &[CtFr],
roots_stride: usize,
) {
for i in 0..data.len() {
// Evaluate first member at 1
ret[i] = data[0].mul(&roots[0]);
// Evaluate the rest of members using a step of (i * J) % data.len() over the roots
// This distributes the roots over correct x^n members and saves on multiplication
for j in 1..data.len() {
let v = data[j * stride].mul(&roots[((i * j) % data.len()) * roots_stride]);
ret[i] = ret[i].add_or_dbl(&v);
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/fft_fr.rs | constantine/src/fft_fr.rs | extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::{FFTFr, Fr};
use crate::types::fft_settings::CtFFTSettings;
use crate::types::fr::CtFr;
/// Fast Fourier Transform for finite field elements. Polynomial ret is operated on in reverse order: ret_i * x ^ (len - i - 1)
pub fn fft_fr_fast(
ret: &mut [CtFr],
data: &[CtFr],
stride: usize,
roots: &[CtFr],
roots_stride: usize,
) {
let half: usize = ret.len() / 2;
if half > 0 {
// Recurse
// Offsetting data by stride = 1 on the first iteration forces the even members to the first half
// and the odd members to the second half
#[cfg(not(feature = "parallel"))]
{
fft_fr_fast(&mut ret[..half], data, stride * 2, roots, roots_stride * 2);
fft_fr_fast(
&mut ret[half..],
&data[stride..],
stride * 2,
roots,
roots_stride * 2,
);
}
#[cfg(feature = "parallel")]
{
if half > 256 {
let (lo, hi) = ret.split_at_mut(half);
rayon::join(
|| fft_fr_fast(lo, data, stride * 2, roots, roots_stride * 2),
|| fft_fr_fast(hi, &data[stride..], stride * 2, roots, roots_stride * 2),
);
} else {
fft_fr_fast(&mut ret[..half], data, stride * 2, roots, roots_stride * 2);
fft_fr_fast(
&mut ret[half..],
&data[stride..],
stride * 2,
roots,
roots_stride * 2,
);
}
}
for i in 0..half {
let y_times_root = ret[i + half].mul(&roots[i * roots_stride]);
ret[i + half] = ret[i].sub(&y_times_root);
ret[i] = ret[i].add(&y_times_root);
}
} else {
// When len = 1, return the permuted element
ret[0] = data[0];
}
}
impl CtFFTSettings {
/// Fast Fourier Transform for finite field elements, `output` must be zeroes
pub(crate) fn fft_fr_output(
&self,
data: &[CtFr],
inverse: bool,
output: &mut [CtFr],
) -> Result<(), String> {
if data.len() > self.max_width {
return Err(String::from(
"Supplied list is longer than the available max width",
));
}
if data.len() != output.len() {
return Err(format!(
"Output length {} doesn't match data length {}",
data.len(),
output.len()
));
}
if !data.len().is_power_of_two() {
return Err(String::from("A list with power-of-two length expected"));
}
// In case more roots are provided with fft_settings, use a larger stride
let stride = self.max_width / data.len();
// Inverse is same as regular, but all constants are reversed and results are divided by n
// This is a property of the DFT matrix
let roots = if inverse {
&self.reverse_roots_of_unity
} else {
&self.roots_of_unity
};
fft_fr_fast(output, data, 1, roots, stride);
if inverse {
let inv_fr_len = CtFr::from_u64(data.len() as u64).inverse();
output.iter_mut().for_each(|f| *f = f.mul(&inv_fr_len));
}
Ok(())
}
}
impl FFTFr<CtFr> for CtFFTSettings {
/// Fast Fourier Transform for finite field elements
fn fft_fr(&self, data: &[CtFr], inverse: bool) -> Result<Vec<CtFr>, String> {
let mut ret = vec![CtFr::default(); data.len()];
self.fft_fr_output(data, inverse, &mut ret)?;
Ok(ret)
}
}
/// Simplified Discrete Fourier Transform, mainly used for testing
pub fn fft_fr_slow(
ret: &mut [CtFr],
data: &[CtFr],
stride: usize,
roots: &[CtFr],
roots_stride: usize,
) {
for i in 0..data.len() {
// Evaluate first member at 1
ret[i] = data[0].mul(&roots[0]);
// Evaluate the rest of members using a step of (i * J) % data.len() over the roots
// This distributes the roots over correct x^n members and saves on multiplication
for j in 1..data.len() {
let v = data[j * stride].mul(&roots[((i * j) % data.len()) * roots_stride]);
ret[i] = ret[i].add(&v);
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/recovery.rs | constantine/src/recovery.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use kzg::{FFTFr, Fr, PolyRecover, ZeroPoly};
use crate::types::fft_settings::CtFFTSettings;
use crate::types::fr::CtFr;
use crate::types::poly::CtPoly;
use once_cell::sync::OnceCell;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
const SCALE_FACTOR: u64 = 5;
static INVERSE_FACTORS: OnceCell<Vec<CtFr>> = OnceCell::new();
static UNSCALE_FACTOR_POWERS: OnceCell<Vec<CtFr>> = OnceCell::new();
pub fn scale_poly(p: &mut [CtFr], len_p: usize) {
let factors = INVERSE_FACTORS.get_or_init(|| {
let scale_factor = CtFr::from_u64(SCALE_FACTOR);
let inv_factor = CtFr::inverse(&scale_factor);
let mut temp = Vec::with_capacity(65536);
temp.push(CtFr::one());
for i in 1..65536 {
temp.push(temp[i - 1].mul(&inv_factor));
}
temp
});
p.iter_mut()
.zip(factors)
.take(len_p)
.skip(1)
.for_each(|(p, factor)| {
*p = p.mul(factor);
});
}
pub fn unscale_poly(p: &mut [CtFr], len_p: usize) {
let factors = UNSCALE_FACTOR_POWERS.get_or_init(|| {
let scale_factor = CtFr::from_u64(SCALE_FACTOR);
let mut temp = Vec::with_capacity(65536);
temp.push(CtFr::one());
for i in 1..65536 {
temp.push(temp[i - 1].mul(&scale_factor));
}
temp
});
p.iter_mut()
.zip(factors)
.take(len_p)
.skip(1)
.for_each(|(p, factor)| {
*p = p.mul(factor);
});
}
impl PolyRecover<CtFr, CtPoly, CtFFTSettings> for CtPoly {
fn recover_poly_coeffs_from_samples(
samples: &[Option<CtFr>],
fs: &CtFFTSettings,
) -> Result<Self, String> {
let len_samples = samples.len();
if !len_samples.is_power_of_two() {
return Err(String::from(
"Samples must have a length that is a power of two",
));
}
let mut missing = Vec::with_capacity(len_samples / 2);
for (i, sample) in samples.iter().enumerate() {
if sample.is_none() {
missing.push(i);
}
}
if missing.len() > len_samples / 2 {
return Err(String::from(
"Impossible to recover, too many shards are missing",
));
}
// Calculate `Z_r,I`
let (zero_eval, mut zero_poly) = fs.zero_poly_via_multiplication(len_samples, &missing)?;
// Construct E * Z_r,I: the loop makes the evaluation polynomial
let poly_evaluations_with_zero = samples
.iter()
.zip(zero_eval)
.map(|(maybe_sample, zero_eval)| {
debug_assert_eq!(maybe_sample.is_none(), zero_eval.is_zero());
match maybe_sample {
Some(sample) => sample.mul(&zero_eval),
None => CtFr::zero(),
}
})
.collect::<Vec<_>>();
// Now inverse FFT so that poly_with_zero is (E * Z_r,I)(x) = (D * Z_r,I)(x)
let mut poly_with_zero = fs.fft_fr(&poly_evaluations_with_zero, true).unwrap();
drop(poly_evaluations_with_zero);
// x -> k * x
let len_zero_poly = zero_poly.coeffs.len();
scale_poly(&mut poly_with_zero, len_samples);
scale_poly(&mut zero_poly.coeffs, len_zero_poly);
// Q1 = (D * Z_r,I)(k * x)
let scaled_poly_with_zero = poly_with_zero;
// Q2 = Z_r,I(k * x)
let scaled_zero_poly = zero_poly.coeffs;
// Polynomial division by convolution: Q3 = Q1 / Q2
#[cfg(feature = "parallel")]
let (eval_scaled_poly_with_zero, eval_scaled_zero_poly) = {
if len_zero_poly - 1 > 1024 {
rayon::join(
|| fs.fft_fr(&scaled_poly_with_zero, false).unwrap(),
|| fs.fft_fr(&scaled_zero_poly, false).unwrap(),
)
} else {
(
fs.fft_fr(&scaled_poly_with_zero, false).unwrap(),
fs.fft_fr(&scaled_zero_poly, false).unwrap(),
)
}
};
#[cfg(not(feature = "parallel"))]
let (eval_scaled_poly_with_zero, eval_scaled_zero_poly) = {
(
fs.fft_fr(&scaled_poly_with_zero, false).unwrap(),
fs.fft_fr(&scaled_zero_poly, false).unwrap(),
)
};
drop(scaled_zero_poly);
let mut eval_scaled_reconstructed_poly = eval_scaled_poly_with_zero;
#[cfg(not(feature = "parallel"))]
let eval_scaled_reconstructed_poly_iter = eval_scaled_reconstructed_poly.iter_mut();
#[cfg(feature = "parallel")]
let eval_scaled_reconstructed_poly_iter = eval_scaled_reconstructed_poly.par_iter_mut();
eval_scaled_reconstructed_poly_iter
.zip(eval_scaled_zero_poly)
.for_each(
|(eval_scaled_reconstructed_poly, eval_scaled_poly_with_zero)| {
*eval_scaled_reconstructed_poly = eval_scaled_reconstructed_poly
.div(&eval_scaled_poly_with_zero)
.unwrap();
},
);
// The result of the division is D(k * x):
let mut scaled_reconstructed_poly =
fs.fft_fr(&eval_scaled_reconstructed_poly, true).unwrap();
drop(eval_scaled_reconstructed_poly);
// k * x -> x
unscale_poly(&mut scaled_reconstructed_poly, len_samples);
// Finally we have D(x) which evaluates to our original data at the powers of roots of unity
Ok(Self {
coeffs: scaled_reconstructed_poly,
})
}
fn recover_poly_from_samples(
samples: &[Option<CtFr>],
fs: &CtFFTSettings,
) -> Result<Self, String> {
let reconstructed_poly = Self::recover_poly_coeffs_from_samples(samples, fs)?;
// The evaluation polynomial for D(x) is the reconstructed data:
let reconstructed_data = fs.fft_fr(&reconstructed_poly.coeffs, false).unwrap();
// Check all is well
samples
.iter()
.zip(&reconstructed_data)
.for_each(|(sample, reconstructed_data)| {
debug_assert!(sample.is_none() || reconstructed_data.equals(&sample.unwrap()));
});
Ok(Self {
coeffs: reconstructed_data,
})
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/mixed_kzg/mixed_kzg_settings.rs | constantine/src/mixed_kzg/mixed_kzg_settings.rs | use core::{marker::PhantomPinned, pin::Pin};
use std::path::Path;
use crate::types::{
fft_settings::CtFFTSettings,
fp::CtFp,
fr::CtFr,
g1::{CtG1, CtG1Affine, CtG1ProjAddAffine},
g2::CtG2,
kzg_settings::CtKZGSettings as GenericContext,
poly::CtPoly,
};
use constantine_core::Threadpool as CttThreadpool;
use constantine_ethereum_kzg::EthKzgContext as CttEthKzgContext;
use constantine_sys::{ctt_eth_kzg_status, ctt_eth_trusted_setup_status};
use kzg::KZGSettings;
use super::mixed_eip_4844::verify_kzg_proof_mixed;
struct CttContextInner<'a> {
ctx: Option<CttEthKzgContext<'a>>,
pool: Option<CttThreadpool>,
_pin: PhantomPinned,
}
pub struct CttContext<'a>(Pin<Box<CttContextInner<'a>>>);
impl CttContext<'_> {
pub fn new(path: &Path) -> Result<Self, ctt_eth_trusted_setup_status> {
let context = CttEthKzgContext::builder().load_trusted_setup(path)?;
#[cfg(feature = "parallel")]
let this = {
let mut this = Box::new(CttContextInner {
pool: Some(CttThreadpool::new(
constantine_core::hardware::get_num_threads_os(),
)),
ctx: None,
_pin: PhantomPinned,
});
this.ctx = Some(
context
.set_threadpool(unsafe {
core::ptr::NonNull::from(this.pool.as_ref().unwrap()).as_ref()
})
.build()?,
);
this
};
#[cfg(not(feature = "parallel"))]
let this = {
Box::new(CttContextInner {
pool: None,
ctx: Some(context.build()?),
_pin: PhantomPinned,
})
};
let pin = Box::into_pin(this);
Ok(CttContext(pin))
}
pub fn blob_to_kzg_commitment(
&self,
blob: &[u8; 4096 * 32],
) -> Result<[u8; 48], ctt_eth_kzg_status> {
#[cfg(feature = "parallel")]
return self
.0
.ctx
.as_ref()
.unwrap()
.blob_to_kzg_commitment_parallel(blob);
#[cfg(not(feature = "parallel"))]
return self.0.ctx.as_ref().unwrap().blob_to_kzg_commitment(blob);
}
pub fn compute_kzg_proof(
&self,
blob: &[u8; 4096 * 32],
z_challenge: &[u8; 32],
) -> Result<([u8; 48], [u8; 32]), ctt_eth_kzg_status> {
#[cfg(feature = "parallel")]
return self
.0
.ctx
.as_ref()
.unwrap()
.compute_kzg_proof_parallel(blob, z_challenge);
#[cfg(not(feature = "parallel"))]
return self
.0
.ctx
.as_ref()
.unwrap()
.compute_kzg_proof(blob, z_challenge);
}
pub fn compute_blob_kzg_proof(
&self,
blob: &[u8; 4096 * 32],
commitment: &[u8; 48],
) -> Result<[u8; 48], ctt_eth_kzg_status> {
#[cfg(feature = "parallel")]
return self
.0
.ctx
.as_ref()
.unwrap()
.compute_blob_kzg_proof_parallel(blob, commitment);
#[cfg(not(feature = "parallel"))]
return self
.0
.ctx
.as_ref()
.unwrap()
.compute_blob_kzg_proof(blob, commitment);
}
pub fn verify_kzg_proof(
&self,
commitment: &[u8; 48],
z_challenge: &[u8; 32],
y_eval_at_challenge: &[u8; 32],
proof: &[u8; 48],
) -> Result<bool, ctt_eth_kzg_status> {
self.0.ctx.as_ref().unwrap().verify_kzg_proof(
commitment,
z_challenge,
y_eval_at_challenge,
proof,
)
}
pub fn verify_blob_kzg_proof(
&self,
blob: &[u8; 4096 * 32],
commitment: &[u8; 48],
proof: &[u8; 48],
) -> Result<bool, ctt_eth_kzg_status> {
#[cfg(feature = "parallel")]
return self
.0
.ctx
.as_ref()
.unwrap()
.verify_blob_kzg_proof_parallel(blob, commitment, proof);
#[cfg(not(feature = "parallel"))]
return self
.0
.ctx
.as_ref()
.unwrap()
.verify_blob_kzg_proof(blob, commitment, proof);
}
pub fn verify_blob_kzg_proof_batch(
&self,
blobs: &[[u8; 4096 * 32]],
commitments: &[[u8; 48]],
proofs: &[[u8; 48]],
secure_random_bytes: &[u8; 32],
) -> Result<bool, ctt_eth_kzg_status> {
#[cfg(feature = "parallel")]
return self
.0
.ctx
.as_ref()
.unwrap()
.verify_blob_kzg_proof_batch_parallel(blobs, commitments, proofs, secure_random_bytes);
#[cfg(not(feature = "parallel"))]
return self.0.ctx.as_ref().unwrap().verify_blob_kzg_proof_batch(
blobs,
commitments,
proofs,
secure_random_bytes,
);
}
}
// Constantine requires loading from path + doesn't expose underlying secrets, but sometimes required for tests
#[allow(clippy::large_enum_variant)]
pub enum MixedKzgSettings<'a> {
Constantine(CttContext<'a>),
Generic(GenericContext),
}
pub trait LocalToStr {
fn to_string(&self) -> String;
}
impl LocalToStr for ctt_eth_trusted_setup_status {
fn to_string(&self) -> String {
match self {
ctt_eth_trusted_setup_status::cttEthTS_InvalidFile => "invalid file".to_owned(),
ctt_eth_trusted_setup_status::cttEthTS_MissingOrInaccessibleFile => {
"missing or inaccessible file".to_owned()
}
ctt_eth_trusted_setup_status::cttEthTS_Success => "success".to_owned(),
}
}
}
impl LocalToStr for ctt_eth_kzg_status {
fn to_string(&self) -> String {
format!("{:?}", self)
}
}
impl MixedKzgSettings<'_> {
pub fn new(
g1_monomial: &[CtG1],
g1_lagrange_brp: &[CtG1],
g2_monomial: &[CtG2],
fft_settings: &CtFFTSettings,
cell_size: usize,
) -> Result<Self, String> {
let res = GenericContext::new(
g1_monomial,
g1_lagrange_brp,
g2_monomial,
fft_settings,
cell_size,
);
match res {
Ok(generic_context) => Ok(Self::Generic(generic_context)),
Err(x) => Err(x),
}
}
pub fn new_from_path(path: &Path) -> Result<Self, String> {
Ok(Self::Constantine(
CttContext::new(path).map_err(|e| e.to_string())?,
))
}
}
impl Default for MixedKzgSettings<'_> {
fn default() -> Self {
Self::Generic(GenericContext::default())
}
}
impl Clone for MixedKzgSettings<'_> {
fn clone(&self) -> Self {
match self {
Self::Constantine(_) => panic!("Cannot clone constantine context"),
Self::Generic(arg0) => Self::Generic(arg0.clone()),
}
}
}
// Allow using MixedKzgSettings as KZGSettings stand-in
impl KZGSettings<CtFr, CtG1, CtG2, CtFFTSettings, CtPoly, CtFp, CtG1Affine, CtG1ProjAddAffine>
for MixedKzgSettings<'_>
{
fn new(
g1_monomial: &[CtG1],
g1_lagrange_brp: &[CtG1],
g2_monomial: &[CtG2],
fft_settings: &CtFFTSettings,
cell_size: usize,
) -> Result<Self, String> {
MixedKzgSettings::new(
g1_monomial,
g1_lagrange_brp,
g2_monomial,
fft_settings,
cell_size,
)
}
fn commit_to_poly(&self, p: &CtPoly) -> Result<CtG1, String> {
match self {
MixedKzgSettings::Constantine(_) => Err("Context not in generic format".to_string()),
MixedKzgSettings::Generic(generic_context) => generic_context.commit_to_poly(p),
}
}
fn compute_proof_single(&self, p: &CtPoly, x: &CtFr) -> Result<CtG1, String> {
match self {
MixedKzgSettings::Constantine(_) => Err("Context not in generic format".to_string()),
MixedKzgSettings::Generic(generic_context) => {
generic_context.compute_proof_single(p, x)
}
}
}
fn check_proof_single(
&self,
com: &CtG1,
proof: &CtG1,
x: &CtFr,
value: &CtFr,
) -> Result<bool, String> {
verify_kzg_proof_mixed(com, x, value, proof, self)
}
fn compute_proof_multi(&self, p: &CtPoly, x: &CtFr, n: usize) -> Result<CtG1, String> {
match self {
MixedKzgSettings::Constantine(_) => Err("Context not in generic format".to_string()),
MixedKzgSettings::Generic(generic_context) => {
generic_context.compute_proof_multi(p, x, n)
}
}
}
fn check_proof_multi(
&self,
com: &CtG1,
proof: &CtG1,
x: &CtFr,
values: &[CtFr],
n: usize,
) -> Result<bool, String> {
match self {
MixedKzgSettings::Constantine(_) => Err("Context not in generic format".to_string()),
MixedKzgSettings::Generic(generic_context) => {
generic_context.check_proof_multi(com, proof, x, values, n)
}
}
}
fn get_roots_of_unity_at(&self, i: usize) -> CtFr {
match self {
MixedKzgSettings::Constantine(_) => {
panic!("Context not in generic format")
}
MixedKzgSettings::Generic(generic_context) => generic_context.get_roots_of_unity_at(i),
}
}
fn get_fft_settings(&self) -> &CtFFTSettings {
match self {
MixedKzgSettings::Constantine(_) => {
panic!("Context not in generic format")
}
MixedKzgSettings::Generic(generic_context) => generic_context.get_fft_settings(),
}
}
fn get_precomputation(
&self,
) -> Option<
&kzg::msm::precompute::PrecomputationTable<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>,
> {
match self {
MixedKzgSettings::Constantine(_) => {
panic!("Context not in generic format")
}
MixedKzgSettings::Generic(generic_context) => generic_context.get_precomputation(),
}
}
fn get_g1_monomial(&self) -> &[CtG1] {
match self {
MixedKzgSettings::Constantine(_) => {
panic!("Context not in generic format")
}
MixedKzgSettings::Generic(generic_context) => generic_context.get_g1_monomial(),
}
}
fn get_g1_lagrange_brp(&self) -> &[CtG1] {
match self {
MixedKzgSettings::Constantine(_) => {
panic!("Context not in generic format")
}
MixedKzgSettings::Generic(generic_context) => generic_context.get_g1_lagrange_brp(),
}
}
fn get_g2_monomial(&self) -> &[CtG2] {
match self {
MixedKzgSettings::Constantine(_) => {
panic!("Context not in generic format")
}
MixedKzgSettings::Generic(generic_context) => generic_context.get_g2_monomial(),
}
}
fn get_x_ext_fft_columns(&self) -> &[Vec<CtG1>] {
match self {
MixedKzgSettings::Constantine(_) => {
panic!("Context not in generic format")
}
MixedKzgSettings::Generic(generic_context) => generic_context.get_x_ext_fft_columns(),
}
}
fn get_cell_size(&self) -> usize {
match self {
MixedKzgSettings::Constantine(_) => {
panic!("Context not in generic format")
}
MixedKzgSettings::Generic(generic_context) => generic_context.get_cell_size(),
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/mixed_kzg/mod.rs | constantine/src/mixed_kzg/mod.rs | pub mod mixed_eip_4844;
pub mod mixed_kzg_settings;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/mixed_kzg/mixed_eip_4844.rs | constantine/src/mixed_kzg/mixed_eip_4844.rs | use std::path::Path;
// use crate::
use crate::mixed_kzg::mixed_kzg_settings::MixedKzgSettings;
use crate::types::{fr::CtFr, g1::CtG1};
use kzg::eip_4844::{
blob_to_kzg_commitment_rust, compute_blob_kzg_proof_rust, compute_kzg_proof_rust,
verify_blob_kzg_proof_batch_rust, verify_blob_kzg_proof_rust, verify_kzg_proof_rust,
BYTES_PER_BLOB, FIELD_ELEMENTS_PER_BLOB,
};
use kzg::{Fr, G1};
use super::mixed_kzg_settings::LocalToStr;
fn blob_fr_to_byte_inplace(blob: &[CtFr], inplace: &mut [u8; BYTES_PER_BLOB]) -> Option<String> {
if blob.len() != FIELD_ELEMENTS_PER_BLOB {
return Some("blob length is not equal to FIELD_ELEMENTS_PER_BLOB".to_string());
}
for i in 0..FIELD_ELEMENTS_PER_BLOB {
inplace[i * 32..(i + 1) * 32].copy_from_slice(&blob[i].to_bytes());
}
None
}
fn blob_fr_to_byte(blob: &[CtFr]) -> Result<[u8; BYTES_PER_BLOB], String> {
if blob.len() != FIELD_ELEMENTS_PER_BLOB {
return Err("blob length is not equal to FIELD_ELEMENTS_PER_BLOB".to_string());
}
let mut blob_bytes = [0u8; BYTES_PER_BLOB];
for i in 0..FIELD_ELEMENTS_PER_BLOB {
blob_bytes[i * 32..(i + 1) * 32].copy_from_slice(&blob[i].to_bytes());
}
Ok(blob_bytes)
// unsafe { Ok(std::mem::transmute(blob.as_ptr() as *const [u8; BYTES_PER_BLOB])) }
}
pub fn load_trusted_setup_filename_mixed(
filepath: &str,
) -> Result<MixedKzgSettings<'static>, String> {
MixedKzgSettings::new_from_path(Path::new(filepath))
}
pub fn blob_to_kzg_commitment_mixed(
blob: &[CtFr],
settings: &MixedKzgSettings,
) -> Result<CtG1, String> {
match settings {
MixedKzgSettings::Constantine(ctt_context) => {
let blob_bytes = blob_fr_to_byte(blob)?;
ctt_context
.blob_to_kzg_commitment(&blob_bytes)
.map_err(|e| e.to_string())
.and_then(|b| CtG1::from_bytes(&b))
}
MixedKzgSettings::Generic(generic_context) => {
blob_to_kzg_commitment_rust(blob, generic_context)
}
}
}
pub fn compute_kzg_proof_mixed(
blob: &[CtFr],
z: &CtFr,
s: &MixedKzgSettings,
) -> Result<(CtG1, CtFr), String> {
match s {
MixedKzgSettings::Constantine(ctt_context) => {
let blob_bytes = blob_fr_to_byte(blob)?;
ctt_context
.compute_kzg_proof(&blob_bytes, &z.to_bytes())
.map_err(|e| e.to_string())
.and_then(|(proof, y)| Ok((CtG1::from_bytes(&proof)?, CtFr::from_bytes(&y)?)))
}
MixedKzgSettings::Generic(generic_context) => {
compute_kzg_proof_rust(blob, z, generic_context)
}
}
}
pub fn compute_blob_kzg_proof_mixed(
blob: &[CtFr],
commitment: &CtG1,
ts: &MixedKzgSettings,
) -> Result<CtG1, String> {
match ts {
MixedKzgSettings::Constantine(ctt_context) => {
let blob_bytes = blob_fr_to_byte(blob)?;
ctt_context
.compute_blob_kzg_proof(&blob_bytes, &commitment.to_bytes())
.map_err(|e| e.to_string())
.and_then(|proof| CtG1::from_bytes(&proof))
}
MixedKzgSettings::Generic(generic_context) => {
compute_blob_kzg_proof_rust(blob, commitment, generic_context)
}
}
}
pub fn verify_kzg_proof_mixed(
commitment: &CtG1,
z: &CtFr,
y: &CtFr,
proof: &CtG1,
s: &MixedKzgSettings,
) -> Result<bool, String> {
match s {
MixedKzgSettings::Constantine(ctt_context) => ctt_context
.verify_kzg_proof(
&commitment.to_bytes(),
&z.to_bytes(),
&y.to_bytes(),
&proof.to_bytes(),
)
.map_err(|e| e.to_string()),
MixedKzgSettings::Generic(generic_context) => {
verify_kzg_proof_rust(commitment, z, y, proof, generic_context)
}
}
}
pub fn verify_blob_kzg_proof_mixed(
blob: &[CtFr],
commitment_g1: &CtG1,
proof_g1: &CtG1,
ts: &MixedKzgSettings,
) -> Result<bool, String> {
match ts {
MixedKzgSettings::Constantine(ctt_context) => {
let blob_bytes = blob_fr_to_byte(blob)?;
ctt_context
.verify_blob_kzg_proof(&blob_bytes, &commitment_g1.to_bytes(), &proof_g1.to_bytes())
.map_err(|e| e.to_string())
}
MixedKzgSettings::Generic(generic_context) => {
verify_blob_kzg_proof_rust(blob, commitment_g1, proof_g1, generic_context)
}
}
}
pub fn verify_blob_kzg_proof_batch_mixed(
blobs: &[Vec<CtFr>],
commitments_g1: &[CtG1],
proofs_g1: &[CtG1],
ts: &MixedKzgSettings,
) -> Result<bool, String> {
match ts {
MixedKzgSettings::Constantine(ctt_context) => {
let mut blobs_storage = vec![[0u8; BYTES_PER_BLOB]; blobs.len()];
for (i, blob) in blobs.iter().enumerate() {
let res = blob_fr_to_byte_inplace(blob, &mut blobs_storage[i]);
if let Some(res) = res {
return Err(res);
}
}
let commitments = commitments_g1
.iter()
.map(|x| x.to_bytes())
.collect::<Vec<_>>();
let proofs_g1 = proofs_g1.iter().map(|x| x.to_bytes()).collect::<Vec<_>>();
let rand_thing = rand::random();
ctt_context
.verify_blob_kzg_proof_batch(
blobs_storage.as_slice(),
commitments.as_slice(),
proofs_g1.as_slice(),
&rand_thing,
)
.map_err(|e| e.to_string())
}
MixedKzgSettings::Generic(generic_context) => {
verify_blob_kzg_proof_batch_rust(blobs, commitments_g1, proofs_g1, generic_context)
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/fr.rs | constantine/src/types/fr.rs | //blst_fp = bls12_381_fp, CtG1 = CtG1, blst_p1 = bls12_381_g1_jac, blst_fr = bls12_381_fr
extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use arbitrary::Arbitrary;
use constantine::ctt_codec_scalar_status;
use core::fmt::{Debug, Formatter};
use kzg::eip_4844::BYTES_PER_FIELD_ELEMENT;
use kzg::eth::c_bindings::blst_fr;
use kzg::Fr;
use kzg::Scalar256;
use constantine_sys as constantine;
use constantine_sys::bls12_381_fr;
use crate::utils::ptr_transmute;
use crate::utils::ptr_transmute_mut;
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub struct CtFr(pub bls12_381_fr);
impl<'a> Arbitrary<'a> for CtFr {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let bytes: [u8; 32] = u.arbitrary()?;
Ok(CtFr::from_bytes_unchecked(&bytes).unwrap())
}
}
impl Debug for CtFr {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "CtFr({:?})", self.0.limbs)
}
}
impl PartialEq for CtFr {
fn eq(&self, other: &Self) -> bool {
self.equals(other)
}
}
impl Eq for CtFr {}
impl CtFr {
pub fn from_blst_fr(fr: blst_fr) -> Self {
unsafe {
Self(bls12_381_fr {
limbs: core::mem::transmute::<[u64; 4], [usize; 4]>(fr.l),
})
}
}
pub fn to_blst_fr(&self) -> blst_fr {
unsafe {
blst_fr {
l: core::mem::transmute::<[usize; 4], [u64; 4]>(self.0.limbs),
}
}
}
}
impl Fr for CtFr {
fn null() -> Self {
Self::from_u64_arr(&[u64::MAX, u64::MAX, u64::MAX, u64::MAX])
}
fn zero() -> Self {
Self::from_u64(0)
}
fn one() -> Self {
Self::from_u64(1)
}
#[cfg(feature = "rand")]
fn rand() -> Self {
let val = constantine_sys::big255 {
limbs: [
rand::random(),
rand::random(),
rand::random(),
rand::random(),
],
};
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_fr_from_big255(&mut ret.0, &val);
}
ret
}
fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
bytes
.try_into()
.map_err(|_| {
format!(
"Invalid byte length. Expected {}, got {}",
BYTES_PER_FIELD_ELEMENT,
bytes.len()
)
})
.and_then(|bytes: &[u8; BYTES_PER_FIELD_ELEMENT]| {
let mut ret: Self = Self::default();
let mut scalar = constantine::big255::default();
unsafe {
let status =
constantine::ctt_bls12_381_deserialize_scalar(&mut scalar, bytes.as_ptr());
if status == ctt_codec_scalar_status::cttCodecScalar_ScalarLargerThanCurveOrder
{
return Err("Invalid scalar".to_string());
}
constantine::ctt_bls12_381_fr_from_big255(&mut ret.0, &scalar);
}
Ok(ret)
})
}
fn from_bytes_unchecked(bytes: &[u8]) -> Result<Self, String> {
bytes
.try_into()
.map_err(|_| {
format!(
"Invalid byte length. Expected {}, got {}",
BYTES_PER_FIELD_ELEMENT,
bytes.len()
)
})
.map(|bytes: &[u8; BYTES_PER_FIELD_ELEMENT]| {
let mut ret = Self::default();
let mut scalar = constantine::big255::default();
unsafe {
let _ = constantine::ctt_big255_unmarshalBE(
&mut scalar,
bytes.as_ptr(),
BYTES_PER_FIELD_ELEMENT,
);
constantine::ctt_bls12_381_fr_from_big255(&mut ret.0, &scalar);
}
ret
})
}
fn from_hex(hex: &str) -> Result<Self, String> {
let bytes = hex::decode(&hex[2..]).unwrap();
Self::from_bytes(&bytes)
}
fn from_u64_arr(u: &[u64; 4]) -> Self {
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_fr_from_big255(&mut ret.0, ptr_transmute(u));
}
ret
}
fn from_u64(val: u64) -> Self {
Self::from_u64_arr(&[val, 0, 0, 0])
}
fn to_bytes(&self) -> [u8; 32] {
let mut scalar = constantine::big255::default();
let mut bytes = [0u8; 32];
unsafe {
constantine::ctt_big255_from_bls12_381_fr(&mut scalar, &self.0);
let _ = constantine::ctt_bls12_381_serialize_scalar(bytes.as_mut_ptr(), &scalar);
}
bytes
}
fn to_u64_arr(&self) -> [u64; 4] {
let mut val: [u64; 4] = [0; 4];
unsafe {
constantine::ctt_big255_from_bls12_381_fr(ptr_transmute_mut(&mut val), &self.0);
}
val
}
fn is_one(&self) -> bool {
unsafe { constantine::ctt_bls12_381_fr_is_one(&self.0) != 0 }
}
fn is_zero(&self) -> bool {
unsafe { constantine::ctt_bls12_381_fr_is_zero(&self.0) != 0 }
}
fn is_null(&self) -> bool {
self.equals(&Self::null())
}
fn sqr(&self) -> Self {
let mut ret = Self::default();
unsafe { constantine::ctt_bls12_381_fr_square(&mut ret.0, &self.0) }
ret
}
fn mul(&self, b: &Self) -> Self {
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_fr_prod(&mut ret.0, &self.0, &b.0);
}
ret
}
fn add(&self, b: &Self) -> Self {
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_fr_sum(&mut ret.0, &self.0, &b.0);
}
ret
}
fn sub(&self, b: &Self) -> Self {
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_fr_diff(&mut ret.0, &self.0, &b.0);
}
ret
}
fn eucl_inverse(&self) -> Self {
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_fr_inv(&mut ret.0, &self.0);
}
ret
}
fn negate(&self) -> Self {
let mut ret = *self;
unsafe {
constantine::ctt_bls12_381_fr_neg_in_place(&mut ret.0);
}
ret
}
fn inverse(&self) -> Self {
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_fr_inv(&mut ret.0, &self.0);
}
ret
}
fn pow(&self, n: usize) -> Self {
let mut out = Self::one();
let mut temp = *self;
let mut n = n;
loop {
if (n & 1) == 1 {
out = out.mul(&temp);
}
n >>= 1;
if n == 0 {
break;
}
temp = temp.sqr();
}
out
}
fn div(&self, b: &Self) -> Result<Self, String> {
let tmp = b.eucl_inverse();
let out = self.mul(&tmp);
Ok(out)
}
fn equals(&self, b: &Self) -> bool {
unsafe { constantine::ctt_bls12_381_fr_is_eq(&self.0, &b.0) != 0 }
}
fn to_scalar(&self) -> kzg::Scalar256 {
let mut scalar = constantine::big255::default();
unsafe {
constantine::ctt_big255_from_bls12_381_fr(&mut scalar, &self.0);
Scalar256::from_u64(core::mem::transmute::<[usize; 4], [u64; 4]>(scalar.limbs))
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/fk20_single_settings.rs | constantine/src/types/fk20_single_settings.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use kzg::common_utils::reverse_bit_order;
use kzg::{FK20SingleSettings, Poly, FFTG1, G1};
use crate::types::fft_settings::CtFFTSettings;
use crate::types::fr::CtFr;
use crate::types::g1::CtG1;
use crate::types::g2::CtG2;
use crate::types::kzg_settings::CtKZGSettings;
use crate::types::poly::CtPoly;
use super::fp::CtFp;
use super::g1::{CtG1Affine, CtG1ProjAddAffine};
#[derive(Clone, Default)]
pub struct CtFK20SingleSettings {
pub kzg_settings: CtKZGSettings,
pub x_ext_fft: Vec<CtG1>,
}
impl
FK20SingleSettings<
CtFr,
CtG1,
CtG2,
CtFFTSettings,
CtPoly,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
> for CtFK20SingleSettings
{
fn new(kzg_settings: &CtKZGSettings, n2: usize) -> Result<Self, String> {
let n = n2 / 2;
if n2 > kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
} else if n2 < 2 {
return Err(String::from("n2 must be greater than or equal to 2"));
}
let mut x = Vec::with_capacity(n);
for i in 0..n - 1 {
x.push(kzg_settings.g1_values_monomial[n - 2 - i]);
}
x.push(CtG1::identity());
let x_ext_fft = kzg_settings.fs.toeplitz_part_1(&x);
drop(x);
let kzg_settings = kzg_settings.clone();
let ret = Self {
kzg_settings,
x_ext_fft,
};
Ok(ret)
}
fn data_availability(&self, p: &CtPoly) -> Result<Vec<CtG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
}
let mut ret = self.data_availability_optimized(p).unwrap();
reverse_bit_order(&mut ret)?;
Ok(ret)
}
fn data_availability_optimized(&self, p: &CtPoly) -> Result<Vec<CtG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
}
let toeplitz_coeffs = p.toeplitz_coeffs_step();
let h_ext_fft = self
.kzg_settings
.fs
.toeplitz_part_2(&toeplitz_coeffs, &self.x_ext_fft);
let h = self.kzg_settings.fs.toeplitz_part_3(&h_ext_fft);
let ret = self.kzg_settings.fs.fft_g1(&h, false).unwrap();
Ok(ret)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/kzg_settings.rs | constantine/src/types/kzg_settings.rs | extern crate alloc;
use alloc::string::String;
use alloc::sync::Arc;
use alloc::vec::Vec;
use kzg::eip_4844::{FIELD_ELEMENTS_PER_BLOB, TRUSTED_SETUP_NUM_G2_POINTS};
use kzg::eth::c_bindings::CKZGSettings;
use kzg::msm::precompute::{precompute, PrecomputationTable};
use kzg::{eth, FFTFr, FFTSettings, Fr, G1Mul, G2Mul, KZGSettings, Poly, G1, G2};
use crate::consts::{G1_GENERATOR, G2_GENERATOR};
use crate::fft_g1::fft_g1_fast;
use crate::kzg_proofs::{g1_linear_combination, pairings_verify};
use crate::types::fft_settings::CtFFTSettings;
use crate::types::fr::CtFr;
use crate::types::g1::CtG1;
use crate::types::g2::CtG2;
use crate::types::poly::CtPoly;
use crate::utils::{fft_settings_to_rust, PRECOMPUTATION_TABLES};
use super::fp::CtFp;
use super::g1::{CtG1Affine, CtG1ProjAddAffine};
#[derive(Clone, Default)]
#[allow(clippy::type_complexity)]
pub struct CtKZGSettings {
pub fs: CtFFTSettings,
pub g1_values_monomial: Vec<CtG1>,
pub g1_values_lagrange_brp: Vec<CtG1>,
pub g2_values_monomial: Vec<CtG2>,
pub precomputation:
Option<Arc<PrecomputationTable<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>>>,
pub x_ext_fft_columns: Vec<Vec<CtG1>>,
pub cell_size: usize,
}
fn toeplitz_part_1(
field_elements_per_ext_blob: usize,
output: &mut [CtG1],
x: &[CtG1],
s: &CtFFTSettings,
) -> Result<(), String> {
let n = x.len();
let n2 = n * 2;
let mut x_ext = vec![CtG1::identity(); n2];
x_ext[..n].copy_from_slice(x);
let x_ext = &x_ext[..];
/* Ensure the length is valid */
if x_ext.len() > field_elements_per_ext_blob || !x_ext.len().is_power_of_two() {
return Err("Invalid input size".to_string());
}
let roots_stride = field_elements_per_ext_blob / x_ext.len();
fft_g1_fast(output, x_ext, 1, &s.roots_of_unity, roots_stride);
Ok(())
}
impl KZGSettings<CtFr, CtG1, CtG2, CtFFTSettings, CtPoly, CtFp, CtG1Affine, CtG1ProjAddAffine>
for CtKZGSettings
{
fn new(
g1_monomial: &[CtG1],
g1_lagrange_brp: &[CtG1],
g2_monomial: &[CtG2],
fft_settings: &CtFFTSettings,
cell_size: usize,
) -> Result<Self, String> {
if g1_monomial.len() != g1_lagrange_brp.len() {
return Err("G1 point length mismatch".to_string());
}
let field_elements_per_blob = g1_monomial.len();
let field_elements_per_ext_blob = field_elements_per_blob * 2;
let n = field_elements_per_ext_blob / 2;
let k = n / cell_size;
let k2 = 2 * k;
let mut points = vec![CtG1::default(); k2];
let mut x = vec![CtG1::default(); k];
let mut x_ext_fft_columns = vec![vec![CtG1::default(); cell_size]; k2];
for offset in 0..cell_size {
let start = n - cell_size - 1 - offset;
for (i, p) in x.iter_mut().enumerate().take(k - 1) {
let j = start - i * cell_size;
*p = g1_monomial[j];
}
x[k - 1] = CtG1::identity();
toeplitz_part_1(field_elements_per_ext_blob, &mut points, &x, fft_settings)?;
for row in 0..k2 {
x_ext_fft_columns[row][offset] = points[row];
}
}
Ok(Self {
g1_values_monomial: g1_monomial.to_vec(),
g1_values_lagrange_brp: g1_lagrange_brp.to_vec(),
g2_values_monomial: g2_monomial.to_vec(),
fs: fft_settings.clone(),
precomputation: precompute(g1_lagrange_brp, &x_ext_fft_columns)
.ok()
.flatten()
.map(Arc::new),
x_ext_fft_columns,
cell_size,
})
}
fn commit_to_poly(&self, poly: &CtPoly) -> Result<CtG1, String> {
if poly.coeffs.len() > self.g1_values_monomial.len() {
return Err(String::from("Polynomial is longer than secret g1"));
}
let mut out = CtG1::default();
g1_linear_combination(
&mut out,
&self.g1_values_monomial,
&poly.coeffs,
poly.coeffs.len(),
None,
);
Ok(out)
}
fn compute_proof_single(&self, p: &CtPoly, x: &CtFr) -> Result<CtG1, String> {
if p.coeffs.is_empty() {
return Err(String::from("Polynomial must not be empty"));
}
// `-(x0^n)`, where `n` is `1`
let divisor_0 = x.negate();
// Calculate `q = p / (x^n - x0^n)` for our reduced case (see `compute_proof_multi` for
// generic implementation)
let mut out_coeffs = Vec::from(&p.coeffs[1..]);
for i in (1..out_coeffs.len()).rev() {
let tmp = out_coeffs[i].mul(&divisor_0);
out_coeffs[i - 1] = out_coeffs[i - 1].sub(&tmp);
}
let q = CtPoly { coeffs: out_coeffs };
let ret = self.commit_to_poly(&q)?;
Ok(ret)
}
fn check_proof_single(
&self,
com: &CtG1,
proof: &CtG1,
x: &CtFr,
y: &CtFr,
) -> Result<bool, String> {
let x_g2: CtG2 = G2_GENERATOR.mul(x);
let s_minus_x: CtG2 = self.g2_values_monomial[1].sub(&x_g2);
let y_g1 = G1_GENERATOR.mul(y);
let commitment_minus_y: CtG1 = com.sub(&y_g1);
Ok(pairings_verify(
&commitment_minus_y,
&G2_GENERATOR,
proof,
&s_minus_x,
))
}
fn compute_proof_multi(&self, p: &CtPoly, x0: &CtFr, n: usize) -> Result<CtG1, String> {
if p.coeffs.is_empty() {
return Err(String::from("Polynomial must not be empty"));
}
if !n.is_power_of_two() {
return Err(String::from("n must be a power of two"));
}
// Construct x^n - x0^n = (x - x0.w^0)(x - x0.w^1)...(x - x0.w^(n-1))
let mut divisor = CtPoly {
coeffs: Vec::with_capacity(n + 1),
};
// -(x0^n)
let x_pow_n = x0.pow(n);
divisor.coeffs.push(x_pow_n.negate());
// Zeros
for _ in 1..n {
divisor.coeffs.push(Fr::zero());
}
// x^n
divisor.coeffs.push(Fr::one());
let mut new_polina = p.clone();
// Calculate q = p / (x^n - x0^n)
// let q = p.div(&divisor).unwrap();
let q = new_polina.div(&divisor)?;
let ret = self.commit_to_poly(&q)?;
Ok(ret)
}
fn check_proof_multi(
&self,
com: &CtG1,
proof: &CtG1,
x: &CtFr,
ys: &[CtFr],
n: usize,
) -> Result<bool, String> {
if !n.is_power_of_two() {
return Err(String::from("n is not a power of two"));
}
// Interpolate at a coset.
let mut interp = CtPoly {
coeffs: self.fs.fft_fr(ys, true)?,
};
let inv_x = x.inverse(); // Not euclidean?
let mut inv_x_pow = inv_x;
for i in 1..n {
interp.coeffs[i] = interp.coeffs[i].mul(&inv_x_pow);
inv_x_pow = inv_x_pow.mul(&inv_x);
}
// [x^n]_2
let x_pow = inv_x_pow.inverse();
let xn2 = G2_GENERATOR.mul(&x_pow);
// [s^n - x^n]_2
let xn_minus_yn = self.g2_values_monomial[n].sub(&xn2);
// [interpolation_polynomial(s)]_1
let is1 = self.commit_to_poly(&interp).unwrap();
// [commitment - interpolation_polynomial(s)]_1 = [commit]_1 - [interpolation_polynomial(s)]_1
let commit_minus_interp = com.sub(&is1);
let ret = pairings_verify(&commit_minus_interp, &G2_GENERATOR, proof, &xn_minus_yn);
Ok(ret)
}
fn get_roots_of_unity_at(&self, i: usize) -> CtFr {
self.fs.get_roots_of_unity_at(i)
}
fn get_fft_settings(&self) -> &CtFFTSettings {
&self.fs
}
fn get_g1_lagrange_brp(&self) -> &[CtG1] {
&self.g1_values_lagrange_brp
}
fn get_g1_monomial(&self) -> &[CtG1] {
&self.g1_values_monomial
}
fn get_g2_monomial(&self) -> &[CtG2] {
&self.g2_values_monomial
}
fn get_precomputation(
&self,
) -> Option<&PrecomputationTable<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>> {
self.precomputation.as_ref().map(|v| v.as_ref())
}
fn get_x_ext_fft_columns(&self) -> &[Vec<CtG1>] {
&self.x_ext_fft_columns
}
fn get_cell_size(&self) -> usize {
self.cell_size
}
}
impl<'a> TryFrom<&'a CKZGSettings> for CtKZGSettings {
type Error = String;
fn try_from(c_settings: &'a CKZGSettings) -> Result<Self, Self::Error> {
Ok(CtKZGSettings {
fs: fft_settings_to_rust(c_settings)?,
g1_values_monomial: unsafe {
core::slice::from_raw_parts(c_settings.g1_values_monomial, FIELD_ELEMENTS_PER_BLOB)
}
.iter()
.map(|r| CtG1::from_blst_p1(*r))
.collect::<Vec<_>>(),
g1_values_lagrange_brp: unsafe {
core::slice::from_raw_parts(
c_settings.g1_values_lagrange_brp,
FIELD_ELEMENTS_PER_BLOB,
)
}
.iter()
.map(|r| CtG1::from_blst_p1(*r))
.collect::<Vec<_>>(),
g2_values_monomial: unsafe {
core::slice::from_raw_parts(
c_settings.g2_values_monomial,
TRUSTED_SETUP_NUM_G2_POINTS,
)
}
.iter()
.map(|r| CtG2::from_blst_p2(*r))
.collect::<Vec<_>>(),
x_ext_fft_columns: unsafe {
core::slice::from_raw_parts(
c_settings.x_ext_fft_columns,
2 * ((eth::FIELD_ELEMENTS_PER_EXT_BLOB / 2) / eth::FIELD_ELEMENTS_PER_CELL),
)
}
.iter()
.map(|it| {
unsafe { core::slice::from_raw_parts(*it, eth::FIELD_ELEMENTS_PER_CELL) }
.iter()
.map(|it| CtG1::from_blst_p1(*it))
.collect::<Vec<_>>()
})
.collect::<Vec<_>>(),
#[allow(static_mut_refs)]
precomputation: unsafe { PRECOMPUTATION_TABLES.get_precomputation(c_settings) },
cell_size: eth::FIELD_ELEMENTS_PER_CELL,
})
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/g2.rs | constantine/src/types/g2.rs | extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use constantine::ctt_codec_ecc_status;
use kzg::eip_4844::BYTES_PER_G2;
#[cfg(feature = "rand")]
use kzg::Fr;
use kzg::{G2Mul, G2};
use crate::consts::{G2_GENERATOR, G2_NEGATIVE_GENERATOR};
use crate::types::fr::CtFr;
use constantine_sys::{
bls12_381_fp, bls12_381_fp2, bls12_381_g2_aff, bls12_381_g2_jac,
ctt_bls12_381_g2_jac_from_affine,
};
use constantine_sys as constantine;
use kzg::eth::c_bindings::{blst_fp, blst_fp2, blst_p2};
#[derive(Default, Clone, Copy)]
pub struct CtG2(pub bls12_381_g2_jac);
impl CtG2 {
pub const fn from_blst_p2(p2: blst_p2) -> Self {
unsafe {
Self(bls12_381_g2_jac {
x: bls12_381_fp2 {
c: [
bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(p2.x.fp[0].l),
},
bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(p2.x.fp[1].l),
},
],
},
y: bls12_381_fp2 {
c: [
bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(p2.y.fp[0].l),
},
bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(p2.y.fp[1].l),
},
],
},
z: bls12_381_fp2 {
c: [
bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(p2.z.fp[0].l),
},
bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(p2.z.fp[1].l),
},
],
},
})
}
}
pub const fn to_blst_p2(&self) -> blst_p2 {
unsafe {
blst_p2 {
x: blst_fp2 {
fp: [
blst_fp {
l: core::mem::transmute::<[usize; 6], [u64; 6]>(self.0.x.c[0].limbs),
},
blst_fp {
l: core::mem::transmute::<[usize; 6], [u64; 6]>(self.0.x.c[1].limbs),
},
],
},
y: blst_fp2 {
fp: [
blst_fp {
l: core::mem::transmute::<[usize; 6], [u64; 6]>(self.0.y.c[0].limbs),
},
blst_fp {
l: core::mem::transmute::<[usize; 6], [u64; 6]>(self.0.y.c[1].limbs),
},
],
},
z: blst_fp2 {
fp: [
blst_fp {
l: core::mem::transmute::<[usize; 6], [u64; 6]>(self.0.z.c[0].limbs),
},
blst_fp {
l: core::mem::transmute::<[usize; 6], [u64; 6]>(self.0.z.c[1].limbs),
},
],
},
}
}
}
}
impl G2Mul<CtFr> for CtG2 {
fn mul(&self, b: &CtFr) -> Self {
let mut result = *self;
unsafe {
constantine::ctt_bls12_381_g2_jac_scalar_mul_fr_coef(&mut result.0, &b.0);
}
result
}
}
impl G2 for CtG2 {
fn generator() -> Self {
G2_GENERATOR
}
fn negative_generator() -> Self {
G2_NEGATIVE_GENERATOR
}
fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
bytes
.try_into()
.map_err(|_| {
format!(
"Invalid byte length. Expected {}, got {}",
BYTES_PER_G2,
bytes.len()
)
})
.and_then(|bytes: &[u8; BYTES_PER_G2]| {
let mut tmp = bls12_381_g2_aff::default();
let mut g2 = bls12_381_g2_jac::default();
unsafe {
// The uncompress routine also checks that the point is on the curve
let res = constantine::ctt_bls12_381_deserialize_g2_compressed(
&mut tmp,
bytes.as_ptr(),
);
if res != ctt_codec_ecc_status::cttCodecEcc_Success
&& res != ctt_codec_ecc_status::cttCodecEcc_PointAtInfinity
{
return Err("Failed to uncompress".to_string());
}
ctt_bls12_381_g2_jac_from_affine(&mut g2, &tmp);
}
Ok(CtG2(g2))
})
}
fn to_bytes(&self) -> [u8; 96] {
let mut out = [0u8; BYTES_PER_G2];
let mut tmp = bls12_381_g2_aff::default();
unsafe {
constantine::ctt_bls12_381_g2_jac_affine(&mut tmp, &self.0);
let _ = constantine::ctt_bls12_381_serialize_g2_compressed(out.as_mut_ptr(), &tmp);
}
out
}
fn add_or_dbl(&mut self, b: &Self) -> Self {
let mut result = self.0;
unsafe {
constantine::ctt_bls12_381_g2_jac_add_in_place(&mut result, &b.0);
}
Self(result)
}
fn dbl(&self) -> Self {
let mut result = bls12_381_g2_jac::default();
unsafe {
constantine::ctt_bls12_381_g2_jac_double(&mut result, &self.0);
}
Self(result)
}
fn sub(&self, b: &Self) -> Self {
let mut bneg: bls12_381_g2_jac = b.0;
let mut result = self.0;
unsafe {
constantine::ctt_bls12_381_g2_jac_neg_in_place(&mut bneg);
constantine::ctt_bls12_381_g2_jac_add_in_place(&mut result, &bneg);
}
Self(result)
}
fn equals(&self, b: &Self) -> bool {
unsafe { constantine::ctt_bls12_381_g2_jac_is_eq(&self.0, &b.0) != 0 }
}
}
impl CtG2 {
pub(crate) fn _from_xyz(x: bls12_381_fp2, y: bls12_381_fp2, z: bls12_381_fp2) -> Self {
CtG2(bls12_381_g2_jac { x, y, z })
}
#[cfg(feature = "rand")]
pub fn rand() -> Self {
let result: CtG2 = G2_GENERATOR;
result.mul(&CtFr::rand())
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/poly.rs | constantine/src/types/poly.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::common_utils::{log2_pow2, log2_u64, next_pow_of_2};
use kzg::{FFTFr, FFTSettings, FFTSettingsPoly, Fr, Poly};
use crate::consts::SCALE_FACTOR;
use crate::types::fft_settings::CtFFTSettings;
use crate::types::fr::CtFr;
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct CtPoly {
pub coeffs: Vec<CtFr>,
}
impl Poly<CtFr> for CtPoly {
fn new(size: usize) -> Self {
Self {
coeffs: vec![CtFr::default(); size],
}
}
fn get_coeff_at(&self, i: usize) -> CtFr {
self.coeffs[i]
}
fn set_coeff_at(&mut self, i: usize, x: &CtFr) {
self.coeffs[i] = *x
}
fn get_coeffs(&self) -> &[CtFr] {
&self.coeffs
}
fn len(&self) -> usize {
self.coeffs.len()
}
fn eval(&self, x: &CtFr) -> CtFr {
if self.coeffs.is_empty() {
return CtFr::zero();
} else if x.is_zero() {
return self.coeffs[0];
}
let mut ret = self.coeffs[self.coeffs.len() - 1];
let mut i = self.coeffs.len() - 2;
loop {
let temp = ret.mul(x);
ret = temp.add(&self.coeffs[i]);
if i == 0 {
break;
}
i -= 1;
}
ret
}
fn scale(&mut self) {
let scale_factor = CtFr::from_u64(SCALE_FACTOR);
let inv_factor = scale_factor.inverse();
let mut factor_power = CtFr::one();
for i in 0..self.coeffs.len() {
factor_power = factor_power.mul(&inv_factor);
self.coeffs[i] = self.coeffs[i].mul(&factor_power);
}
}
fn unscale(&mut self) {
let scale_factor = CtFr::from_u64(SCALE_FACTOR);
let mut factor_power = CtFr::one();
for i in 0..self.coeffs.len() {
factor_power = factor_power.mul(&scale_factor);
self.coeffs[i] = self.coeffs[i].mul(&factor_power);
}
}
// TODO: analyze how algo works
fn inverse(&mut self, output_len: usize) -> Result<Self, String> {
if output_len == 0 {
return Err(String::from("Can't produce a zero-length result"));
} else if self.coeffs.is_empty() {
return Err(String::from("Can't inverse a zero-length poly"));
} else if self.coeffs[0].is_zero() {
return Err(String::from(
"First coefficient of polynomial mustn't be zero",
));
}
let mut ret = CtPoly {
coeffs: vec![CtFr::zero(); output_len],
};
// If the input polynomial is constant, the remainder of the series is zero
if self.coeffs.len() == 1 {
ret.coeffs[0] = self.coeffs[0].eucl_inverse();
return Ok(ret);
}
let maxd = output_len - 1;
// Max space for multiplications is (2 * length - 1)
// Don't need the following as its recalculated inside
// let scale: usize = log2_pow2(next_pow_of_2(2 * output_len - 1));
// let fft_settings = FsFFTSettings::new(scale).unwrap();
// To store intermediate results
// Base case for d == 0
ret.coeffs[0] = self.coeffs[0].eucl_inverse();
let mut d: usize = 0;
let mut mask: usize = 1 << log2_u64(maxd);
while mask != 0 {
d = 2 * d + usize::from((maxd & mask) != 0);
mask >>= 1;
// b.c -> tmp0 (we're using out for c)
// tmp0.length = min_u64(d + 1, b->length + output->length - 1);
let len_temp = (d + 1).min(self.len() + output_len - 1);
let mut tmp0 = self.mul(&ret, len_temp).unwrap();
// 2 - b.c -> tmp0
for i in 0..tmp0.len() {
tmp0.coeffs[i] = tmp0.coeffs[i].negate();
}
let fr_two = Fr::from_u64(2);
tmp0.coeffs[0] = tmp0.coeffs[0].add(&fr_two);
// c.(2 - b.c) -> tmp1;
let tmp1 = ret.mul(&tmp0, d + 1).unwrap();
for i in 0..tmp1.len() {
ret.coeffs[i] = tmp1.coeffs[i];
}
}
if d + 1 != output_len {
return Err(String::from("D + 1 must be equal to output_len"));
}
Ok(ret)
}
fn div(&mut self, divisor: &Self) -> Result<Self, String> {
if divisor.len() >= self.len() || divisor.len() < 128 {
// Tunable parameter
self.long_div(divisor)
} else {
self.fast_div(divisor)
}
}
fn long_div(&mut self, divisor: &Self) -> Result<Self, String> {
if divisor.coeffs.is_empty() {
return Err(String::from("Can't divide by zero"));
} else if divisor.coeffs[divisor.coeffs.len() - 1].is_zero() {
return Err(String::from("Highest coefficient must be non-zero"));
}
let out_length = self.poly_quotient_length(divisor);
if out_length == 0 {
return Ok(CtPoly { coeffs: vec![] });
}
// Special case for divisor.len() == 2
if divisor.len() == 2 {
let divisor_0 = divisor.coeffs[0];
let divisor_1 = divisor.coeffs[1];
let mut out_coeffs = Vec::from(&self.coeffs[1..]);
for i in (1..out_length).rev() {
out_coeffs[i] = out_coeffs[i].div(&divisor_1).unwrap();
let tmp = out_coeffs[i].mul(&divisor_0);
out_coeffs[i - 1] = out_coeffs[i - 1].sub(&tmp);
}
out_coeffs[0] = out_coeffs[0].div(&divisor_1).unwrap();
Ok(CtPoly { coeffs: out_coeffs })
} else {
let mut out: CtPoly = CtPoly {
coeffs: vec![CtFr::default(); out_length],
};
let mut a_pos = self.len() - 1;
let b_pos = divisor.len() - 1;
let mut diff = a_pos - b_pos;
let mut a = self.coeffs.clone();
while diff > 0 {
out.coeffs[diff] = a[a_pos].div(&divisor.coeffs[b_pos]).unwrap();
for i in 0..(b_pos + 1) {
let tmp = out.coeffs[diff].mul(&divisor.coeffs[i]);
a[diff + i] = a[diff + i].sub(&tmp);
}
diff -= 1;
a_pos -= 1;
}
out.coeffs[0] = a[a_pos].div(&divisor.coeffs[b_pos]).unwrap();
Ok(out)
}
}
fn fast_div(&mut self, divisor: &Self) -> Result<Self, String> {
if divisor.coeffs.is_empty() {
return Err(String::from("Cant divide by zero"));
} else if divisor.coeffs[divisor.coeffs.len() - 1].is_zero() {
return Err(String::from("Highest coefficient must be non-zero"));
}
let m: usize = self.len() - 1;
let n: usize = divisor.len() - 1;
// If the divisor is larger than the dividend, the result is zero-length
if n > m {
return Ok(CtPoly { coeffs: Vec::new() });
}
// Special case for divisor.length == 1 (it's a constant)
if divisor.len() == 1 {
let mut out = CtPoly {
coeffs: vec![CtFr::zero(); self.len()],
};
for i in 0..out.len() {
out.coeffs[i] = self.coeffs[i].div(&divisor.coeffs[0]).unwrap();
}
return Ok(out);
}
let mut a_flip = self.flip().unwrap();
let mut b_flip = divisor.flip().unwrap();
let inv_b_flip = b_flip.inverse(m - n + 1).unwrap();
let q_flip = a_flip.mul(&inv_b_flip, m - n + 1).unwrap();
let out = q_flip.flip().unwrap();
Ok(out)
}
fn mul_direct(&mut self, multiplier: &Self, output_len: usize) -> Result<Self, String> {
if self.len() == 0 || multiplier.len() == 0 {
return Ok(CtPoly::new(0));
}
let a_degree = self.len() - 1;
let b_degree = multiplier.len() - 1;
let mut ret = CtPoly {
coeffs: vec![Fr::zero(); output_len],
};
// Truncate the output to the length of the output polynomial
for i in 0..(a_degree + 1) {
let mut j = 0;
while (j <= b_degree) && ((i + j) < output_len) {
let tmp = self.coeffs[i].mul(&multiplier.coeffs[j]);
let tmp = ret.coeffs[i + j].add(&tmp);
ret.coeffs[i + j] = tmp;
j += 1;
}
}
Ok(ret)
}
}
impl FFTSettingsPoly<CtFr, CtPoly, CtFFTSettings> for CtFFTSettings {
fn poly_mul_fft(
a: &CtPoly,
b: &CtPoly,
len: usize,
_fs: Option<&CtFFTSettings>,
) -> Result<CtPoly, String> {
b.mul_fft(a, len)
}
}
impl CtPoly {
pub fn _poly_norm(&self) -> Self {
let mut ret = self.clone();
let mut temp_len: usize = ret.coeffs.len();
while temp_len > 0 && ret.coeffs[temp_len - 1].is_zero() {
temp_len -= 1;
}
if temp_len == 0 {
ret.coeffs = Vec::new();
} else {
ret.coeffs = ret.coeffs[0..temp_len].to_vec();
}
ret
}
pub fn poly_quotient_length(&self, divisor: &Self) -> usize {
if self.len() >= divisor.len() {
self.len() - divisor.len() + 1
} else {
0
}
}
pub fn pad(&self, out_length: usize) -> Self {
let mut ret = Self {
coeffs: vec![CtFr::zero(); out_length],
};
for i in 0..self.len().min(out_length) {
ret.coeffs[i] = self.coeffs[i];
}
ret
}
pub fn flip(&self) -> Result<CtPoly, String> {
let mut ret = CtPoly {
coeffs: vec![CtFr::default(); self.len()],
};
for i in 0..self.len() {
ret.coeffs[i] = self.coeffs[self.coeffs.len() - i - 1]
}
Ok(ret)
}
pub fn mul_fft(&self, multiplier: &Self, output_len: usize) -> Result<Self, String> {
let length = next_pow_of_2(self.len() + multiplier.len() - 1);
let scale = log2_pow2(length);
let fft_settings = CtFFTSettings::new(scale).unwrap();
let a_pad = self.pad(length);
let b_pad = multiplier.pad(length);
let a_fft: Vec<CtFr>;
let b_fft: Vec<CtFr>;
#[cfg(feature = "parallel")]
{
if length > 1024 {
let mut a_fft_temp = vec![];
let mut b_fft_temp = vec![];
rayon::join(
|| a_fft_temp = fft_settings.fft_fr(&a_pad.coeffs, false).unwrap(),
|| b_fft_temp = fft_settings.fft_fr(&b_pad.coeffs, false).unwrap(),
);
a_fft = a_fft_temp;
b_fft = b_fft_temp;
} else {
a_fft = fft_settings.fft_fr(&a_pad.coeffs, false).unwrap();
b_fft = fft_settings.fft_fr(&b_pad.coeffs, false).unwrap();
}
}
#[cfg(not(feature = "parallel"))]
{
// Convert Poly to values
a_fft = fft_settings.fft_fr(&a_pad.coeffs, false).unwrap();
b_fft = fft_settings.fft_fr(&b_pad.coeffs, false).unwrap();
}
// Multiply two value ranges
let mut ab_fft = a_fft;
ab_fft.iter_mut().zip(b_fft).for_each(|(a, b)| {
*a = a.mul(&b);
});
// Convert value range multiplication to a resulting polynomial
let ab = fft_settings.fft_fr(&ab_fft, true).unwrap();
drop(ab_fft);
let mut ret = CtPoly {
coeffs: vec![CtFr::zero(); output_len],
};
let range = ..output_len.min(length);
ret.coeffs[range].clone_from_slice(&ab[range]);
Ok(ret)
}
pub fn mul(&mut self, multiplier: &Self, output_len: usize) -> Result<Self, String> {
if self.len() < 64 || multiplier.len() < 64 || output_len < 128 {
// Tunable parameter
self.mul_direct(multiplier, output_len)
} else {
self.mul_fft(multiplier, output_len)
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/fft_settings.rs | constantine/src/types/fft_settings.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::common_utils::reverse_bit_order;
use kzg::{FFTSettings, Fr};
use crate::consts::SCALE2_ROOT_OF_UNITY;
use crate::types::fr::CtFr;
#[derive(Clone)]
pub struct CtFFTSettings {
pub max_width: usize,
pub root_of_unity: CtFr,
pub roots_of_unity: Vec<CtFr>,
pub brp_roots_of_unity: Vec<CtFr>,
pub reverse_roots_of_unity: Vec<CtFr>,
}
impl Default for CtFFTSettings {
fn default() -> Self {
Self::new(0).unwrap()
}
}
impl FFTSettings<CtFr> for CtFFTSettings {
/// Create FFTSettings with roots of unity for a selected scale. Resulting roots will have a magnitude of 2 ^ max_scale.
fn new(scale: usize) -> Result<CtFFTSettings, String> {
if scale >= SCALE2_ROOT_OF_UNITY.len() {
return Err(String::from(
"Scale is expected to be within root of unity matrix row size",
));
}
// max_width = 2 ^ max_scale
let max_width: usize = 1 << scale;
let root_of_unity = CtFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[scale]);
// create max_width of roots & store them reversed as well
let roots_of_unity = expand_root_of_unity(&root_of_unity, max_width)?;
let mut brp_roots_of_unity = roots_of_unity.clone();
brp_roots_of_unity.pop();
reverse_bit_order(&mut brp_roots_of_unity)?;
let mut reverse_roots_of_unity = roots_of_unity.clone();
reverse_roots_of_unity.reverse();
Ok(CtFFTSettings {
max_width,
root_of_unity,
reverse_roots_of_unity,
roots_of_unity,
brp_roots_of_unity,
})
}
fn get_max_width(&self) -> usize {
self.max_width
}
fn get_reverse_roots_of_unity_at(&self, i: usize) -> CtFr {
self.reverse_roots_of_unity[i]
}
fn get_reversed_roots_of_unity(&self) -> &[CtFr] {
&self.reverse_roots_of_unity
}
fn get_roots_of_unity_at(&self, i: usize) -> CtFr {
self.roots_of_unity[i]
}
fn get_roots_of_unity(&self) -> &[CtFr] {
&self.roots_of_unity
}
fn get_brp_roots_of_unity(&self) -> &[CtFr] {
&self.brp_roots_of_unity
}
fn get_brp_roots_of_unity_at(&self, i: usize) -> CtFr {
self.brp_roots_of_unity[i]
}
}
/// Multiply a given root of unity by itself until it results in a 1 and result all multiplication values in a vector
pub fn expand_root_of_unity(root: &CtFr, width: usize) -> Result<Vec<CtFr>, String> {
let mut generated_powers = vec![CtFr::one(), *root];
while !(generated_powers.last().unwrap().is_one()) {
if generated_powers.len() > width {
return Err(String::from("Root of unity multiplied for too long"));
}
generated_powers.push(generated_powers.last().unwrap().mul(root));
}
if generated_powers.len() != width + 1 {
return Err(String::from("Root of unity has invalid scale"));
}
Ok(generated_powers)
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/g1.rs | constantine/src/types/g1.rs | extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use arbitrary::Arbitrary;
use constantine::ctt_codec_ecc_status;
use kzg::eth::c_bindings::blst_fp;
use kzg::eth::c_bindings::blst_p1;
use kzg::msm::precompute::PrecomputationTable;
use kzg::G1LinComb;
use core::{
fmt::{Debug, Formatter},
hash::Hash,
};
use crate::kzg_proofs::g1_linear_combination;
use crate::types::fp::CtFp;
use crate::types::fr::CtFr;
use kzg::eip_4844::BYTES_PER_G1;
use kzg::G1Affine;
use kzg::G1GetFp;
use kzg::G1ProjAddAffine;
use kzg::{G1Mul, G1};
use crate::consts::{G1_GENERATOR, G1_IDENTITY, G1_NEGATIVE_GENERATOR};
// use crate::kzg_proofs::g1_linear_combination;
use constantine_sys as constantine;
use constantine_sys::{
bls12_381_fp, bls12_381_g1_aff, bls12_381_g1_jac, ctt_bls12_381_g1_jac_from_affine,
};
#[repr(C)]
#[derive(Clone, Copy, Default)]
pub struct CtG1(pub bls12_381_g1_jac);
impl Hash for CtG1 {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.0.x.limbs.hash(state);
self.0.y.limbs.hash(state);
self.0.z.limbs.hash(state);
}
}
impl PartialEq for CtG1 {
fn eq(&self, other: &Self) -> bool {
unsafe { constantine::ctt_bls12_381_g1_jac_is_eq(&self.0, &other.0) != 0 }
}
}
impl Eq for CtG1 {}
impl Debug for CtG1 {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(
f,
"CtG1({:?}, {:?}, {:?})",
self.0.x.limbs, self.0.y.limbs, self.0.z.limbs
)
}
}
impl CtG1 {
pub(crate) const fn from_xyz(x: bls12_381_fp, y: bls12_381_fp, z: bls12_381_fp) -> Self {
CtG1(bls12_381_g1_jac { x, y, z })
}
pub const fn from_blst_p1(p1: blst_p1) -> Self {
unsafe {
Self(bls12_381_g1_jac {
x: bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(p1.x.l),
},
y: bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(p1.y.l),
},
z: bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(p1.z.l),
},
})
}
}
pub const fn to_blst_p1(&self) -> blst_p1 {
unsafe {
blst_p1 {
x: blst_fp {
l: core::mem::transmute::<[usize; 6], [u64; 6]>(self.0.x.limbs),
},
y: blst_fp {
l: core::mem::transmute::<[usize; 6], [u64; 6]>(self.0.y.limbs),
},
z: blst_fp {
l: core::mem::transmute::<[usize; 6], [u64; 6]>(self.0.z.limbs),
},
}
}
}
}
impl G1 for CtG1 {
fn identity() -> Self {
G1_IDENTITY
}
fn generator() -> Self {
G1_GENERATOR
}
fn negative_generator() -> Self {
G1_NEGATIVE_GENERATOR
}
#[cfg(feature = "rand")]
fn rand() -> Self {
let result: CtG1 = G1_GENERATOR;
result.mul(&kzg::Fr::rand())
}
fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
bytes
.try_into()
.map_err(|_| {
format!(
"Invalid byte length. Expected {}, got {}",
BYTES_PER_G1,
bytes.len()
)
})
.and_then(|bytes: &[u8; BYTES_PER_G1]| {
let mut tmp = bls12_381_g1_aff::default();
let mut g1 = bls12_381_g1_jac::default();
unsafe {
// The uncompress routine also checks that the point is on the curve
let res = constantine::ctt_bls12_381_deserialize_g1_compressed(
&mut tmp,
bytes.as_ptr(),
);
if res != ctt_codec_ecc_status::cttCodecEcc_Success
&& res != ctt_codec_ecc_status::cttCodecEcc_PointAtInfinity
{
return Err("Failed to uncompress".to_string());
}
ctt_bls12_381_g1_jac_from_affine(&mut g1, &tmp);
}
Ok(CtG1(g1))
})
}
fn from_hex(hex: &str) -> Result<Self, String> {
let bytes = hex::decode(&hex[2..]).unwrap();
Self::from_bytes(&bytes)
}
fn to_bytes(&self) -> [u8; 48] {
let mut out = [0u8; BYTES_PER_G1];
unsafe {
let _ = constantine::ctt_bls12_381_serialize_g1_compressed(
out.as_mut_ptr(),
&CtG1Affine::into_affine(self).0,
);
}
out
}
fn add_or_dbl(&self, b: &Self) -> Self {
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_g1_jac_sum(&mut ret.0, &self.0, &b.0);
}
ret
}
fn is_inf(&self) -> bool {
unsafe { constantine::ctt_bls12_381_g1_jac_is_neutral(&self.0) != 0 }
}
fn is_valid(&self) -> bool {
unsafe {
matches!(
constantine::ctt_bls12_381_validate_g1(&CtG1Affine::into_affine(self).0),
ctt_codec_ecc_status::cttCodecEcc_Success
| ctt_codec_ecc_status::cttCodecEcc_PointAtInfinity
)
}
}
fn dbl(&self) -> Self {
let mut result = bls12_381_g1_jac::default();
unsafe {
constantine::ctt_bls12_381_g1_jac_double(&mut result, &self.0);
}
Self(result)
}
fn add(&self, b: &Self) -> Self {
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_g1_jac_sum(&mut ret.0, &self.0, &b.0);
}
ret
}
fn sub(&self, b: &Self) -> Self {
let mut ret = Self::default();
unsafe {
constantine::ctt_bls12_381_g1_jac_diff(&mut ret.0, &self.0, &b.0);
}
ret
}
fn equals(&self, b: &Self) -> bool {
unsafe { constantine::ctt_bls12_381_g1_jac_is_eq(&self.0, &b.0) != 0 }
}
fn zero() -> Self {
CtG1::from_xyz(
bls12_381_fp {
limbs: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
},
bls12_381_fp {
limbs: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
},
bls12_381_fp { limbs: [0; 6] },
)
}
fn add_or_dbl_assign(&mut self, b: &Self) {
unsafe {
constantine::ctt_bls12_381_g1_jac_add_in_place(&mut self.0, &b.0);
}
}
fn add_assign(&mut self, b: &Self) {
unsafe {
constantine::ctt_bls12_381_g1_jac_add_in_place(&mut self.0, &b.0);
}
}
fn dbl_assign(&mut self) {
unsafe {
constantine::ctt_bls12_381_g1_jac_double_in_place(&mut self.0);
}
}
}
impl G1Mul<CtFr> for CtG1 {
fn mul(&self, b: &CtFr) -> Self {
let mut result = *self;
unsafe {
constantine::ctt_bls12_381_g1_jac_scalar_mul_fr_coef(&mut result.0, &b.0);
}
result
}
}
impl G1LinComb<CtFr, CtFp, CtG1Affine, CtG1ProjAddAffine> for CtG1 {
fn g1_lincomb(
points: &[Self],
scalars: &[CtFr],
len: usize,
precomputation: Option<
&PrecomputationTable<CtFr, Self, CtFp, CtG1Affine, CtG1ProjAddAffine>,
>,
) -> Self {
let mut out = CtG1::default();
g1_linear_combination(&mut out, points, scalars, len, precomputation);
out
}
}
impl G1GetFp<CtFp> for CtG1 {
fn x(&self) -> &CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&self.0.x)
}
}
fn y(&self) -> &CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&self.0.y)
}
}
fn z(&self) -> &CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&self.0.z)
}
}
fn x_mut(&mut self) -> &mut CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&mut self.0.x)
}
}
fn y_mut(&mut self) -> &mut CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&mut self.0.y)
}
}
fn z_mut(&mut self) -> &mut CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&mut self.0.z)
}
}
fn from_jacobian(x: CtFp, y: CtFp, z: CtFp) -> Self {
Self(bls12_381_g1_jac {
x: x.0,
y: y.0,
z: z.0,
})
}
}
#[repr(C)]
#[derive(Default, Clone, Copy)]
pub struct CtG1Affine(pub constantine::bls12_381_g1_aff);
impl<'a> Arbitrary<'a> for CtG1Affine {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(CtG1Affine::into_affine(
&CtG1::generator().mul(&u.arbitrary()?),
))
}
}
impl PartialEq for CtG1Affine {
fn eq(&self, other: &Self) -> bool {
unsafe { constantine::ctt_bls12_381_g1_aff_is_eq(&self.0, &other.0) != 0 }
}
}
impl Debug for CtG1Affine {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "CtG1Affine({:?}, {:?})", self.0.x.limbs, self.0.y.limbs)
}
}
impl G1Affine<CtG1, CtFp> for CtG1Affine {
fn zero() -> Self {
Self(bls12_381_g1_aff {
x: {
bls12_381_fp {
limbs: [0, 0, 0, 0, 0, 0],
}
},
y: {
bls12_381_fp {
limbs: [0, 0, 0, 0, 0, 0],
}
},
})
}
fn into_affine(g1: &CtG1) -> Self {
let mut ret: Self = Default::default();
unsafe {
constantine::ctt_bls12_381_g1_jac_affine(&mut ret.0, &g1.0);
}
ret
}
fn into_affines_loc(out: &mut [Self], g1: &[CtG1]) {
if g1.is_empty() {
return;
}
unsafe {
constantine::ctt_bls12_381_g1_jac_batch_affine(
core::mem::transmute::<*mut CtG1Affine, *const constantine_sys::bls12_381_g1_aff>(
out.as_mut_ptr(),
),
core::mem::transmute::<*const CtG1, *const constantine_sys::bls12_381_g1_jac>(
g1.as_ptr(),
),
g1.len(),
);
}
}
fn to_proj(&self) -> CtG1 {
let mut ret: CtG1 = Default::default();
unsafe {
constantine::ctt_bls12_381_g1_jac_from_affine(&mut ret.0, &self.0);
}
ret
}
fn x(&self) -> &CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&self.0.x)
}
}
fn y(&self) -> &CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&self.0.y)
}
}
fn is_infinity(&self) -> bool {
unsafe { constantine::ctt_bls12_381_g1_aff_is_neutral(&self.0) != 0 }
}
fn x_mut(&mut self) -> &mut CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&mut self.0.x)
}
}
fn y_mut(&mut self) -> &mut CtFp {
unsafe {
// Transmute safe due to repr(C) on CtFp
core::mem::transmute(&mut self.0.y)
}
}
fn neg(&self) -> Self {
let mut output = *self;
unsafe {
constantine::ctt_bls12_381_g1_aff_neg_in_place(&mut output.0);
}
output
}
fn from_xy(x: CtFp, y: CtFp) -> Self {
Self(bls12_381_g1_aff { x: x.0, y: y.0 })
}
fn to_bytes_uncompressed(&self) -> [u8; 96] {
todo!()
}
fn from_bytes_uncompressed(_bytes: [u8; 96]) -> Result<Self, String> {
todo!()
}
}
pub struct CtG1ProjAddAffine;
impl G1ProjAddAffine<CtG1, CtFp, CtG1Affine> for CtG1ProjAddAffine {
fn add_assign_affine(proj: &mut CtG1, aff: &CtG1Affine) {
let mut g1_jac = bls12_381_g1_jac::default();
unsafe {
constantine::ctt_bls12_381_g1_jac_from_affine(&mut g1_jac, &aff.0);
constantine::ctt_bls12_381_g1_jac_add_in_place(&mut proj.0, &g1_jac);
}
}
fn add_or_double_assign_affine(proj: &mut CtG1, aff: &CtG1Affine) {
let mut g1_jac = bls12_381_g1_jac::default();
unsafe {
constantine::ctt_bls12_381_g1_jac_from_affine(&mut g1_jac, &aff.0);
constantine::ctt_bls12_381_g1_jac_add_in_place(&mut proj.0, &g1_jac);
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/fp.rs | constantine/src/types/fp.rs | use constantine_sys as constantine;
use constantine_sys::bls12_381_fp;
use core::fmt::{Debug, Formatter};
use kzg::G1Fp;
#[repr(C)]
#[derive(Default, Clone, Copy)]
pub struct CtFp(pub bls12_381_fp);
impl PartialEq for CtFp {
fn eq(&self, other: &Self) -> bool {
unsafe { constantine::ctt_bls12_381_fp_is_eq(&self.0, &other.0) != 0 }
}
}
impl Debug for CtFp {
fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
write!(f, "CtFp({:?})", self.0.limbs)
}
}
impl G1Fp for CtFp {
fn one() -> Self {
Self(bls12_381_fp {
limbs: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
})
}
fn zero() -> Self {
Self(bls12_381_fp {
limbs: [0, 0, 0, 0, 0, 0],
})
}
fn bls12_381_rx_p() -> Self {
Self(bls12_381_fp {
limbs: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
})
}
fn inverse(&self) -> Option<Self> {
let mut out: Self = *self;
unsafe {
constantine::ctt_bls12_381_fp_inv(&mut out.0, &self.0);
}
Some(out)
}
fn square(&self) -> Self {
let mut out: Self = Default::default();
unsafe {
constantine::ctt_bls12_381_fp_square(&mut out.0, &self.0);
}
out
}
fn double(&self) -> Self {
let mut out: Self = Default::default();
unsafe {
constantine::ctt_bls12_381_fp_double(&mut out.0, &self.0);
}
out
}
fn from_underlying_arr(arr: &[u64; 6]) -> Self {
unsafe {
Self(bls12_381_fp {
limbs: core::mem::transmute::<[u64; 6], [usize; 6]>(*arr),
})
}
}
fn neg_assign(&mut self) {
unsafe {
constantine::ctt_bls12_381_fp_neg_in_place(&mut self.0);
}
}
fn mul_assign_fp(&mut self, b: &Self) {
unsafe {
constantine::ctt_bls12_381_fp_mul_in_place(&mut self.0, &b.0);
}
}
fn sub_assign_fp(&mut self, b: &Self) {
unsafe {
constantine::ctt_bls12_381_fp_sub_in_place(&mut self.0, &b.0);
}
}
fn add_assign_fp(&mut self, b: &Self) {
unsafe {
constantine::ctt_bls12_381_fp_add_in_place(&mut self.0, &b.0);
}
}
fn mul3(&self) -> Self {
const THREE: CtFp = CtFp(bls12_381_fp {
limbs: [
17157870155352091297,
9692872460839157767,
5726366251156250088,
11420128032487956561,
9069687087735597977,
1000072309349998725,
],
});
self.mul_fp(&THREE)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/mod.rs | constantine/src/types/mod.rs | pub mod fft_settings;
pub mod fk20_multi_settings;
pub mod fk20_single_settings;
pub mod fp;
pub mod fr;
pub mod g1;
pub mod g2;
pub mod kzg_settings;
pub mod poly;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/src/types/fk20_multi_settings.rs | constantine/src/types/fk20_multi_settings.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::common_utils::reverse_bit_order;
use kzg::{FK20MultiSettings, Poly, FFTG1, G1};
use crate::types::fft_settings::CtFFTSettings;
use crate::types::fr::CtFr;
use crate::types::g1::CtG1;
use crate::types::g2::CtG2;
use crate::types::kzg_settings::CtKZGSettings;
use crate::types::poly::CtPoly;
use super::fp::CtFp;
use super::g1::{CtG1Affine, CtG1ProjAddAffine};
pub struct CtFK20MultiSettings {
pub kzg_settings: CtKZGSettings,
pub chunk_len: usize,
pub x_ext_fft_files: Vec<Vec<CtG1>>,
}
impl Clone for CtFK20MultiSettings {
fn clone(&self) -> Self {
Self {
kzg_settings: self.kzg_settings.clone(),
chunk_len: self.chunk_len,
x_ext_fft_files: self.x_ext_fft_files.clone(),
}
}
}
impl Default for CtFK20MultiSettings {
fn default() -> Self {
Self {
kzg_settings: CtKZGSettings::default(),
chunk_len: 1,
x_ext_fft_files: vec![],
}
}
}
impl
FK20MultiSettings<
CtFr,
CtG1,
CtG2,
CtFFTSettings,
CtPoly,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
> for CtFK20MultiSettings
{
#[allow(clippy::many_single_char_names)]
fn new(ks: &CtKZGSettings, n2: usize, chunk_len: usize) -> Result<Self, String> {
if n2 > ks.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
} else if n2 < 2 {
return Err(String::from("n2 must be greater than or equal to 2"));
} else if chunk_len > n2 / 2 {
return Err(String::from("chunk_len must be greater or equal to n2 / 2"));
} else if !chunk_len.is_power_of_two() {
return Err(String::from("chunk_len must be a power of two"));
}
let n = n2 / 2;
let k = n / chunk_len;
let mut ext_fft_files = Vec::with_capacity(chunk_len);
{
let mut x = Vec::with_capacity(k);
for offset in 0..chunk_len {
let mut start = 0;
if n >= chunk_len + 1 + offset {
start = n - chunk_len - 1 - offset;
}
let mut i = 0;
let mut j = start;
while i + 1 < k {
x.push(ks.g1_values_monomial[j]);
i += 1;
if j >= chunk_len {
j -= chunk_len;
} else {
j = 0;
}
}
x.push(CtG1::identity());
let ext_fft_file = ks.fs.toeplitz_part_1(&x);
x.clear();
ext_fft_files.push(ext_fft_file);
}
}
let ret = Self {
kzg_settings: ks.clone(),
chunk_len,
x_ext_fft_files: ext_fft_files,
};
Ok(ret)
}
fn data_availability(&self, p: &CtPoly) -> Result<Vec<CtG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
}
if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
}
let mut ret = self.data_availability_optimized(p).unwrap();
reverse_bit_order(&mut ret)?;
Ok(ret)
}
fn data_availability_optimized(&self, p: &CtPoly) -> Result<Vec<CtG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
}
let n = n2 / 2;
let k = n / self.chunk_len;
let k2 = k * 2;
let mut h_ext_fft = vec![CtG1::identity(); k2];
for i in 0..self.chunk_len {
let toeplitz_coeffs = p.toeplitz_coeffs_stride(i, self.chunk_len);
let h_ext_fft_file = self
.kzg_settings
.fs
.toeplitz_part_2(&toeplitz_coeffs, &self.x_ext_fft_files[i]);
for j in 0..k2 {
h_ext_fft[j] = h_ext_fft[j].add_or_dbl(&h_ext_fft_file[j]);
}
}
let mut h = self.kzg_settings.fs.toeplitz_part_3(&h_ext_fft);
h[k..k2].copy_from_slice(&vec![CtG1::identity(); k2 - k]);
let ret = self.kzg_settings.fs.fft_g1(&h, false).unwrap();
Ok(ret)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/consts.rs | constantine/tests/consts.rs | // #[path = "./local_tests/local_consts.rs"]
// pub mod local_consts;
#[cfg(test)]
mod tests {
use kzg_bench::tests::consts::{
expand_roots_is_plausible, new_fft_settings_is_plausible, roots_of_unity_are_plausible,
roots_of_unity_is_the_expected_size, roots_of_unity_out_of_bounds_fails,
};
use rust_kzg_constantine::consts::SCALE2_ROOT_OF_UNITY;
use rust_kzg_constantine::types::fft_settings::{expand_root_of_unity, CtFFTSettings};
use rust_kzg_constantine::types::fr::CtFr;
// Shared tests
#[test]
fn roots_of_unity_is_the_expected_size_() {
roots_of_unity_is_the_expected_size(&SCALE2_ROOT_OF_UNITY);
}
#[test]
fn roots_of_unity_out_of_bounds_fails_() {
roots_of_unity_out_of_bounds_fails::<CtFr, CtFFTSettings>();
}
#[test]
fn roots_of_unity_are_plausible_() {
roots_of_unity_are_plausible::<CtFr>(&SCALE2_ROOT_OF_UNITY);
}
#[test]
fn expand_roots_is_plausible_() {
expand_roots_is_plausible::<CtFr>(&SCALE2_ROOT_OF_UNITY, &expand_root_of_unity);
}
#[test]
fn new_fft_settings_is_plausible_() {
new_fft_settings_is_plausible::<CtFr, CtFFTSettings>();
}
// Local tests
// #[test]
// fn roots_of_unity_repeat_at_stride_() {
// roots_of_unity_repeat_at_stride::<CtFr, CtFFTSettings>();
// }
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/das.rs | constantine/tests/das.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::das::{das_extension_test_known, das_extension_test_random};
use rust_kzg_constantine::types::fft_settings::CtFFTSettings;
use rust_kzg_constantine::types::fr::CtFr;
#[test]
fn das_extension_test_known_() {
das_extension_test_known::<CtFr, CtFFTSettings>();
}
#[test]
fn das_extension_test_random_() {
das_extension_test_random::<CtFr, CtFFTSettings>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/eip_4844.rs | constantine/tests/eip_4844.rs | #[cfg(test)]
mod tests {
use kzg::eip_4844::{
blob_to_kzg_commitment_rust, blob_to_polynomial, bytes_to_blob,
compute_blob_kzg_proof_rust, compute_challenge_rust, compute_kzg_proof_rust,
compute_powers, evaluate_polynomial_in_evaluation_form, verify_blob_kzg_proof_batch_rust,
verify_blob_kzg_proof_rust, verify_kzg_proof_rust,
};
use kzg::Fr;
use kzg_bench::tests::eip_4844::{
blob_to_kzg_commitment_test, bytes_to_bls_field_test,
compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test,
compute_and_verify_blob_kzg_proof_test,
compute_and_verify_kzg_proof_fails_with_incorrect_proof_test,
compute_and_verify_kzg_proof_round_trip_test,
compute_and_verify_kzg_proof_within_domain_test, compute_kzg_proof_empty_blob_vector_test,
compute_kzg_proof_incorrect_blob_length_test,
compute_kzg_proof_incorrect_commitments_len_test,
compute_kzg_proof_incorrect_poly_length_test, compute_kzg_proof_incorrect_proofs_len_test,
compute_kzg_proof_test, compute_powers_test, test_vectors_blob_to_kzg_commitment,
test_vectors_compute_blob_kzg_proof, test_vectors_compute_challenge,
test_vectors_compute_kzg_proof, test_vectors_verify_blob_kzg_proof,
test_vectors_verify_blob_kzg_proof_batch, test_vectors_verify_kzg_proof,
validate_batched_input_test, verify_kzg_proof_batch_fails_with_incorrect_proof_test,
verify_kzg_proof_batch_test,
};
use rust_kzg_constantine::consts::SCALE2_ROOT_OF_UNITY;
use rust_kzg_constantine::eip_4844::load_trusted_setup_filename_rust;
use rust_kzg_constantine::types::fft_settings::expand_root_of_unity;
use rust_kzg_constantine::types::g1::{CtG1Affine, CtG1ProjAddAffine};
use rust_kzg_constantine::types::{
fft_settings::CtFFTSettings, fp::CtFp, fr::CtFr, g1::CtG1, g2::CtG2,
kzg_settings::CtKZGSettings, poly::CtPoly,
};
#[test]
pub fn bytes_to_bls_field_test_() {
bytes_to_bls_field_test::<CtFr>();
}
#[test]
pub fn compute_powers_test_() {
compute_powers_test::<CtFr>(&compute_powers);
}
#[test]
pub fn blob_to_kzg_commitment_test_() {
blob_to_kzg_commitment_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
);
}
#[test]
pub fn compute_kzg_proof_test_() {
compute_kzg_proof_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&compute_kzg_proof_rust,
&blob_to_polynomial,
&evaluate_polynomial_in_evaluation_form,
);
}
#[test]
pub fn compute_and_verify_kzg_proof_round_trip_test_() {
compute_and_verify_kzg_proof_round_trip_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_kzg_proof_rust,
&blob_to_polynomial,
&evaluate_polynomial_in_evaluation_form,
&verify_kzg_proof_rust,
);
}
#[test]
pub fn compute_and_verify_kzg_proof_within_domain_test_() {
compute_and_verify_kzg_proof_within_domain_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_kzg_proof_rust,
&blob_to_polynomial,
&evaluate_polynomial_in_evaluation_form,
&verify_kzg_proof_rust,
);
}
#[test]
pub fn compute_and_verify_kzg_proof_fails_with_incorrect_proof_test_() {
compute_and_verify_kzg_proof_fails_with_incorrect_proof_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_kzg_proof_rust,
&blob_to_polynomial,
&evaluate_polynomial_in_evaluation_form,
&verify_kzg_proof_rust,
);
}
#[test]
pub fn compute_and_verify_blob_kzg_proof_test_() {
compute_and_verify_blob_kzg_proof_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
&verify_blob_kzg_proof_rust,
);
}
#[test]
pub fn compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test_() {
compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
&verify_blob_kzg_proof_rust,
);
}
#[test]
pub fn verify_kzg_proof_batch_test_() {
verify_kzg_proof_batch_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
&verify_blob_kzg_proof_batch_rust,
);
}
#[test]
pub fn verify_kzg_proof_batch_fails_with_incorrect_proof_test_() {
verify_kzg_proof_batch_fails_with_incorrect_proof_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
&verify_blob_kzg_proof_batch_rust,
);
}
#[test]
pub fn test_vectors_blob_to_kzg_commitment_() {
test_vectors_blob_to_kzg_commitment::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
);
}
#[test]
pub fn test_vectors_compute_kzg_proof_() {
test_vectors_compute_kzg_proof::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&compute_kzg_proof_rust,
&bytes_to_blob,
);
}
#[test]
pub fn test_vectors_compute_blob_kzg_proof_() {
test_vectors_compute_blob_kzg_proof::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
);
}
#[test]
pub fn test_vectors_verify_kzg_proof_() {
test_vectors_verify_kzg_proof::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&load_trusted_setup_filename_rust, &verify_kzg_proof_rust);
}
#[test]
pub fn test_vectors_verify_blob_kzg_proof_() {
test_vectors_verify_blob_kzg_proof::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&bytes_to_blob,
&verify_blob_kzg_proof_rust,
);
}
#[test]
pub fn test_vectors_verify_blob_kzg_proof_batch_() {
test_vectors_verify_blob_kzg_proof_batch::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&bytes_to_blob,
&verify_blob_kzg_proof_batch_rust,
);
}
#[test]
pub fn test_vectors_compute_challenge_() {
test_vectors_compute_challenge::<CtFr, CtG1>(&bytes_to_blob, &compute_challenge_rust);
}
#[test]
pub fn expand_root_of_unity_too_long() {
let out = expand_root_of_unity(&CtFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[1]), 1);
assert!(out.is_err());
}
#[test]
pub fn expand_root_of_unity_too_short() {
let out = expand_root_of_unity(&CtFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[1]), 3);
assert!(out.is_err());
}
#[test]
pub fn compute_kzg_proof_incorrect_blob_length() {
compute_kzg_proof_incorrect_blob_length_test::<CtFr, CtPoly>(&blob_to_polynomial);
}
#[test]
pub fn compute_kzg_proof_incorrect_poly_length() {
compute_kzg_proof_incorrect_poly_length_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&evaluate_polynomial_in_evaluation_form);
}
#[test]
pub fn compute_kzg_proof_empty_blob_vector() {
compute_kzg_proof_empty_blob_vector_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&verify_blob_kzg_proof_batch_rust)
}
#[test]
pub fn compute_kzg_proof_incorrect_commitments_len() {
compute_kzg_proof_incorrect_commitments_len_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&verify_blob_kzg_proof_batch_rust)
}
#[test]
pub fn compute_kzg_proof_incorrect_proofs_len() {
compute_kzg_proof_incorrect_proofs_len_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&verify_blob_kzg_proof_batch_rust)
}
#[test]
pub fn validate_batched_input() {
validate_batched_input_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&verify_blob_kzg_proof_batch_rust,
&load_trusted_setup_filename_rust,
)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/kzg_proofs.rs | constantine/tests/kzg_proofs.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::kzg_proofs::{
commit_to_nil_poly, commit_to_too_long_poly_returns_err, proof_multi, proof_single,
trusted_setup_in_correct_form,
};
use rust_kzg_constantine::{eip_7594::CtBackend, utils::generate_trusted_setup};
#[test]
pub fn test_trusted_setup_in_correct_form() {
trusted_setup_in_correct_form::<CtBackend>(&generate_trusted_setup);
}
#[test]
pub fn test_proof_single() {
proof_single::<CtBackend>(&generate_trusted_setup);
}
#[test]
pub fn test_commit_to_nil_poly() {
commit_to_nil_poly::<CtBackend>(&generate_trusted_setup);
}
#[test]
pub fn test_commit_to_too_long_poly() {
commit_to_too_long_poly_returns_err::<CtBackend>(&generate_trusted_setup);
}
#[test]
pub fn test_proof_multi() {
proof_multi::<CtBackend>(&generate_trusted_setup);
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/eip_7594.rs | constantine/tests/eip_7594.rs | #[cfg(test)]
mod tests {
use kzg::eip_4844::bytes_to_blob;
use kzg_bench::tests::eip_7594::{
test_vectors_compute_cells, test_vectors_compute_cells_and_kzg_proofs,
test_vectors_compute_verify_cell_kzg_proof_batch_challenge,
test_vectors_recover_cells_and_kzg_proofs, test_vectors_verify_cell_kzg_proof_batch,
};
use rust_kzg_constantine::{eip_4844::load_trusted_setup_filename_rust, eip_7594::CtBackend};
#[test]
pub fn test_vectors_compute_cells_() {
test_vectors_compute_cells::<CtBackend>(&load_trusted_setup_filename_rust, &bytes_to_blob);
}
#[test]
pub fn test_vectors_compute_cells_and_kzg_proofs_() {
test_vectors_compute_cells_and_kzg_proofs::<CtBackend>(
&load_trusted_setup_filename_rust,
&bytes_to_blob,
);
}
#[test]
pub fn test_vectors_recover_cells_and_kzg_proofs_() {
test_vectors_recover_cells_and_kzg_proofs::<CtBackend>(&load_trusted_setup_filename_rust);
}
#[test]
pub fn test_vectors_verify_cell_kzg_proof_batch_() {
test_vectors_verify_cell_kzg_proof_batch::<CtBackend>(&load_trusted_setup_filename_rust);
}
#[test]
pub fn test_vectors_compute_verify_cell_kzg_proof_batch_challenge_() {
test_vectors_compute_verify_cell_kzg_proof_batch_challenge::<CtBackend>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/poly.rs | constantine/tests/poly.rs | // #[path = "./local_tests/local_poly.rs"]
// pub mod local_poly;
#[cfg(test)]
mod tests {
use kzg_bench::tests::poly::{
create_poly_of_length_ten, poly_div_by_zero, poly_div_fast_test, poly_div_long_test,
poly_div_random, poly_eval_0_check, poly_eval_check, poly_eval_nil_check,
poly_inverse_simple_0, poly_inverse_simple_1, poly_mul_direct_test, poly_mul_fft_test,
poly_mul_random, poly_test_div,
};
use rust_kzg_constantine::types::fft_settings::CtFFTSettings;
use rust_kzg_constantine::types::fr::CtFr;
use rust_kzg_constantine::types::poly::CtPoly;
// Local tests
// #[test]
// fn local_create_poly_of_length_ten_() {
// create_poly_of_length_ten()
// }
//
// #[test]
// fn local_poly_pad_works_rand_() {
// poly_pad_works_rand()
// }
//
// #[test]
// fn local_poly_eval_check_() {
// poly_eval_check()
// }
//
// #[test]
// fn local_poly_eval_0_check_() { poly_eval_0_check() }
//
// #[test]
// fn local_poly_eval_nil_check_() {
// poly_eval_nil_check()
// }
//
// #[test]
// fn local_poly_inverse_simple_0_() {
// poly_inverse_simple_0()
// }
//
// #[test]
// fn local_poly_inverse_simple_1_() {
// poly_inverse_simple_1()
// }
//
// #[test]
// fn local_test_poly_div_by_zero_() {
// test_poly_div_by_zero()
// }
//
// #[test]
// fn local_poly_div_long_test_() {
// poly_div_long_test()
// }
//
// #[test]
// fn local_poly_div_fast_test_() {
// poly_div_fast_test()
// }
//
// #[test]
// fn local_poly_mul_direct_test_() {
// poly_mul_direct_test()
// }
//
// #[test]
// fn local_poly_mul_fft_test_() {
// poly_mul_fft_test()
// }
//
// #[test]
// fn local_poly_mul_random_() {
// poly_mul_random()
// }
//
// #[test]
// fn local_poly_div_random_() {
// poly_div_random()
// }
// Shared tests
#[test]
fn create_poly_of_length_ten_() {
create_poly_of_length_ten::<CtFr, CtPoly>()
}
#[test]
fn poly_eval_check_() {
poly_eval_check::<CtFr, CtPoly>()
}
#[test]
fn poly_eval_0_check_() {
poly_eval_0_check::<CtFr, CtPoly>()
}
#[test]
fn poly_eval_nil_check_() {
poly_eval_nil_check::<CtFr, CtPoly>()
}
#[test]
fn poly_inverse_simple_0_() {
poly_inverse_simple_0::<CtFr, CtPoly>()
}
#[test]
fn poly_inverse_simple_1_() {
poly_inverse_simple_1::<CtFr, CtPoly>()
}
#[test]
fn poly_test_div_() {
poly_test_div::<CtFr, CtPoly>()
}
#[test]
fn poly_div_by_zero_() {
poly_div_by_zero::<CtFr, CtPoly>()
}
#[test]
fn poly_mul_direct_test_() {
poly_mul_direct_test::<CtFr, CtPoly>()
}
#[test]
fn poly_mul_fft_test_() {
poly_mul_fft_test::<CtFr, CtPoly, CtFFTSettings>()
}
#[test]
fn poly_mul_random_() {
poly_mul_random::<CtFr, CtPoly, CtFFTSettings>()
}
#[test]
fn poly_div_random_() {
poly_div_random::<CtFr, CtPoly>()
}
#[test]
fn poly_div_long_test_() {
poly_div_long_test::<CtFr, CtPoly>()
}
#[test]
fn poly_div_fast_test_() {
poly_div_fast_test::<CtFr, CtPoly>()
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/zero_poly.rs | constantine/tests/zero_poly.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::zero_poly::{
check_test_data, reduce_partials_random, test_reduce_partials, zero_poly_252,
zero_poly_all_but_one, zero_poly_known, zero_poly_random,
};
use rust_kzg_constantine::types::fft_settings::CtFFTSettings;
use rust_kzg_constantine::types::fr::CtFr;
use rust_kzg_constantine::types::poly::CtPoly;
#[test]
fn test_reduce_partials_() {
test_reduce_partials::<CtFr, CtFFTSettings, CtPoly>();
}
#[test]
fn reduce_partials_random_() {
reduce_partials_random::<CtFr, CtFFTSettings, CtPoly>();
}
#[test]
fn check_test_data_() {
check_test_data::<CtFr, CtFFTSettings, CtPoly>();
}
#[test]
fn zero_poly_known_() {
zero_poly_known::<CtFr, CtFFTSettings, CtPoly>();
}
#[test]
fn zero_poly_random_() {
zero_poly_random::<CtFr, CtFFTSettings, CtPoly>();
}
#[test]
fn zero_poly_all_but_one_() {
zero_poly_all_but_one::<CtFr, CtFFTSettings, CtPoly>();
}
#[test]
fn zero_poly_252_() {
zero_poly_252::<CtFr, CtFFTSettings, CtPoly>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/bls12_381.rs | constantine/tests/bls12_381.rs | #[cfg(test)]
mod tests {
use kzg::common_utils::log_2_byte;
use kzg_bench::tests::bls12_381::{
fr_div_by_zero, fr_div_works, fr_equal_works, fr_from_uint64_works, fr_is_null_works,
fr_is_one_works, fr_is_zero_works, fr_negate_works, fr_pow_works, fr_uint64s_roundtrip,
g1_identity_is_identity, g1_identity_is_infinity, g1_linear_combination_infinity_points,
g1_make_linear_combination, g1_random_linear_combination, g1_small_linear_combination,
log_2_byte_works, p1_mul_works, p1_sub_works, p2_add_or_dbl_works, p2_mul_works,
p2_sub_works, pairings_work,
};
use rust_kzg_constantine::kzg_proofs::{g1_linear_combination, pairings_verify};
use rust_kzg_constantine::types::fp::CtFp;
use rust_kzg_constantine::types::fr::CtFr;
use rust_kzg_constantine::types::g1::{CtG1, CtG1Affine, CtG1ProjAddAffine};
use rust_kzg_constantine::types::g2::CtG2;
#[test]
fn log_2_byte_works_() {
log_2_byte_works(&log_2_byte)
}
#[test]
fn fr_is_null_works_() {
fr_is_null_works::<CtFr>()
}
#[test]
fn fr_is_zero_works_() {
fr_is_zero_works::<CtFr>()
}
#[test]
fn fr_is_one_works_() {
fr_is_one_works::<CtFr>()
}
#[test]
fn fr_from_uint64_works_() {
fr_from_uint64_works::<CtFr>()
}
#[test]
fn fr_equal_works_() {
fr_equal_works::<CtFr>()
}
#[test]
fn fr_negate_works_() {
fr_negate_works::<CtFr>()
}
#[test]
fn fr_pow_works_() {
fr_pow_works::<CtFr>()
}
#[test]
fn fr_div_works_() {
fr_div_works::<CtFr>()
}
#[test]
fn fr_div_by_zero_() {
fr_div_by_zero::<CtFr>()
}
#[test]
fn fr_uint64s_roundtrip_() {
fr_uint64s_roundtrip::<CtFr>()
}
#[test]
fn p1_mul_works_() {
p1_mul_works::<CtFr, CtG1>()
}
#[test]
fn p1_sub_works_() {
p1_sub_works::<CtG1>()
}
#[test]
fn p2_add_or_dbl_works_() {
p2_add_or_dbl_works::<CtG2>()
}
#[test]
fn p2_mul_works_() {
p2_mul_works::<CtFr, CtG2>()
}
#[test]
fn p2_sub_works_() {
p2_sub_works::<CtG2>()
}
#[test]
fn g1_identity_is_infinity_() {
g1_identity_is_infinity::<CtG1>()
}
#[test]
fn g1_identity_is_identity_() {
g1_identity_is_identity::<CtG1>()
}
#[test]
fn g1_make_linear_combination_() {
g1_make_linear_combination::<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>(
&g1_linear_combination,
)
}
#[test]
fn g1_random_linear_combination_() {
g1_random_linear_combination::<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>(
&g1_linear_combination,
)
}
#[test]
pub fn g1_linear_combination_infinity_points_() {
g1_linear_combination_infinity_points::<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>(
&g1_linear_combination,
);
}
#[test]
fn g1_small_linear_combination_() {
g1_small_linear_combination::<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>(
&g1_linear_combination,
)
}
#[test]
fn pairings_work_() {
pairings_work::<CtFr, CtG1, CtG2>(&pairings_verify)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/fk20_proofs.rs | constantine/tests/fk20_proofs.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::fk20_proofs::*;
use rust_kzg_constantine::eip_7594::CtBackend;
use rust_kzg_constantine::types::fk20_multi_settings::CtFK20MultiSettings;
use rust_kzg_constantine::types::fk20_single_settings::CtFK20SingleSettings;
use rust_kzg_constantine::utils::generate_trusted_setup;
#[test]
fn test_fk_single() {
fk_single::<CtBackend, CtFK20SingleSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_single_strided() {
fk_single_strided::<CtBackend, CtFK20SingleSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_settings() {
fk_multi_settings::<CtBackend, CtFK20MultiSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_chunk_len_1_512() {
fk_multi_chunk_len_1_512::<CtBackend, CtFK20MultiSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_chunk_len_16_512() {
fk_multi_chunk_len_16_512::<CtBackend, CtFK20MultiSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_chunk_len_16_16() {
fk_multi_chunk_len_16_16::<CtBackend, CtFK20MultiSettings>(&generate_trusted_setup);
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/mod.rs | constantine/tests/mod.rs | pub mod local_tests;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/c_bindings.rs | constantine/tests/c_bindings.rs | #[cfg(all(test, feature = "c_bindings"))]
mod tests {
use kzg_bench::tests::c_bindings::{
blob_to_kzg_commitment_invalid_blob_test,
compute_blob_kzg_proof_commitment_is_point_at_infinity_test,
compute_blob_kzg_proof_invalid_blob_test, free_trusted_setup_null_ptr_test,
free_trusted_setup_set_all_values_to_null_test,
load_trusted_setup_file_invalid_format_test, load_trusted_setup_file_valid_format_test,
load_trusted_setup_invalid_form_test, load_trusted_setup_invalid_g1_byte_length_test,
load_trusted_setup_invalid_g1_point_test, load_trusted_setup_invalid_g2_byte_length_test,
load_trusted_setup_invalid_g2_point_test,
};
use rust_kzg_constantine::eip_4844::{
blob_to_kzg_commitment, compute_blob_kzg_proof, free_trusted_setup, load_trusted_setup,
load_trusted_setup_file,
};
#[test]
fn blob_to_kzg_commitment_invalid_blob() {
blob_to_kzg_commitment_invalid_blob_test(blob_to_kzg_commitment, load_trusted_setup_file);
}
#[test]
fn load_trusted_setup_invalid_g1_byte_length() {
load_trusted_setup_invalid_g1_byte_length_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_invalid_g1_point() {
load_trusted_setup_invalid_g1_point_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_invalid_g2_byte_length() {
load_trusted_setup_invalid_g2_byte_length_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_invalid_g2_point() {
load_trusted_setup_invalid_g2_point_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_invalid_form() {
load_trusted_setup_invalid_form_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_file_invalid_format() {
load_trusted_setup_file_invalid_format_test(load_trusted_setup_file);
}
#[test]
fn load_trusted_setup_file_valid_format() {
load_trusted_setup_file_valid_format_test(load_trusted_setup_file);
}
#[test]
fn free_trusted_setup_null_ptr() {
free_trusted_setup_null_ptr_test(free_trusted_setup);
}
#[test]
fn free_trusted_setup_set_all_values_to_null() {
free_trusted_setup_set_all_values_to_null_test(free_trusted_setup, load_trusted_setup_file);
}
#[test]
fn compute_blob_kzg_proof_invalid_blob() {
compute_blob_kzg_proof_invalid_blob_test(compute_blob_kzg_proof, load_trusted_setup_file);
}
#[test]
fn compute_blob_kzg_proof_commitment_is_point_at_infinity() {
compute_blob_kzg_proof_commitment_is_point_at_infinity_test(
compute_blob_kzg_proof,
load_trusted_setup_file,
);
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/fft_g1.rs | constantine/tests/fft_g1.rs | #[cfg(test)]
mod tests {
use kzg::G1;
use kzg_bench::tests::fft_g1::{compare_ft_fft, roundtrip_fft, stride_fft};
use rust_kzg_constantine::consts::G1_GENERATOR;
use rust_kzg_constantine::fft_g1::{fft_g1_fast, fft_g1_slow};
use rust_kzg_constantine::types::fft_settings::CtFFTSettings;
use rust_kzg_constantine::types::fr::CtFr;
use rust_kzg_constantine::types::g1::CtG1;
fn make_data(n: usize) -> Vec<CtG1> {
if n == 0 {
return Vec::new();
}
let mut result: Vec<CtG1> = vec![CtG1::default(); n];
result[0] = G1_GENERATOR;
for i in 1..n {
result[i] = result[i - 1].add_or_dbl(&G1_GENERATOR)
}
result
}
#[test]
fn roundtrip_fft_() {
roundtrip_fft::<CtFr, CtG1, CtFFTSettings>(&make_data);
}
#[test]
fn stride_fft_() {
stride_fft::<CtFr, CtG1, CtFFTSettings>(&make_data);
}
#[test]
fn compare_sft_fft_() {
compare_ft_fft::<CtFr, CtG1, CtFFTSettings>(&fft_g1_slow, &fft_g1_fast, &make_data);
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/fft_fr.rs | constantine/tests/fft_fr.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::fft_fr::{compare_sft_fft, inverse_fft, roundtrip_fft, stride_fft};
use rust_kzg_constantine::fft_fr::{fft_fr_fast, fft_fr_slow};
use rust_kzg_constantine::types::fft_settings::CtFFTSettings;
use rust_kzg_constantine::types::fr::CtFr;
#[test]
fn compare_sft_fft_() {
compare_sft_fft::<CtFr, CtFFTSettings>(&fft_fr_slow, &fft_fr_fast);
}
#[test]
fn roundtrip_fft_() {
roundtrip_fft::<CtFr, CtFFTSettings>();
}
#[test]
fn inverse_fft_() {
inverse_fft::<CtFr, CtFFTSettings>();
}
#[test]
fn stride_fft_() {
stride_fft::<CtFr, CtFFTSettings>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/recovery.rs | constantine/tests/recovery.rs | // #[path = "./local_tests/local_recovery.rs"]
// pub mod local_recovery;
#[cfg(test)]
mod tests {
use kzg_bench::tests::recover::*;
// uncomment to use the local tests
//use crate::local_recovery::{recover_random, recover_simple};
use rust_kzg_constantine::types::fft_settings::CtFFTSettings;
use rust_kzg_constantine::types::fr::CtFr;
use rust_kzg_constantine::types::poly::CtPoly;
// Shared tests
#[test]
fn recover_simple_() {
recover_simple::<CtFr, CtFFTSettings, CtPoly, CtPoly>();
}
#[test]
fn recover_random_() {
recover_random::<CtFr, CtFFTSettings, CtPoly, CtPoly>();
}
#[test]
fn more_than_half_missing_() {
more_than_half_missing::<CtFr, CtFFTSettings, CtPoly, CtPoly>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/batch_adder.rs | constantine/tests/batch_adder.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::msm::batch_adder::{
test_batch_add, test_batch_add_indexed, test_batch_add_indexed_single_bucket,
test_batch_add_step_n, test_phase_one_p_add_p, test_phase_one_p_add_q,
test_phase_one_p_add_q_twice, test_phase_one_zero_or_neg, test_phase_two_p_add_neg,
test_phase_two_p_add_p, test_phase_two_p_add_q, test_phase_two_zero_add_p,
};
use rust_kzg_constantine::types::{
fp::CtFp,
g1::{CtG1, CtG1Affine},
};
// use rust_kzg_constantine::types::
#[test]
fn test_phase_one_zero_or_neg_() {
test_phase_one_zero_or_neg::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_phase_one_p_add_p_() {
test_phase_one_p_add_p::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_phase_one_p_add_q_() {
test_phase_one_p_add_q::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_phase_one_p_add_q_twice_() {
test_phase_one_p_add_q_twice::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_phase_two_zero_add_p_() {
test_phase_two_zero_add_p::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_phase_two_p_add_neg_() {
test_phase_two_p_add_neg::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_phase_two_p_add_q_() {
test_phase_two_p_add_q::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_phase_two_p_add_p_() {
test_phase_two_p_add_p::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_batch_add_() {
test_batch_add::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_batch_add_step_n_() {
test_batch_add_step_n::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_batch_add_indexed_() {
test_batch_add_indexed::<CtG1, CtFp, CtG1Affine>();
}
#[test]
fn test_batch_add_indexed_single_bucket_() {
test_batch_add_indexed_single_bucket::<CtG1, CtFp, CtG1Affine>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/eip_4844_constantine.rs | constantine/tests/eip_4844_constantine.rs | // EIP_4844 Tests, but using constantine binding functions
// Some tests are disabled because they rely on data that is not possible to pull from constantine
#[cfg(test)]
mod tests {
use kzg::eip_4844::{
blob_to_polynomial, bytes_to_blob, compute_powers, evaluate_polynomial_in_evaluation_form,
};
use kzg::Fr;
use kzg_bench::tests::eip_4844::{
blob_to_kzg_commitment_test, bytes_to_bls_field_test,
compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test,
compute_and_verify_blob_kzg_proof_test, compute_kzg_proof_empty_blob_vector_test,
compute_kzg_proof_incorrect_blob_length_test,
compute_kzg_proof_incorrect_commitments_len_test,
compute_kzg_proof_incorrect_poly_length_test, compute_kzg_proof_incorrect_proofs_len_test,
compute_powers_test, test_vectors_blob_to_kzg_commitment,
test_vectors_compute_blob_kzg_proof, test_vectors_compute_kzg_proof,
test_vectors_verify_blob_kzg_proof, test_vectors_verify_blob_kzg_proof_batch,
test_vectors_verify_kzg_proof, validate_batched_input_test,
verify_kzg_proof_batch_fails_with_incorrect_proof_test, verify_kzg_proof_batch_test,
};
use rust_kzg_constantine::consts::SCALE2_ROOT_OF_UNITY;
use rust_kzg_constantine::mixed_kzg::mixed_eip_4844::{
blob_to_kzg_commitment_mixed, compute_blob_kzg_proof_mixed, compute_kzg_proof_mixed,
load_trusted_setup_filename_mixed, verify_blob_kzg_proof_batch_mixed,
verify_blob_kzg_proof_mixed, verify_kzg_proof_mixed,
};
use rust_kzg_constantine::mixed_kzg::mixed_kzg_settings::MixedKzgSettings;
use rust_kzg_constantine::types::fft_settings::expand_root_of_unity;
use rust_kzg_constantine::types::fp::CtFp;
use rust_kzg_constantine::types::g1::{CtG1Affine, CtG1ProjAddAffine};
use rust_kzg_constantine::types::{
fft_settings::CtFFTSettings, fr::CtFr, g1::CtG1, g2::CtG2, poly::CtPoly,
};
#[test]
pub fn bytes_to_bls_field_test_() {
bytes_to_bls_field_test::<CtFr>();
}
#[test]
pub fn compute_powers_test_() {
compute_powers_test::<CtFr>(&compute_powers);
}
#[test]
pub fn blob_to_kzg_commitment_test_() {
blob_to_kzg_commitment_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&blob_to_kzg_commitment_mixed,
);
}
// #[test]
// pub fn compute_kzg_proof_test_() {
// compute_kzg_proof_test::<CtFr, CtG1, CtG2, CtPoly, CtFFTSettings, MixedKzgSettings, CtFp, CtG1Affine>(
// &load_trusted_setup_filename_mixed,
// &compute_kzg_proof_mixed,
// &blob_to_polynomial,
// &evaluate_polynomial_in_evaluation_form,
// );
// }
// #[test]
// pub fn compute_and_verify_kzg_proof_round_trip_test_() {
// compute_and_verify_kzg_proof_round_trip_test::<
// CtFr,
// CtG1,
// CtG2,
// CtPoly,
// CtFFTSettings,
// MixedKzgSettings, CtFp, CtG1Affine>(
// &load_trusted_setup_filename_mixed,
// &blob_to_kzg_commitment_mixed,
// &bytes_to_blob,
// &compute_kzg_proof_mixed,
// &blob_to_polynomial,
// &evaluate_polynomial_in_evaluation_form,
// &verify_kzg_proof_mixed,
// );
// }
// #[test]
// pub fn compute_and_verify_kzg_proof_within_domain_test_() {
// compute_and_verify_kzg_proof_within_domain_test::<
// CtFr,
// CtG1,
// CtG2,
// CtPoly,
// CtFFTSettings,
// MixedKzgSettings, CtFp, CtG1Affine>(
// &load_trusted_setup_filename_mixed,
// &blob_to_kzg_commitment_mixed,
// &bytes_to_blob,
// &compute_kzg_proof_mixed,
// &blob_to_polynomial,
// &evaluate_polynomial_in_evaluation_form,
// &verify_kzg_proof_mixed,
// );
// }
// #[test]
// pub fn compute_and_verify_kzg_proof_fails_with_incorrect_proof_test_() {
// compute_and_verify_kzg_proof_fails_with_incorrect_proof_test::<
// CtFr,
// CtG1,
// CtG2,
// CtPoly,
// CtFFTSettings,
// MixedKzgSettings, CtFp, CtG1Affine>(
// &load_trusted_setup_filename_mixed,
// &blob_to_kzg_commitment_mixed,
// &bytes_to_blob,
// &compute_kzg_proof_mixed,
// &blob_to_polynomial,
// &evaluate_polynomial_in_evaluation_form,
// &verify_kzg_proof_mixed,
// );
// }
#[test]
pub fn compute_and_verify_blob_kzg_proof_test_() {
compute_and_verify_blob_kzg_proof_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&blob_to_kzg_commitment_mixed,
&bytes_to_blob,
&compute_blob_kzg_proof_mixed,
&verify_blob_kzg_proof_mixed,
);
}
#[test]
pub fn compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test_() {
compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&blob_to_kzg_commitment_mixed,
&bytes_to_blob,
&compute_blob_kzg_proof_mixed,
&verify_blob_kzg_proof_mixed,
);
}
#[test]
pub fn verify_kzg_proof_batch_test_() {
verify_kzg_proof_batch_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&blob_to_kzg_commitment_mixed,
&bytes_to_blob,
&compute_blob_kzg_proof_mixed,
&verify_blob_kzg_proof_batch_mixed,
);
}
#[test]
pub fn verify_kzg_proof_batch_fails_with_incorrect_proof_test_() {
verify_kzg_proof_batch_fails_with_incorrect_proof_test::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&blob_to_kzg_commitment_mixed,
&bytes_to_blob,
&compute_blob_kzg_proof_mixed,
&verify_blob_kzg_proof_batch_mixed,
);
}
#[test]
pub fn test_vectors_blob_to_kzg_commitment_() {
test_vectors_blob_to_kzg_commitment::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&blob_to_kzg_commitment_mixed,
&bytes_to_blob,
);
}
#[test]
pub fn test_vectors_compute_kzg_proof_() {
test_vectors_compute_kzg_proof::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&compute_kzg_proof_mixed,
&bytes_to_blob,
);
}
#[test]
pub fn test_vectors_compute_blob_kzg_proof_() {
test_vectors_compute_blob_kzg_proof::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&bytes_to_blob,
&compute_blob_kzg_proof_mixed,
);
}
#[test]
pub fn test_vectors_verify_kzg_proof_() {
test_vectors_verify_kzg_proof::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&load_trusted_setup_filename_mixed, &verify_kzg_proof_mixed);
}
#[test]
pub fn test_vectors_verify_blob_kzg_proof_() {
test_vectors_verify_blob_kzg_proof::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&bytes_to_blob,
&verify_blob_kzg_proof_mixed,
);
}
#[test]
pub fn test_vectors_verify_blob_kzg_proof_batch_() {
test_vectors_verify_blob_kzg_proof_batch::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&load_trusted_setup_filename_mixed,
&bytes_to_blob,
&verify_blob_kzg_proof_batch_mixed,
);
}
#[test]
pub fn expand_root_of_unity_too_long() {
let out = expand_root_of_unity(&CtFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[1]), 1);
assert!(out.is_err());
}
#[test]
pub fn expand_root_of_unity_too_short() {
let out = expand_root_of_unity(&CtFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[1]), 3);
assert!(out.is_err());
}
#[test]
pub fn compute_kzg_proof_incorrect_blob_length() {
compute_kzg_proof_incorrect_blob_length_test::<CtFr, CtPoly>(&blob_to_polynomial);
}
#[test]
pub fn compute_kzg_proof_incorrect_poly_length() {
compute_kzg_proof_incorrect_poly_length_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&evaluate_polynomial_in_evaluation_form);
}
#[test]
pub fn compute_kzg_proof_empty_blob_vector() {
compute_kzg_proof_empty_blob_vector_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&verify_blob_kzg_proof_batch_mixed)
}
#[test]
pub fn compute_kzg_proof_incorrect_commitments_len() {
compute_kzg_proof_incorrect_commitments_len_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&verify_blob_kzg_proof_batch_mixed)
}
#[test]
pub fn compute_kzg_proof_incorrect_proofs_len() {
compute_kzg_proof_incorrect_proofs_len_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(&verify_blob_kzg_proof_batch_mixed)
}
#[test]
pub fn validate_batched_input() {
validate_batched_input_test::<
CtPoly,
CtFr,
CtG1,
CtG2,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
&verify_blob_kzg_proof_batch_mixed,
&load_trusted_setup_filename_mixed,
)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/local_tests/local_recovery.rs | constantine/tests/local_tests/local_recovery.rs | use kzg::{FFTFr, FFTSettings, Fr, Poly, PolyRecover};
use rand::rngs::StdRng;
use rand::{RngCore, SeedableRng};
use std::convert::TryInto;
fn shuffle(a: &mut [usize], n: usize) {
let mut i: u64 = n as u64;
let mut j: usize;
let mut tmp: usize;
let mut rng = StdRng::seed_from_u64(0);
while i > 0 {
j = (rng.next_u64() % i) as usize;
i -= 1;
tmp = a[j];
a[j] = a[i as usize];
a[i as usize] = tmp;
}
}
fn random_missing<TFr: Fr>(
with_missing: &mut [Option<TFr>],
data: &[TFr],
len_data: usize,
known: usize,
) {
let mut missing_idx = Vec::new();
for i in 0..len_data {
missing_idx.push(i);
with_missing[i] = Some(data[i].clone());
}
shuffle(&mut missing_idx, len_data);
for i in 0..(len_data - known) {
with_missing[missing_idx[i]] = None;
}
}
pub fn recover_simple<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>,
TPoly: Poly<TFr>,
TPolyRecover: PolyRecover<TFr, TPoly, TFFTSettings>,
>() {
let fs_query = TFFTSettings::new(2);
assert!(fs_query.is_ok());
let fs: TFFTSettings = fs_query.unwrap();
let max_width: usize = fs.get_max_width();
let poly_query = TPoly::new(max_width);
let mut poly = poly_query;
for i in 0..(max_width / 2) {
poly.set_coeff_at(i, &TFr::from_u64(i.try_into().unwrap()));
}
for i in (max_width / 2)..max_width {
poly.set_coeff_at(i, &TFr::zero());
}
let data_query = fs.fft_fr(poly.get_coeffs(), false);
assert!(data_query.is_ok());
let data = data_query.unwrap();
let sample: [Option<TFr>; 4] = [Some(data[0].clone()), None, None, Some(data[3].clone())];
let recovered_query = TPolyRecover::recover_poly_from_samples(&sample, &fs);
assert!(recovered_query.is_ok());
let recovered = recovered_query.unwrap();
for (i, item) in data.iter().enumerate().take(max_width) {
assert!(item.equals(&recovered.get_coeff_at(i)));
}
let mut recovered_vec: Vec<TFr> = Vec::new();
for i in 0..max_width {
recovered_vec.push(recovered.get_coeff_at(i));
}
let back_query = fs.fft_fr(&recovered_vec, true);
assert!(back_query.is_ok());
let back = back_query.unwrap();
for (i, back_x) in back[..(max_width / 2)].iter().enumerate() {
assert!(back_x.equals(&poly.get_coeff_at(i)));
}
for back_x in back[(max_width / 2)..max_width].iter() {
assert!(back_x.is_zero());
}
}
pub fn recover_random<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>,
TPoly: Poly<TFr>,
TPolyRecover: PolyRecover<TFr, TPoly, TFFTSettings>,
>() {
let fs_query = TFFTSettings::new(12);
assert!(fs_query.is_ok());
let fs: TFFTSettings = fs_query.unwrap();
let max_width: usize = fs.get_max_width();
// let mut poly = TPoly::default();
let poly_query = TPoly::new(max_width);
let mut poly = poly_query;
for i in 0..(max_width / 2) {
poly.set_coeff_at(i, &TFr::from_u64(i.try_into().unwrap()));
}
for i in (max_width / 2)..max_width {
poly.set_coeff_at(i, &TFr::zero());
}
let data_query = fs.fft_fr(poly.get_coeffs(), false);
assert!(data_query.is_ok());
let data = data_query.unwrap();
let mut samples = vec![Some(TFr::default()); max_width]; // std::vec![TFr; max_width];
for i in 0..10 {
let known_ratio = 0.5 + (i as f32) * 0.05;
let known: usize = ((max_width as f32) * known_ratio) as usize;
for _ in 0..4 {
random_missing(&mut samples, &data, max_width, known);
let recovered_query = TPolyRecover::recover_poly_from_samples(&samples, &fs);
assert!(recovered_query.is_ok());
let recovered = recovered_query.unwrap();
for (j, item) in data.iter().enumerate().take(max_width) {
assert!(item.equals(&recovered.get_coeff_at(j)));
}
let mut recovered_vec: Vec<TFr> = Vec::new();
for i in 0..max_width {
recovered_vec.push(recovered.get_coeff_at(i));
}
let back_query = fs.fft_fr(&recovered_vec, true);
assert!(back_query.is_ok());
let back = back_query.unwrap();
for (i, back_x) in back[..(max_width / 2)].iter().enumerate() {
assert!(back_x.equals(&poly.get_coeff_at(i)));
}
for back_x in back[(max_width / 2)..max_width].iter() {
assert!(back_x.is_zero());
}
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/local_tests/local_poly.rs | constantine/tests/local_tests/local_poly.rs | use kzg::{Fr, Poly};
use rand::rngs::StdRng;
use rand::{RngCore, SeedableRng};
use rust_kzg_constantine::types::fr::CtFr;
use rust_kzg_constantine::types::poly::CtPoly;
pub fn create_poly_of_length_ten() {
let poly = CtPoly::new(10);
assert_eq!(poly.len(), 10);
}
pub fn poly_pad_works_rand() {
let mut rng = StdRng::seed_from_u64(0);
for _k in 0..256 {
let poly_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let mut poly = CtPoly::new(poly_length);
for i in 0..poly.len() {
poly.set_coeff_at(i, &CtFr::rand());
}
let padded_poly = poly.pad(1000);
for i in 0..poly_length {
assert!(padded_poly.get_coeff_at(i).equals(&poly.get_coeff_at(i)));
}
for i in poly_length..1000 {
assert!(padded_poly.get_coeff_at(i).equals(&Fr::zero()));
}
}
}
pub fn poly_eval_check() {
let n: usize = 10;
let mut poly = CtPoly::new(n);
for i in 0..n {
let fr = CtFr::from_u64((i + 1) as u64);
poly.set_coeff_at(i, &fr);
}
let expected = CtFr::from_u64((n * (n + 1) / 2) as u64);
let actual = poly.eval(&CtFr::one());
assert!(expected.equals(&actual));
}
pub fn poly_eval_0_check() {
let n: usize = 7;
let a: usize = 597;
let mut poly = CtPoly::new(n);
for i in 0..n {
let fr = CtFr::from_u64((i + a) as u64);
poly.set_coeff_at(i, &fr);
}
let expected = CtFr::from_u64(a as u64);
let actual = poly.eval(&CtFr::zero());
assert!(expected.equals(&actual));
}
pub fn poly_eval_nil_check() {
let n: usize = 0;
let poly = CtPoly::new(n);
let actual = poly.eval(&CtFr::one());
assert!(actual.equals(&CtFr::zero()));
}
pub fn poly_inverse_simple_0() {
// 1 / (1 - x) = 1 + x + x^2 + ...
let d: usize = 16;
let mut p = CtPoly::new(2);
p.set_coeff_at(0, &CtFr::one());
p.set_coeff_at(1, &CtFr::one());
p.set_coeff_at(1, &CtFr::negate(&p.get_coeff_at(1)));
let result = p.inverse(d);
assert!(result.is_ok());
let q = result.unwrap();
for i in 0..d {
assert!(q.get_coeff_at(i).is_one());
}
}
pub fn poly_inverse_simple_1() {
// 1 / (1 + x) = 1 - x + x^2 - ...
let d: usize = 16;
let mut p = CtPoly::new(2);
p.set_coeff_at(0, &CtFr::one());
p.set_coeff_at(1, &CtFr::one());
let result = p.inverse(d);
assert!(result.is_ok());
let q = result.unwrap();
for i in 0..d {
let mut tmp = q.get_coeff_at(i);
if i & 1 != 0 {
tmp = CtFr::negate(&tmp);
}
assert!(tmp.is_one());
}
}
pub const NUM_TESTS: u64 = 10;
fn test_data(a: usize, b: usize) -> Vec<i64> {
// (x^2 - 1) / (x + 1) = x - 1
let test_0_0 = vec![-1, 0, 1];
let test_0_1 = vec![1, 1];
let test_0_2 = vec![-1, 1];
// (12x^3 - 11x^2 + 9x + 18) / (4x + 3) = 3x^2 - 5x + 6
let test_1_0 = vec![18, 9, -11, 12];
let test_1_1 = vec![3, 4];
let test_1_2 = vec![6, -5, 3];
// (x + 1) / (x^2 - 1) = nil
let test_2_0 = vec![1, 1];
let test_2_1 = vec![-1, 0, 2];
let test_2_2 = vec![];
// (10x^2 + 20x + 30) / 10 = x^2 + 2x + 3
let test_3_0 = vec![30, 20, 10];
let test_3_1 = vec![10];
let test_3_2 = vec![3, 2, 1];
// (x^2 + x) / (x + 1) = x
let test_4_0 = vec![0, 1, 1];
let test_4_1 = vec![1, 1];
let test_4_2 = vec![0, 1];
// (x^2 + x + 1) / 1 = x^2 + x + 1
let test_5_0 = vec![1, 1, 1];
let test_5_1 = vec![1];
let test_5_2 = vec![1, 1, 1];
// (x^2 + x + 1) / (0x + 1) = x^2 + x + 1
let test_6_0 = vec![1, 1, 1];
let test_6_1 = vec![1, 0]; // The highest coefficient is zero
let test_6_2 = vec![1, 1, 1];
// (x^3) / (x) = (x^2)
let test_7_0 = vec![0, 0, 0, 1];
let test_7_1 = vec![0, 1];
let test_7_2 = vec![0, 0, 1];
//
let test_8_0 = vec![
236,
945,
-297698,
2489425,
-18556462,
-301325440,
2473062655,
-20699887353,
];
let test_8_1 = vec![4, 11, -5000, 45541, -454533];
let test_8_2 = vec![59, 74, -878, 45541];
// (x^4 + 2x^3 + 3x^2 + 2x + 1) / (-x^2 -x -1) = (-x^2 -x -1)
let test_9_0 = vec![1, 2, 3, 2, 1];
let test_9_1 = vec![-1, -1, -1];
let test_9_2 = vec![-1, -1, -1];
let test_data = [
[test_0_0, test_0_1, test_0_2],
[test_1_0, test_1_1, test_1_2],
[test_2_0, test_2_1, test_2_2],
[test_3_0, test_3_1, test_3_2],
[test_4_0, test_4_1, test_4_2],
[test_5_0, test_5_1, test_5_2],
[test_6_0, test_6_1, test_6_2],
[test_7_0, test_7_1, test_7_2],
[test_8_0, test_8_1, test_8_2],
[test_9_0, test_9_1, test_9_2],
];
test_data[a][b].clone()
}
fn new_test_poly(coeffs: &[i64]) -> CtPoly {
let mut p = CtPoly::new(0);
for &coeff in coeffs.iter() {
if coeff >= 0 {
let c = CtFr::from_u64(coeff as u64);
p.coeffs.push(c);
} else {
let c = CtFr::from_u64((-coeff) as u64);
let negc = c.negate();
p.coeffs.push(negc);
}
}
p
}
pub fn poly_div_long_test() {
for i in 0..9 {
// Tests are designed to throw an exception when last member is 0
if i == 6 {
continue;
}
let divided_data = test_data(i, 0);
let divisor_data = test_data(i, 1);
let expected_data = test_data(i, 2);
let mut dividend: CtPoly = new_test_poly(÷d_data);
let divisor: CtPoly = new_test_poly(&divisor_data);
let expected: CtPoly = new_test_poly(&expected_data);
let actual = dividend.long_div(&divisor).unwrap();
assert_eq!(expected.len(), actual.len());
for i in 0..actual.len() {
assert!(expected.get_coeff_at(i).equals(&actual.get_coeff_at(i)))
}
}
}
pub fn poly_div_fast_test() {
for i in 0..9 {
// Tests are designed to throw an exception when last member is 0
if i == 6 {
continue;
}
let divided_data = test_data(i, 0);
let divisor_data = test_data(i, 1);
let expected_data = test_data(i, 2);
let mut dividend: CtPoly = new_test_poly(÷d_data);
let divisor: CtPoly = new_test_poly(&divisor_data);
let expected: CtPoly = new_test_poly(&expected_data);
let actual = dividend.fast_div(&divisor).unwrap();
assert_eq!(expected.len(), actual.len());
for i in 0..actual.len() {
assert!(expected.get_coeff_at(i).equals(&actual.get_coeff_at(i)))
}
}
}
pub fn test_poly_div_by_zero() {
let mut dividend = CtPoly::new(2);
dividend.set_coeff_at(0, &CtFr::from_u64(1));
dividend.set_coeff_at(1, &CtFr::from_u64(1));
let divisor = CtPoly::new(0);
let dummy = dividend.div(&divisor);
assert!(dummy.is_err());
}
pub fn poly_mul_direct_test() {
for i in 0..9 {
let coeffs1 = test_data(i, 2);
let coeffs2 = test_data(i, 1);
let coeffs3 = test_data(i, 0);
let mut multiplicand: CtPoly = new_test_poly(&coeffs1);
let mut multiplier: CtPoly = new_test_poly(&coeffs2);
let expected: CtPoly = new_test_poly(&coeffs3);
let result0 = multiplicand.mul_direct(&multiplier, coeffs3.len()).unwrap();
for j in 0..result0.len() {
assert!(expected.get_coeff_at(j).equals(&result0.get_coeff_at(j)))
}
// Check commutativity
let result1 = multiplier.mul_direct(&multiplicand, coeffs3.len()).unwrap();
for j in 0..result1.len() {
assert!(expected.get_coeff_at(j).equals(&result1.get_coeff_at(j)))
}
}
}
pub fn poly_mul_fft_test() {
for i in 0..9 {
// Ignore 0 multiplication case because its incorrect when multiplied backwards
if i == 2 {
continue;
}
let coeffs1 = test_data(i, 2);
let coeffs2 = test_data(i, 1);
let coeffs3 = test_data(i, 0);
let multiplicand: CtPoly = new_test_poly(&coeffs1);
let multiplier: CtPoly = new_test_poly(&coeffs2);
let expected: CtPoly = new_test_poly(&coeffs3);
let result0 = multiplicand.mul_fft(&multiplier, coeffs3.len()).unwrap();
for j in 0..result0.len() {
assert!(expected.get_coeff_at(j).equals(&result0.get_coeff_at(j)))
}
// Check commutativity
let result1 = multiplier.mul_fft(&multiplicand, coeffs3.len()).unwrap();
for j in 0..result1.len() {
assert!(expected.get_coeff_at(j).equals(&result1.get_coeff_at(j)))
}
}
}
pub fn poly_mul_random() {
let mut rng = StdRng::seed_from_u64(0);
for _k in 0..256 {
let multiplicand_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let mut multiplicand = CtPoly::new(multiplicand_length);
for i in 0..multiplicand.len() {
multiplicand.set_coeff_at(i, &CtFr::rand());
}
let multiplier_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let mut multiplier = CtPoly::new(multiplier_length);
for i in 0..multiplier.len() {
multiplier.set_coeff_at(i, &CtFr::rand());
}
if multiplicand.get_coeff_at(multiplicand.len() - 1).is_zero() {
multiplicand.set_coeff_at(multiplicand.len() - 1, &Fr::one());
}
if multiplier.get_coeff_at(multiplier.len() - 1).is_zero() {
multiplier.set_coeff_at(multiplier.len() - 1, &Fr::one());
}
let out_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let q0 = multiplicand.mul_direct(&multiplier, out_length).unwrap();
let q1 = multiplicand.mul_fft(&multiplier, out_length).unwrap();
assert_eq!(q0.len(), q1.len());
for i in 0..q0.len() {
assert!(q0.get_coeff_at(i).equals(&q1.get_coeff_at(i)));
}
}
}
pub fn poly_div_random() {
let mut rng = StdRng::seed_from_u64(0);
for _k in 0..256 {
let dividend_length: usize = (2 + (rng.next_u64() % 1000)) as usize;
let divisor_length: usize = 1 + ((rng.next_u64() as usize) % dividend_length);
let mut dividend = CtPoly::new(dividend_length);
let mut divisor = CtPoly::new(divisor_length);
for i in 0..dividend_length {
dividend.set_coeff_at(i, &CtFr::rand());
}
for i in 0..divisor_length {
divisor.set_coeff_at(i, &CtFr::rand());
}
//Ensure that the polynomials' orders corresponds to their lengths
if dividend.get_coeff_at(dividend.len() - 1).is_zero() {
dividend.set_coeff_at(dividend.len() - 1, &Fr::one());
}
if divisor.get_coeff_at(divisor.len() - 1).is_zero() {
divisor.set_coeff_at(divisor.len() - 1, &Fr::one());
}
let result0 = dividend.long_div(&divisor).unwrap();
let result1 = dividend.fast_div(&divisor).unwrap();
assert_eq!(result0.len(), result1.len());
for i in 0..result0.len() {
assert!(result0.get_coeff_at(i).equals(&result1.get_coeff_at(i)));
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/local_tests/mod.rs | constantine/tests/local_tests/mod.rs | pub mod local_consts;
pub mod local_poly;
pub mod local_recovery;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/tests/local_tests/local_consts.rs | constantine/tests/local_tests/local_consts.rs | use kzg::{FFTSettings, Fr};
pub fn roots_of_unity_repeat_at_stride<TFr: Fr, TFFTSettings: FFTSettings<TFr>>() {
let fs1 = TFFTSettings::new(15).unwrap();
let fs2 = TFFTSettings::new(16).unwrap();
let fs3 = TFFTSettings::new(17).unwrap();
for i in 0..fs1.get_max_width() {
assert!(fs1
.get_roots_of_unity_at(i)
.equals(&fs2.get_roots_of_unity_at(i * 2)));
assert!(fs1
.get_roots_of_unity_at(i)
.equals(&fs3.get_roots_of_unity_at(i * 4)));
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/das.rs | constantine/benches/das.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::das::bench_das_extension;
use rust_kzg_constantine::types::fft_settings::CtFFTSettings;
use rust_kzg_constantine::types::fr::CtFr;
fn bench_das_extension_(c: &mut Criterion) {
bench_das_extension::<CtFr, CtFFTSettings>(c)
}
criterion_group! {
name = benches;
config = Criterion::default().sample_size(10);
targets = bench_das_extension_
}
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/eip_4844_constantine_no_conv.rs | constantine/benches/eip_4844_constantine_no_conv.rs | // Same as eip_4844.rs, but using constantine implementations of verification functions
use std::path::Path;
use criterion::{criterion_group, criterion_main};
use criterion::{BatchSize, BenchmarkId, Criterion, Throughput};
use kzg::eip_4844::{BYTES_PER_BLOB, TRUSTED_SETUP_PATH};
use kzg_bench::set_trusted_setup_dir;
use kzg_bench::tests::eip_4844::{generate_random_blob_bytes, generate_random_field_element_bytes};
use rand::random;
use rust_kzg_constantine::mixed_kzg::mixed_kzg_settings::CttContext;
fn bench_eip_4844_constantine_no_conv_(c: &mut Criterion) {
set_trusted_setup_dir();
let ctx = CttContext::new(Path::new(TRUSTED_SETUP_PATH)).unwrap();
let mut rng = rand::thread_rng();
const MAX_COUNT: usize = 64;
let blobs: Vec<[u8; BYTES_PER_BLOB]> = (0..MAX_COUNT)
.map(|_| generate_random_blob_bytes(&mut rng))
.collect();
let commitments: Vec<[u8; 48]> = blobs
.iter()
.map(|blob| ctx.blob_to_kzg_commitment(blob).unwrap())
.collect();
let proofs: Vec<[u8; 48]> = blobs
.iter()
.zip(commitments.iter())
.map(|(blob, commitment)| ctx.compute_blob_kzg_proof(blob, commitment).unwrap())
.collect();
let fields: Vec<[u8; 32]> = (0..MAX_COUNT)
.map(|_| generate_random_field_element_bytes(&mut rng))
.collect();
c.bench_function("blob_to_kzg_commitment", |b| {
b.iter(|| ctx.blob_to_kzg_commitment(blobs.first().unwrap()));
});
c.bench_function("compute_kzg_proof", |b| {
b.iter(|| ctx.compute_kzg_proof(blobs.first().unwrap(), fields.first().unwrap()));
});
c.bench_function("verify_kzg_proof", |b| {
b.iter(|| {
ctx.verify_kzg_proof(
commitments.first().unwrap(),
fields.first().unwrap(),
fields.first().unwrap(),
proofs.first().unwrap(),
)
.unwrap()
})
});
c.bench_function("compute_blob_kzg_proof", |b| {
b.iter(|| {
ctx.compute_blob_kzg_proof(blobs.first().unwrap(), commitments.first().unwrap())
.unwrap();
});
});
c.bench_function("verify_blob_kzg_proof", |b| {
b.iter(|| {
ctx.verify_blob_kzg_proof(
blobs.first().unwrap(),
commitments.first().unwrap(),
proofs.first().unwrap(),
)
.unwrap()
});
});
let mut group = c.benchmark_group("verify_blob_kzg_proof_batch");
let rand_thing = random();
for count in [1, 2, 4, 8, 16, 32, 64] {
group.throughput(Throughput::Elements(count as u64));
group.bench_with_input(BenchmarkId::from_parameter(count), &count, |b, &count| {
b.iter_batched_ref(
|| {
let blobs_subset = blobs.clone().into_iter().take(count).collect::<Vec<_>>();
let commitments_subset = commitments
.clone()
.into_iter()
.take(count)
.collect::<Vec<_>>();
let proofs_subset = proofs.clone().into_iter().take(count).collect::<Vec<_>>();
(blobs_subset, commitments_subset, proofs_subset)
},
|(blobs_subset, commitments_subset, proofs_subset)| {
ctx.verify_blob_kzg_proof_batch(
blobs_subset,
commitments_subset,
proofs_subset,
&rand_thing,
)
.unwrap();
},
BatchSize::LargeInput,
);
});
}
group.finish();
}
criterion_group!(benches, bench_eip_4844_constantine_no_conv_);
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/eip_4844.rs | constantine/benches/eip_4844.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg::eip_4844::{
blob_to_kzg_commitment_rust, bytes_to_blob, compute_blob_kzg_proof_rust,
compute_kzg_proof_rust, verify_blob_kzg_proof_batch_rust, verify_blob_kzg_proof_rust,
verify_kzg_proof_rust,
};
use kzg_bench::benches::eip_4844::bench_eip_4844;
use rust_kzg_constantine::{
eip_4844::load_trusted_setup_filename_rust,
types::{
fft_settings::CtFFTSettings,
fp::CtFp,
fr::CtFr,
g1::{CtG1, CtG1Affine, CtG1ProjAddAffine},
g2::CtG2,
kzg_settings::CtKZGSettings,
poly::CtPoly,
},
};
fn bench_eip_4844_(c: &mut Criterion) {
bench_eip_4844::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
CtKZGSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
c,
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_kzg_proof_rust,
&verify_kzg_proof_rust,
&compute_blob_kzg_proof_rust,
&verify_blob_kzg_proof_rust,
&verify_blob_kzg_proof_batch_rust,
);
}
criterion_group!(benches, bench_eip_4844_);
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/poly.rs | constantine/benches/poly.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::poly::bench_new_poly_div;
use rust_kzg_constantine::types::fr::CtFr;
use rust_kzg_constantine::types::poly::CtPoly;
fn bench_new_poly_div_(c: &mut Criterion) {
bench_new_poly_div::<CtFr, CtPoly>(c);
}
criterion_group! {
name = benches;
config = Criterion::default().sample_size(10);
targets = bench_new_poly_div_
}
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/zero_poly.rs | constantine/benches/zero_poly.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::zero_poly::bench_zero_poly;
use rust_kzg_constantine::types::{fft_settings::CtFFTSettings, fr::CtFr, poly::CtPoly};
fn bench_zero_poly_(c: &mut Criterion) {
bench_zero_poly::<CtFr, CtFFTSettings, CtPoly>(c);
}
criterion_group! {
name = benches;
config = Criterion::default().sample_size(10);
targets = bench_zero_poly_
}
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/kzg.rs | constantine/benches/kzg.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::kzg::{bench_commit_to_poly, bench_compute_proof_single};
use rust_kzg_constantine::eip_7594::CtBackend;
use rust_kzg_constantine::utils::generate_trusted_setup;
fn bench_commit_to_poly_(c: &mut Criterion) {
bench_commit_to_poly::<CtBackend>(c, &generate_trusted_setup)
}
fn bench_compute_proof_single_(c: &mut Criterion) {
bench_compute_proof_single::<CtBackend>(c, &generate_trusted_setup)
}
criterion_group! {
name = benches;
config = Criterion::default().sample_size(10);
targets = bench_commit_to_poly_, bench_compute_proof_single_
}
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/lincomb.rs | constantine/benches/lincomb.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::lincomb::bench_g1_lincomb;
use rust_kzg_constantine::kzg_proofs::g1_linear_combination;
use rust_kzg_constantine::types::fp::CtFp;
use rust_kzg_constantine::types::fr::CtFr;
use rust_kzg_constantine::types::g1::{CtG1, CtG1Affine, CtG1ProjAddAffine};
fn bench_g1_lincomb_(c: &mut Criterion) {
bench_g1_lincomb::<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>(c, &g1_linear_combination);
}
criterion_group! {
name = benches;
config = Criterion::default().sample_size(10);
targets = bench_g1_lincomb_
}
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/fk_20.rs | constantine/benches/fk_20.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::fk20::{bench_fk_multi_da, bench_fk_single_da};
use rust_kzg_constantine::eip_7594::CtBackend;
use rust_kzg_constantine::types::fk20_multi_settings::CtFK20MultiSettings;
use rust_kzg_constantine::types::fk20_single_settings::CtFK20SingleSettings;
use rust_kzg_constantine::utils::generate_trusted_setup;
fn bench_fk_single_da_(c: &mut Criterion) {
bench_fk_single_da::<CtBackend, CtFK20SingleSettings>(c, &generate_trusted_setup)
}
fn bench_fk_multi_da_(c: &mut Criterion) {
bench_fk_multi_da::<CtBackend, CtFK20MultiSettings>(c, &generate_trusted_setup)
}
criterion_group! {
name = benches;
config = Criterion::default().sample_size(10);
targets = bench_fk_single_da_, bench_fk_multi_da_
}
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/eip_4844_constantine.rs | constantine/benches/eip_4844_constantine.rs | // Same as eip_4844.rs, but using constantine implementations of verification functions
use criterion::{criterion_group, criterion_main, Criterion};
use kzg::eip_4844::bytes_to_blob;
use kzg_bench::benches::eip_4844::bench_eip_4844;
use rust_kzg_constantine::{
mixed_kzg::{
mixed_eip_4844::{
blob_to_kzg_commitment_mixed, compute_blob_kzg_proof_mixed, compute_kzg_proof_mixed,
load_trusted_setup_filename_mixed, verify_blob_kzg_proof_batch_mixed,
verify_blob_kzg_proof_mixed, verify_kzg_proof_mixed,
},
mixed_kzg_settings::MixedKzgSettings,
},
types::{
fft_settings::CtFFTSettings,
fp::CtFp,
fr::CtFr,
g1::{CtG1, CtG1Affine, CtG1ProjAddAffine},
g2::CtG2,
poly::CtPoly,
},
};
fn bench_eip_4844_constantine_(c: &mut Criterion) {
// Mixed KZG eip_4844 test - lots of conversions so not indicative of 'true' performance
bench_eip_4844::<
CtFr,
CtG1,
CtG2,
CtPoly,
CtFFTSettings,
MixedKzgSettings,
CtFp,
CtG1Affine,
CtG1ProjAddAffine,
>(
c,
&load_trusted_setup_filename_mixed,
&blob_to_kzg_commitment_mixed,
&bytes_to_blob,
&compute_kzg_proof_mixed,
&verify_kzg_proof_mixed,
&compute_blob_kzg_proof_mixed,
&verify_blob_kzg_proof_mixed,
&verify_blob_kzg_proof_batch_mixed,
);
}
criterion_group!(benches, bench_eip_4844_constantine_);
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/recover.rs | constantine/benches/recover.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::recover::bench_recover;
use rust_kzg_constantine::types::{fft_settings::CtFFTSettings, fr::CtFr, poly::CtPoly};
pub fn bench_recover_(c: &mut Criterion) {
bench_recover::<CtFr, CtFFTSettings, CtPoly, CtPoly>(c)
}
criterion_group! {
name = benches;
config = Criterion::default().sample_size(10);
targets = bench_recover_
}
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/constantine/benches/fft.rs | constantine/benches/fft.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::fft::{bench_fft_fr, bench_fft_g1};
use rust_kzg_constantine::types::fft_settings::CtFFTSettings;
use rust_kzg_constantine::types::fr::CtFr;
use rust_kzg_constantine::types::g1::CtG1;
fn bench_fft_fr_(c: &mut Criterion) {
bench_fft_fr::<CtFr, CtFFTSettings>(c);
}
fn bench_fft_g1_(c: &mut Criterion) {
bench_fft_g1::<CtFr, CtG1, CtFFTSettings>(c);
}
criterion_group! {
name = benches;
config = Criterion::default().sample_size(10);
targets = bench_fft_fr_, bench_fft_g1_
}
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/rust-eth-kzg-benches/src/lib.rs | rust-eth-kzg-benches/src/lib.rs | rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false | |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/rust-eth-kzg-benches/benches/trusted_setup.rs | rust-eth-kzg-benches/benches/trusted_setup.rs | use criterion::{criterion_group, criterion_main, Criterion};
use rust_eth_kzg::{DASContext, TrustedSetup, UsePrecomp};
fn bench_load_trusted_setup(c: &mut Criterion) {
c.bench_function("load_trusted_setup", |b| {
b.iter(|| {
let trusted_setup = TrustedSetup::default();
#[cfg(feature = "parallel")]
let _ = DASContext::with_threads(
&trusted_setup,
rust_eth_kzg::ThreadCount::Multi(
std::thread::available_parallelism().unwrap().into(),
),
UsePrecomp::Yes { width: 8 },
);
#[cfg(not(feature = "parallel"))]
let _ = DASContext::new(&trusted_setup, UsePrecomp::Yes { width: 8 });
});
});
}
criterion_group!(benches, bench_load_trusted_setup);
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/rust-eth-kzg-benches/benches/eip_7594.rs | rust-eth-kzg-benches/benches/eip_7594.rs | use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use kzg_bench::benches::eip_7594::get_partial_cells;
use kzg_bench::tests::eip_4844::generate_random_blob_bytes;
use rust_eth_kzg::constants::CELLS_PER_EXT_BLOB;
use rust_eth_kzg::UsePrecomp;
use rust_eth_kzg::{DASContext, TrustedSetup};
fn bench_eip_7594_(c: &mut Criterion) {
const MAX_COUNT: usize = 64;
let trusted_setup = TrustedSetup::default();
#[cfg(feature = "parallel")]
let ctx = DASContext::with_threads(
&trusted_setup,
rust_eth_kzg::ThreadCount::Multi(std::thread::available_parallelism().unwrap().into()),
UsePrecomp::Yes { width: 8 },
);
#[cfg(not(feature = "parallel"))]
let ctx = DASContext::new(&trusted_setup, UsePrecomp::Yes { width: 8 });
let mut rng = rand::thread_rng();
let blobs = (0..MAX_COUNT)
.map(|_| generate_random_blob_bytes(&mut rng))
.collect::<Vec<_>>();
let mut blob_cells = Vec::with_capacity(MAX_COUNT);
let mut blob_cell_proofs = Vec::with_capacity(MAX_COUNT);
let mut blob_commitments = Vec::with_capacity(MAX_COUNT);
for blob in blobs.iter() {
let (cells, proofs) = ctx.compute_cells_and_kzg_proofs(blob).unwrap();
blob_cells.push(cells);
blob_cell_proofs.push(proofs);
blob_commitments.push(ctx.blob_to_kzg_commitment(blob).unwrap());
}
let blob_cells = blob_cells;
let blob_cell_proofs = blob_cell_proofs;
let blob_commitments = blob_commitments;
c.bench_function("compute_cells_and_kzg_proofs", |b| {
b.iter(|| {
ctx.compute_cells_and_kzg_proofs(&blobs[0]).unwrap();
});
});
let mut group = c.benchmark_group("recover_cells_and_kzg_proofs (% missing)");
for i in [2, 4, 8] {
let percent_missing = 100.0 / (i as f64);
let (cell_indices, partial_cells) = get_partial_cells(&blob_cells[0], 1, i);
let partial_cells = partial_cells
.iter()
.map(|it| it.as_ref())
.collect::<Vec<_>>();
let cell_indices = cell_indices
.into_iter()
.map(|it| it as u64)
.collect::<Vec<_>>();
group.bench_function(BenchmarkId::from_parameter(percent_missing), |b| {
b.iter(|| {
ctx.recover_cells_and_kzg_proofs(cell_indices.clone(), partial_cells.clone())
.unwrap();
});
});
}
group.finish();
let mut group = c.benchmark_group("recover_cells_and_kzg_proofs (missing)");
for i in 1..=5 {
let modulo = (CELLS_PER_EXT_BLOB + i - 1) / i;
let (cell_indices, partial_cells) = get_partial_cells(&blob_cells[0], 1, modulo);
let partial_cells = partial_cells
.iter()
.map(|it| it.as_ref())
.collect::<Vec<_>>();
let cell_indices = cell_indices
.into_iter()
.map(|it| it as u64)
.collect::<Vec<_>>();
group.bench_function(BenchmarkId::from_parameter(i), |b| {
b.iter(|| {
ctx.recover_cells_and_kzg_proofs(cell_indices.clone(), partial_cells.clone())
.unwrap();
});
});
}
group.finish();
c.bench_function("verify_cell_kzg_proof_batch", |b| {
let mut cell_commitments = Vec::with_capacity(MAX_COUNT * CELLS_PER_EXT_BLOB);
let mut cell_indices = Vec::with_capacity(MAX_COUNT * CELLS_PER_EXT_BLOB);
let mut cells = Vec::with_capacity(MAX_COUNT * CELLS_PER_EXT_BLOB);
let mut cell_proofs = Vec::with_capacity(MAX_COUNT * CELLS_PER_EXT_BLOB);
for (row_index, blob_cell) in blob_cells.iter().enumerate() {
for (cell_index, cell) in blob_cell.iter().enumerate() {
cell_commitments.push(&blob_commitments[row_index]);
cell_indices.push(cell_index as u64);
cells.push(cell.as_ref());
cell_proofs.push(&blob_cell_proofs[row_index][cell_index]);
}
}
b.iter(|| {
ctx.verify_cell_kzg_proof_batch(
cell_commitments.clone(),
cell_indices.clone(),
cells.clone(),
cell_proofs.clone(),
)
.unwrap();
});
});
let mut group = c.benchmark_group("verify_cell_kzg_proof_batch (rows)");
for i in (0..=MAX_COUNT.ilog2()).map(|exp| 2usize.pow(exp)) {
group.bench_function(BenchmarkId::from_parameter(i), |b| {
let mut cell_commitments = Vec::with_capacity(i * CELLS_PER_EXT_BLOB);
let mut cell_indices = Vec::with_capacity(i * CELLS_PER_EXT_BLOB);
let mut cells = Vec::with_capacity(i * CELLS_PER_EXT_BLOB);
let mut cell_proofs = Vec::with_capacity(i * CELLS_PER_EXT_BLOB);
for (row_index, blob_cell) in blob_cells.iter().take(i).enumerate() {
for (cell_index, cell) in blob_cell.iter().enumerate() {
cell_commitments.push(&blob_commitments[row_index]);
cell_indices.push(cell_index as u64);
cells.push(cell.as_ref());
cell_proofs.push(&blob_cell_proofs[row_index][cell_index]);
}
}
b.iter(|| {
ctx.verify_cell_kzg_proof_batch(
cell_commitments.clone(),
cell_indices.clone(),
cells.clone(),
cell_proofs.clone(),
)
.unwrap();
});
});
}
group.finish();
let mut group = c.benchmark_group("verify_cell_kzg_proof_batch (columns)");
for i in (0..=CELLS_PER_EXT_BLOB.ilog2()).map(|exp| 2usize.pow(exp)) {
group.bench_function(BenchmarkId::from_parameter(i), |b| {
let mut cell_commitments = Vec::with_capacity(MAX_COUNT * i);
let mut cell_indices = Vec::with_capacity(MAX_COUNT * i);
let mut cells = Vec::with_capacity(MAX_COUNT * i);
let mut cell_proofs = Vec::with_capacity(MAX_COUNT * i);
for (row_index, blob_cell) in blob_cells.iter().enumerate() {
for (cell_index, cell) in blob_cell.iter().take(i).enumerate() {
cell_commitments.push(&blob_commitments[row_index]);
cell_indices.push(cell_index as u64);
cells.push(cell.as_ref());
cell_proofs.push(&blob_cell_proofs[row_index][cell_index]);
}
}
b.iter(|| {
ctx.verify_cell_kzg_proof_batch(
cell_commitments.clone(),
cell_indices.clone(),
cells.clone(),
cell_proofs.clone(),
)
.unwrap();
});
});
}
group.finish();
}
criterion_group!(benches, bench_eip_7594_);
criterion_main!(benches);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/fk20_fft.rs | mcl/src/fk20_fft.rs | use kzg::common_utils::{is_power_of_2, next_pow_of_2, reverse_bit_order};
use crate::data_types::{fp::*, fr::*, g1::*};
use std::iter;
// MODULUS = 52435875175126190479447740508185965837690552500527637822603658699938581184513
// PRIMITIVE_ROOT = 5
// [pow(PRIMITIVE_ROOT, (MODULUS - 1) // (2**i), MODULUS) for i in range(32)]
// TODO: gen dynamically?
pub const SCALE_2_ROOT_OF_UNITY_PR5_STRINGS: [&str; 32] = [
"1",
"52435875175126190479447740508185965837690552500527637822603658699938581184512",
"3465144826073652318776269530687742778270252468765361963008",
"23674694431658770659612952115660802947967373701506253797663184111817857449850",
"14788168760825820622209131888203028446852016562542525606630160374691593895118",
"36581797046584068049060372878520385032448812009597153775348195406694427778894",
"31519469946562159605140591558550197856588417350474800936898404023113662197331",
"47309214877430199588914062438791732591241783999377560080318349803002842391998",
"36007022166693598376559747923784822035233416720563672082740011604939309541707",
"4214636447306890335450803789410475782380792963881561516561680164772024173390",
"22781213702924172180523978385542388841346373992886390990881355510284839737428",
"49307615728544765012166121802278658070711169839041683575071795236746050763237",
"39033254847818212395286706435128746857159659164139250548781411570340225835782",
"32731401973776920074999878620293785439674386180695720638377027142500196583783",
"39072540533732477250409069030641316533649120504872707460480262653418090977761",
"22872204467218851938836547481240843888453165451755431061227190987689039608686",
"15076889834420168339092859836519192632846122361203618639585008852351569017005",
"15495926509001846844474268026226183818445427694968626800913907911890390421264",
"20439484849038267462774237595151440867617792718791690563928621375157525968123",
"37115000097562964541269718788523040559386243094666416358585267518228781043101",
"1755840822790712607783180844474754741366353396308200820563736496551326485835",
"32468834368094611004052562760214251466632493208153926274007662173556188291130",
"4859563557044021881916617240989566298388494151979623102977292742331120628579",
"52167942466760591552294394977846462646742207006759917080697723404762651336366",
"18596002123094854211120822350746157678791770803088570110573239418060655130524",
"734830308204920577628633053915970695663549910788964686411700880930222744862",
"4541622677469846713471916119560591929733417256448031920623614406126544048514",
"15932505959375582308231798849995567447410469395474322018100309999481287547373",
"37480612446576615530266821837655054090426372233228960378061628060638903214217",
"5660829372603820951332104046316074966592589311213397907344198301300676239643",
"20094891866007995289136270587723853997043774683345353712639419774914899074390",
"34070893824967080313820779135880760772780807222436853681508667398599787661631",
];
pub const SCALE_2_ROOT_OF_UNITY_PR7_STRINGS: [&str; 32] = [
"1",
/* k=1 r=2 */
"52435875175126190479447740508185965837690552500527637822603658699938581184512",
/* k=2 r=4 */
"3465144826073652318776269530687742778270252468765361963008",
/* k=3 r=8 */
"23674694431658770659612952115660802947967373701506253797663184111817857449850",
/* k=4 r=16 */
"14788168760825820622209131888203028446852016562542525606630160374691593895118",
/* k=5 r=32 */
"36581797046584068049060372878520385032448812009597153775348195406694427778894",
/* k=6 r=64 */
"31519469946562159605140591558550197856588417350474800936898404023113662197331", // iki cia pakeista
/* k=7 r=128 */
"3535074550574477753284711575859241084625659976293648650204577841347885064712",
/* k=8 r=256 */
"21071158244812412064791010377580296085971058123779034548857891862303448703672",
/* k=9 r=512 */
"12531186154666751577774347439625638674013361494693625348921624593362229945844",
/* k=10 r=1024 */
"21328829733576761151404230261968752855781179864716879432436835449516750606329",
/* k=11 r=2048 */
"30450688096165933124094588052280452792793350252342406284806180166247113753719",
/* k=12 r=4096 */
"7712148129911606624315688729500842900222944762233088101895611600385646063109",
/* k=13 r=8192 */
"4862464726302065505506688039068558711848980475932963135959468859464391638674",
/* k=14 r=16384 */
"36362449573598723777784795308133589731870287401357111047147227126550012376068",
/* k=15 r=32768 */
"30195699792882346185164345110260439085017223719129789169349923251189180189908",
/* k=16 r=65536 */
"46605497109352149548364111935960392432509601054990529243781317021485154656122",
/* k=17 r=131072 */
"2655041105015028463885489289298747241391034429256407017976816639065944350782",
/* k=18 r=262144 */
"42951892408294048319804799042074961265671975460177021439280319919049700054024",
/* k=19 r=524288 */
"26418991338149459552592774439099778547711964145195139895155358980955972635668",
/* k=20 r=1048576 */
"23615957371642610195417524132420957372617874794160903688435201581369949179370",
/* k=21 r=2097152 */
"50175287592170768174834711592572954584642344504509533259061679462536255873767",
/* k=22 r=4194304 */
"1664636601308506509114953536181560970565082534259883289958489163769791010513",
/* k=23 r=8388608 */
"36760611456605667464829527713580332378026420759024973496498144810075444759800",
/* k=24 r=16777216 */
"13205172441828670567663721566567600707419662718089030114959677511969243860524",
/* k=25 r=33554432 */
"10335750295308996628517187959952958185340736185617535179904464397821611796715",
/* k=26 r=67108864 */
"51191008403851428225654722580004101559877486754971092640244441973868858562750",
/* k=27 r=134217728 */
"24000695595003793337811426892222725080715952703482855734008731462871475089715",
/* k=28 r=268435456 */
"18727201054581607001749469507512963489976863652151448843860599973148080906836",
/* k=29 r=536870912 */
"50819341139666003587274541409207395600071402220052213520254526953892511091577",
/* k=30 r=1073741824 */
"3811138593988695298394477416060533432572377403639180677141944665584601642504",
/* k=31 r=2147483648 */
"43599901455287962219281063402626541872197057165786841304067502694013639882090",
];
pub const G1_GENERATOR: G1 = G1 {
x: Fp {
d: [
0x5cb38790fd530c16,
0x7817fc679976fff5,
0x154f95c7143ba1c1,
0xf0ae6acdf3d0e747,
0xedce6ecc21dbf440,
0x120177419e0bfb75,
],
},
y: Fp {
d: [
0xbaac93d50ce72271,
0x8c22631a7918fd8e,
0xdd595f13570725ce,
0x51ac582950405194,
0x0e1c8c3fad0059c0,
0x0bbc3efc5008a26a,
],
},
z: Fp {
d: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
};
pub const G1_NEGATIVE_GENERATOR: G1 = G1 {
x: Fp {
d: [
0x5cb38790fd530c16,
0x7817fc679976fff5,
0x154f95c7143ba1c1,
0xf0ae6acdf3d0e747,
0xedce6ecc21dbf440,
0x120177419e0bfb75,
],
},
y: Fp {
d: [
0xff526c2af318883a,
0x92899ce4383b0270,
0x89d7738d9fa9d055,
0x12caf35ba344c12a,
0x3cff1b76964b5317,
0x0e44d2ede9774430,
],
},
z: Fp {
d: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
};
pub static mut SCALE_2_ROOT_OF_UNITY: Vec<Fr> = vec![];
pub static mut GLOBALS_INITIALIZED: bool = false;
pub static mut DEFAULT_GLOBALS_INITIALIZED: bool = false;
pub const PRIMITIVE_ROOT: i32 = 5;
pub fn make_data(n: usize) -> Vec<G1> {
// Multiples of g1_gen
if n == 0 {
return vec![];
}
let mut data: Vec<G1> = vec![G1_GENERATOR];
for _ in 1..n {
let g1 = data.last().unwrap() + &G1_GENERATOR.clone();
data.push(g1);
}
data
}
/// # Safety
///
/// use of mutable static is unsafe and requires unsafe function or block
pub unsafe fn init_globals() {
if GLOBALS_INITIALIZED && DEFAULT_GLOBALS_INITIALIZED {
return;
}
SCALE_2_ROOT_OF_UNITY = SCALE_2_ROOT_OF_UNITY_PR5_STRINGS
.iter()
.map(|x| Fr::from_str(x, 10).unwrap())
.collect();
GLOBALS_INITIALIZED = true;
DEFAULT_GLOBALS_INITIALIZED = true;
}
/// # Safety
///
/// use of mutable static is unsafe and requires unsafe function or block
pub unsafe fn init_globals_custom(root_strings: [&str; 32]) {
SCALE_2_ROOT_OF_UNITY = root_strings
.iter()
.map(|x| Fr::from_str(x, 10).unwrap())
.collect();
GLOBALS_INITIALIZED = true;
DEFAULT_GLOBALS_INITIALIZED = false;
}
pub fn expand_root_of_unity(root: &Fr) -> Vec<Fr> {
let mut root_z = vec![Fr::one(), *root];
let mut i = 1;
while !root_z[i].is_one() {
let next = &root_z[i] * root;
root_z.push(next);
i += 1;
}
root_z
}
#[derive(Debug, Clone)]
pub struct FFTSettings {
pub max_width: usize,
pub root_of_unity: Fr,
pub expanded_roots_of_unity: Vec<Fr>,
pub reverse_roots_of_unity: Vec<Fr>,
pub roots_of_unity: Vec<Fr>,
}
impl Default for FFTSettings {
fn default() -> Self {
Self::new(0)
}
}
impl FFTSettings {
//fix this mess
/// # Safety
///
/// use of mutable static is unsafe and requires unsafe function or block
pub fn new(max_scale: u8) -> FFTSettings {
let root_of_unity: Fr;
unsafe {
init_globals();
root_of_unity = SCALE_2_ROOT_OF_UNITY[max_scale as usize]
}
let expanded_roots_of_unity = expand_root_of_unity(&root_of_unity);
let mut reverse_roots_of_unity = expanded_roots_of_unity.clone();
reverse_roots_of_unity.reverse();
// Permute the roots of unity
let mut roots_of_unity = expanded_roots_of_unity.clone();
reverse_bit_order(&mut roots_of_unity);
FFTSettings {
max_width: 1 << max_scale,
root_of_unity,
expanded_roots_of_unity,
reverse_roots_of_unity,
roots_of_unity,
}
}
/// # Safety
///
/// use of mutable static is unsafe and requires unsafe function or block
pub fn new_custom_primitive_roots(
max_scale: u8,
root_strings: [&str; 32],
) -> Result<FFTSettings, String> {
let root_of_unity: Fr;
unsafe {
init_globals_custom(root_strings);
if max_scale as usize >= SCALE_2_ROOT_OF_UNITY.len() {
return Err(String::from(
"Scale is expected to be within root of unity matrix row size",
));
}
root_of_unity = SCALE_2_ROOT_OF_UNITY[max_scale as usize]
}
let expanded_roots_of_unity = expand_root_of_unity(&root_of_unity);
let mut reverse_roots_of_unity = expanded_roots_of_unity.clone();
reverse_roots_of_unity.reverse();
// Permute the roots of unity
let mut roots_of_unity = expanded_roots_of_unity.clone();
reverse_bit_order(&mut roots_of_unity)?;
Ok(FFTSettings {
max_width: 1 << max_scale,
root_of_unity,
expanded_roots_of_unity,
reverse_roots_of_unity,
roots_of_unity,
})
}
// #[cfg(feature = "parallel")]
fn _fft(
values: &[Fr],
offset: usize,
stride: usize,
roots_of_unity: &[Fr],
root_stride: usize,
out: &mut [Fr],
) {
// check if correct value is checked in case of a bug!
if out.len() <= 4 {
// if the value count is small, run the unoptimized version instead. // TODO tune threshold.
return FFTSettings::_simple_ftt(
values,
offset,
stride,
roots_of_unity,
root_stride,
out,
);
}
let half = out.len() >> 1;
#[cfg(feature = "parallel")]
{
if half > 256 {
let (lo, hi) = out.split_at_mut(half);
rayon::join(
|| {
FFTSettings::_fft(
values,
offset,
stride << 1,
roots_of_unity,
root_stride << 1,
lo,
)
},
|| {
FFTSettings::_fft(
values,
offset + stride,
stride << 1,
roots_of_unity,
root_stride << 1,
hi,
)
},
);
} else {
FFTSettings::_fft(
values,
offset,
stride << 1,
roots_of_unity,
root_stride << 1,
&mut out[..half],
);
FFTSettings::_fft(
values,
offset + stride,
stride << 1,
roots_of_unity,
root_stride << 1,
&mut out[half..],
);
}
}
#[cfg(not(feature = "parallel"))]
{
// left
FFTSettings::_fft(
values,
offset,
stride << 1,
roots_of_unity,
root_stride << 1,
&mut out[..half],
);
// right
FFTSettings::_fft(
values,
offset + stride,
stride << 1,
roots_of_unity,
root_stride << 1,
&mut out[half..],
);
}
for i in 0..half {
let root = &roots_of_unity[i * root_stride];
let y_times_root = &out[i + half] * root;
out[i + half] = out[i] - y_times_root;
out[i] = out[i] + y_times_root;
}
}
fn _simple_ftt(
values: &[Fr],
offset: usize,
stride: usize,
roots_of_unity: &[Fr],
root_stride: usize,
out: &mut [Fr],
) {
let out_len = out.len();
let init_last = values[offset] * roots_of_unity[0];
for i in 0..out_len {
let mut last = init_last;
for j in 1..out_len {
let jv = &values[offset + j * stride];
let r = &roots_of_unity[((i * j) % out_len) * root_stride];
// last += (jv * r)
last = last + (jv * r);
}
out[i] = last;
}
}
pub fn inplace_fft(&self, values: &[Fr], inv: bool) -> Vec<Fr> {
if inv {
let root_z: Vec<Fr> = self
.reverse_roots_of_unity
.iter()
.copied()
.take(self.max_width)
.collect();
let stride = self.max_width / values.len();
let mut out = vec![Fr::default(); values.len()];
FFTSettings::_fft(values, 0, 1, &root_z, stride, &mut out);
let inv_len = Fr::from_int(values.len() as i32).get_inv();
for item in out.iter_mut() {
*item = *item * inv_len;
}
out
} else {
let root_z: Vec<Fr> = self
.expanded_roots_of_unity
.iter()
.copied()
.take(self.max_width)
.collect();
let stride = self.max_width / values.len();
let mut out = vec![Fr::default(); values.len()];
FFTSettings::_fft(values, 0, 1, &root_z, stride, &mut out);
out
}
}
pub fn fft(&self, values: &[Fr], inv: bool) -> Result<Vec<Fr>, String> {
if values.len() > self.max_width {
return Err(String::from(
"Supplied values is longer than the available max width",
));
}
let n = next_pow_of_2(values.len());
let diff = n - values.len();
let tail = iter::repeat(Fr::zero()).take(diff);
let values_copy: Vec<Fr> = values.iter().copied().chain(tail).collect();
Ok(self.inplace_fft(&values_copy, inv))
}
pub fn fft_fr_slow(
result: &mut [Fr],
values: &[Fr],
stride: usize,
passed_roots_of_unity: &[Fr],
root_stride: usize,
) {
FFTSettings::_simple_ftt(
values,
0,
stride,
passed_roots_of_unity,
root_stride,
result,
);
}
pub fn fft_fr_fast(
result: &mut [Fr],
values: &[Fr],
stride: usize,
passed_roots_of_unity: &[Fr],
root_stride: usize,
) {
FFTSettings::_fft(
values,
0,
stride,
passed_roots_of_unity,
root_stride,
result,
);
}
pub fn fft_g1(&self, values: &[G1]) -> Result<Vec<G1>, String> {
if values.len() > self.max_width {
return Err(String::from(
"length of values is longer than the available max width",
));
}
if !is_power_of_2(values.len()) {
return Err(String::from("length of values must be a power of two"));
}
// TODO: check if copy can be removed, opt?
// let vals_copy = values.clone();
let root_z: Vec<Fr> = self
.expanded_roots_of_unity
.iter()
.take(self.max_width)
.copied()
.collect();
let stride = self.max_width / values.len();
let mut out = vec![G1::zero(); values.len()];
FFTSettings::_fft_g1(values, 0, 1, &root_z, stride, &mut out);
Ok(out)
}
//just copied of for fk20_matrix
pub fn fft_g1_inv(&self, values: &[G1]) -> Result<Vec<G1>, String> {
if values.len() > self.max_width {
return Err(String::from(
"length of values is longer than the available max width",
));
}
if !is_power_of_2(values.len()) {
return Err(String::from("length of values must be a power of two"));
}
// TODO: check if copy can be removed, opt?
// let vals_copy = values.clone();
let root_z: Vec<Fr> = self
.reverse_roots_of_unity
.iter()
.take(self.max_width)
.copied()
.collect();
let stride = self.max_width / values.len();
let mut out = vec![G1::zero(); values.len()];
FFTSettings::_fft_g1(values, 0, 1, &root_z, stride, &mut out);
let inv_len = Fr::from_int(values.len() as i32).get_inv();
for item in out.iter_mut() {
// for i in 0..out.len() {
*item = &*item * &inv_len;
}
Ok(out)
}
// #[cfg(feature = "parallel")]
fn _fft_g1(
values: &[G1],
value_offset: usize,
value_stride: usize,
roots_of_unity: &[Fr],
roots_stride: usize,
out: &mut [G1],
) {
//TODO: fine tune for opt, maybe resolve number dinamically based on experiments
if out.len() <= 4 {
return FFTSettings::_fft_g1_simple(
values,
value_offset,
value_stride,
roots_of_unity,
roots_stride,
out,
);
}
let half = out.len() >> 1;
#[cfg(feature = "parallel")]
{
let (lo, hi) = out.split_at_mut(half);
rayon::join(
|| {
FFTSettings::_fft_g1(
values,
value_offset,
value_stride << 1,
roots_of_unity,
roots_stride << 1,
lo,
)
},
|| {
FFTSettings::_fft_g1(
values,
value_offset + value_stride,
value_stride << 1,
roots_of_unity,
roots_stride << 1,
hi,
)
},
);
}
#[cfg(not(feature = "parallel"))]
{
// left
FFTSettings::_fft_g1(
values,
value_offset,
value_stride << 1,
roots_of_unity,
roots_stride << 1,
&mut out[..half],
);
// right
FFTSettings::_fft_g1(
values,
value_offset + value_stride,
value_stride << 1,
roots_of_unity,
roots_stride << 1,
&mut out[half..],
);
}
for i in 0..half {
let x = out[i];
let y = out[i + half];
let root = &roots_of_unity[i * roots_stride];
let y_times_root = y * root;
G1::add(&mut out[i], &x, &y_times_root);
out[i + half] = x - y_times_root;
}
}
fn _fft_g1_simple(
values: &[G1],
value_offset: usize,
value_stride: usize,
roots_of_unity: &[Fr],
roots_stride: usize,
out: &mut [G1],
) {
let l = out.len();
for i in 0..l {
// TODO: check this logic with a working brain, there could be a simpler way to write this;
let mut v = &values[value_offset] * &roots_of_unity[0];
let mut last = v;
for j in 1..l {
v = &values[value_offset + j * value_stride]
* &roots_of_unity[((i * j) % l) * roots_stride];
let temp = last;
last = &temp + &v;
}
out[i] = last;
}
}
pub fn fft_g1_slow(
out: &mut [G1],
values: &[G1],
stride: usize,
passed_roots_of_unity: &[Fr],
root_stride: usize,
_n: usize,
) {
FFTSettings::_fft_g1_simple(values, 0, stride, passed_roots_of_unity, root_stride, out);
}
pub fn fft_g1_fast(
out: &mut [G1],
values: &[G1],
stride: usize,
passed_roots_of_unity: &[Fr],
root_stride: usize,
_n: usize,
) {
FFTSettings::_fft_g1(values, 0, stride, passed_roots_of_unity, root_stride, out);
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/consts.rs | mcl/src/consts.rs | use crate::mcl_methods::{mcl_fp, mcl_fp2, mcl_g1, mcl_g2};
use crate::types::g1::MclG1;
use crate::types::g2::MclG2;
pub const G1_IDENTITY: MclG1 = MclG1::from_xyz(
mcl_fp { d: [0; 6] },
mcl_fp { d: [0; 6] },
mcl_fp { d: [0; 6] },
);
pub const SCALE_FACTOR: u64 = 5;
pub const NUM_ROOTS: usize = 32;
/// The roots of unity. Every root_i equals 1 when raised to the power of (2 ^ i)
#[rustfmt::skip]
pub const SCALE2_ROOT_OF_UNITY: [[u64; 4]; 32] = [
[0x0000000000000001, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0xffffffff00000000, 0x53bda402fffe5bfe, 0x3339d80809a1d805, 0x73eda753299d7d48],
[0x0001000000000000, 0xec03000276030000, 0x8d51ccce760304d0, 0x0000000000000000],
[0x7228fd3397743f7a, 0xb38b21c28713b700, 0x8c0625cd70d77ce2, 0x345766f603fa66e7],
[0x53ea61d87742bcce, 0x17beb312f20b6f76, 0xdd1c0af834cec32c, 0x20b1ce9140267af9],
[0x360c60997369df4e, 0xbf6e88fb4c38fb8a, 0xb4bcd40e22f55448, 0x50e0903a157988ba],
[0x8140d032f0a9ee53, 0x2d967f4be2f95155, 0x14a1e27164d8fdbd, 0x45af6345ec055e4d],
[0x5130c2c1660125be, 0x98d0caac87f5713c, 0xb7c68b4d7fdd60d0, 0x6898111413588742],
[0x4935bd2f817f694b, 0x0a0865a899e8deff, 0x6b368121ac0cf4ad, 0x4f9b4098e2e9f12e],
[0x4541b8ff2ee0434e, 0xd697168a3a6000fe, 0x39feec240d80689f, 0x095166525526a654],
[0x3c28d666a5c2d854, 0xea437f9626fc085e, 0x8f4de02c0f776af3, 0x325db5c3debf77a1],
[0x4a838b5d59cd79e5, 0x55ea6811be9c622d, 0x09f1ca610a08f166, 0x6d031f1b5c49c834],
[0xe206da11a5d36306, 0x0ad1347b378fbf96, 0xfc3e8acfe0f8245f, 0x564c0a11a0f704f4],
[0x6fdd00bfc78c8967, 0x146b58bc434906ac, 0x2ccddea2972e89ed, 0x485d512737b1da3d],
[0x034d2ff22a5ad9e1, 0xae4622f6a9152435, 0xdc86b01c0d477fa6, 0x56624634b500a166],
[0xfbd047e11279bb6e, 0xc8d5f51db3f32699, 0x483405417a0cbe39, 0x3291357ee558b50d],
[0xd7118f85cd96b8ad, 0x67a665ae1fcadc91, 0x88f39a78f1aeb578, 0x2155379d12180caa],
[0x08692405f3b70f10, 0xcd7f2bd6d0711b7d, 0x473a2eef772c33d6, 0x224262332d8acbf4],
[0x6f421a7d8ef674fb, 0xbb97a3bf30ce40fd, 0x652f717ae1c34bb0, 0x2d3056a530794f01],
[0x194e8c62ecb38d9d, 0xad8e16e84419c750, 0xdf625e80d0adef90, 0x520e587a724a6955],
[0xfece7e0e39898d4b, 0x2f69e02d265e09d9, 0xa57a6e07cb98de4a, 0x03e1c54bcb947035],
[0xcd3979122d3ea03a, 0x46b3105f04db5844, 0xc70d0874b0691d4e, 0x47c8b5817018af4f],
[0xc6e7a6ffb08e3363, 0xe08fec7c86389bee, 0xf2d38f10fbb8d1bb, 0x0abe6a5e5abcaa32],
[0x5616c57de0ec9eae, 0xc631ffb2585a72db, 0x5121af06a3b51e3c, 0x73560252aa0655b2],
[0x92cf4deb77bd779c, 0x72cf6a8029b7d7bc, 0x6e0bcd91ee762730, 0x291cf6d68823e687],
[0xce32ef844e11a51e, 0xc0ba12bb3da64ca5, 0x0454dc1edc61a1a3, 0x019fe632fd328739],
[0x531a11a0d2d75182, 0x02c8118402867ddc, 0x116168bffbedc11d, 0x0a0a77a3b1980c0d],
[0xe2d0a7869f0319ed, 0xb94f1101b1d7a628, 0xece8ea224f31d25d, 0x23397a9300f8f98b],
[0xd7b688830a4f2089, 0x6558e9e3f6ac7b41, 0x99e276b571905a7d, 0x52dd465e2f094256],
[0x474650359d8e211b, 0x84d37b826214abc6, 0x8da40c1ef2bb4598, 0x0c83ea7744bf1bee],
[0x694341f608c9dd56, 0xed3a181fabb30adc, 0x1339a815da8b398f, 0x2c6d4e4511657e1e],
[0x63e7cb4906ffc93f, 0xf070bb00e28a193d, 0xad1715b02e5713b5, 0x4b5371495990693f]
];
pub const G1_GENERATOR: MclG1 = MclG1(mcl_g1 {
x: mcl_fp {
d: [
0x5cb38790fd530c16,
0x7817fc679976fff5,
0x154f95c7143ba1c1,
0xf0ae6acdf3d0e747,
0xedce6ecc21dbf440,
0x120177419e0bfb75,
],
},
y: mcl_fp {
d: [
0xbaac93d50ce72271,
0x8c22631a7918fd8e,
0xdd595f13570725ce,
0x51ac582950405194,
0x0e1c8c3fad0059c0,
0x0bbc3efc5008a26a,
],
},
z: mcl_fp {
d: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
});
pub const G1_NEGATIVE_GENERATOR: MclG1 = MclG1(mcl_g1 {
x: mcl_fp {
d: [
0x5cb38790fd530c16,
0x7817fc679976fff5,
0x154f95c7143ba1c1,
0xf0ae6acdf3d0e747,
0xedce6ecc21dbf440,
0x120177419e0bfb75,
],
},
y: mcl_fp {
d: [
0xff526c2af318883a,
0x92899ce4383b0270,
0x89d7738d9fa9d055,
0x12caf35ba344c12a,
0x3cff1b76964b5317,
0x0e44d2ede9774430,
],
},
z: mcl_fp {
d: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
});
pub const G2_GENERATOR: MclG2 = MclG2(mcl_g2 {
x: mcl_fp2 {
d: [
mcl_fp {
d: [
0xf5f28fa202940a10,
0xb3f5fb2687b4961a,
0xa1a893b53e2ae580,
0x9894999d1a3caee9,
0x6f67b7631863366b,
0x058191924350bcd7,
],
},
mcl_fp {
d: [
0xa5a9c0759e23f606,
0xaaa0c59dbccd60c3,
0x3bb17e18e2867806,
0x1b1ab6cc8541b367,
0xc2b6ed0ef2158547,
0x11922a097360edf3,
],
},
],
},
y: mcl_fp2 {
d: [
mcl_fp {
d: [
0x4c730af860494c4a,
0x597cfa1f5e369c5a,
0xe7e6856caa0a635a,
0xbbefb5e96e0d495f,
0x07d3a975f0ef25a2,
0x0083fd8e7e80dae5,
],
},
mcl_fp {
d: [
0xadc0fc92df64b05d,
0x18aa270a2b1461dc,
0x86adac6a3be4eba0,
0x79495c4ec93da33a,
0xe7175850a43ccaed,
0x0b2bc2a163de1bf2,
],
},
],
},
z: mcl_fp2 {
d: [
mcl_fp {
d: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
mcl_fp {
d: [
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
],
},
],
},
});
pub const G2_NEGATIVE_GENERATOR: MclG2 = MclG2(mcl_g2 {
x: mcl_fp2 {
d: [
mcl_fp {
d: [
0xf5f28fa202940a10,
0xb3f5fb2687b4961a,
0xa1a893b53e2ae580,
0x9894999d1a3caee9,
0x6f67b7631863366b,
0x058191924350bcd7,
],
},
mcl_fp {
d: [
0xa5a9c0759e23f606,
0xaaa0c59dbccd60c3,
0x3bb17e18e2867806,
0x1b1ab6cc8541b367,
0xc2b6ed0ef2158547,
0x11922a097360edf3,
],
},
],
},
y: mcl_fp2 {
d: [
mcl_fp {
d: [
0x6d8bf5079fb65e61,
0xc52f05df531d63a5,
0x7f4a4d344ca692c9,
0xa887959b8577c95f,
0x4347fe40525c8734,
0x197d145bbaff0bb5,
],
},
mcl_fp {
d: [
0x0c3e036d209afa4e,
0x0601d8f4863f9e23,
0xe0832636bacc0a84,
0xeb2def362a476f84,
0x64044f659f0ee1e9,
0x0ed54f48d5a1caa7,
],
},
],
},
z: mcl_fp2 {
d: [
mcl_fp {
d: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
mcl_fp {
d: [
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
],
},
],
},
});
pub const TRUSTED_SETUP_GENERATOR: [u8; 32usize] = [
0xa4, 0x73, 0x31, 0x95, 0x28, 0xc8, 0xb6, 0xea, 0x4d, 0x08, 0xcc, 0x53, 0x18, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
];
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/das.rs | mcl/src/das.rs | use kzg::common_utils::is_power_of_2;
use crate::data_types::fr::Fr;
use crate::fk20_fft::*;
impl FFTSettings {
pub fn das_fft_extension(&self, values: &mut [Fr]) -> Result<(), String> {
if values.is_empty() {
return Err(String::from("Values cannot be empty"));
}
if !is_power_of_2(values.len()) {
return Err(String::from("Value count must be a number of two"));
}
if values.len() << 1 > self.max_width {
return Err(String::from("ftt settings max width too small!"));
}
//larger stride if more roots fttsettings
let stride = self.max_width / (values.len() * 2);
self._das_fft_extension(values, stride);
// just dividing every value by 1/(2**depth) aka length
// TODO: what's faster, maybe vec[x] * vec[x], ask herumi to implement?
let inv_length = Fr::from_int(values.len() as i32).get_inv();
for item in values.iter_mut() {
*item *= &inv_length;
}
Ok(())
}
// #[cfg(feature = "parallel")]
fn _das_fft_extension(&self, values: &mut [Fr], stride: usize) {
if values.len() < 2 {
return;
}
if values.len() == 2 {
let (x, y) = FFTSettings::_calc_add_and_sub(&values[0], &values[1]);
let temp = y * self.expanded_roots_of_unity[stride];
values[0] = x + temp;
values[1] = x - temp;
return;
}
let length = values.len();
let half = length >> 1;
for i in 0..half {
let (add, sub) = FFTSettings::_calc_add_and_sub(&values[i], &values[half + i]);
values[half + i] = sub * self.reverse_roots_of_unity[(i << 1) * stride];
values[i] = add;
}
#[cfg(feature = "parallel")]
{
if values.len() > 32 {
let (lo, hi) = values.split_at_mut(half);
rayon::join(
|| self._das_fft_extension(hi, stride * 2),
|| self._das_fft_extension(lo, stride * 2),
);
} else {
self._das_fft_extension(&mut values[..half], stride << 1);
self._das_fft_extension(&mut values[half..], stride << 1);
}
}
#[cfg(not(feature = "parallel"))]
{
// left
self._das_fft_extension(&mut values[..half], stride << 1);
// right
self._das_fft_extension(&mut values[half..], stride << 1);
}
for i in 0..half {
let root = &self.expanded_roots_of_unity[((i << 1) + 1) * stride];
let y_times_root = &values[half + i] * root;
let (add, sub) = FFTSettings::_calc_add_and_sub(&values[i], &y_times_root);
values[i] = add;
values[i + half] = sub;
}
}
fn _calc_add_and_sub(a: &Fr, b: &Fr) -> (Fr, Fr) {
(a + b, a - b)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/lib.rs | mcl/src/lib.rs | #![cfg_attr(not(feature = "std"), no_std)]
pub mod consts;
pub mod data_availability_sampling;
pub mod eip_4844;
pub mod eip_7594;
pub mod fft_fr;
pub mod fft_g1;
pub mod fk20_proofs;
pub mod kzg_proofs;
pub mod mcl_methods;
pub mod recovery;
pub mod types;
pub mod utils;
pub mod zero_poly;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/eip_4844.rs | mcl/src/eip_4844.rs | extern crate alloc;
#[cfg(feature = "c_bindings")]
use alloc::{boxed::Box, vec::Vec};
#[cfg(feature = "c_bindings")]
use core::ptr;
use kzg::eip_4844::load_trusted_setup_rust;
#[cfg(feature = "c_bindings")]
use kzg::{
eip_4844::{
BYTES_PER_G1, FIELD_ELEMENTS_PER_BLOB, TRUSTED_SETUP_NUM_G1_POINTS,
TRUSTED_SETUP_NUM_G2_POINTS,
},
eth::{
c_bindings::{Blob, Bytes32, Bytes48, CKZGSettings, CKzgRet, KZGCommitment, KZGProof},
FIELD_ELEMENTS_PER_CELL, FIELD_ELEMENTS_PER_EXT_BLOB,
},
Fr, G1,
};
#[cfg(all(feature = "std", feature = "c_bindings"))]
use libc::FILE;
#[cfg(feature = "std")]
use std::fs::File;
#[cfg(feature = "std")]
use std::io::Read;
#[cfg(feature = "std")]
use kzg::eip_4844::load_trusted_setup_string;
#[cfg(feature = "c_bindings")]
use crate::types::{fr::MclFr, g1::MclG1};
#[cfg(feature = "c_bindings")]
use crate::{types::kzg_settings::MclKZGSettings, utils::PRECOMPUTATION_TABLES};
#[cfg(feature = "c_bindings")]
macro_rules! handle_ckzg_badargs {
($x: expr) => {
match $x {
Ok(value) => value,
Err(_) => return kzg::eth::c_bindings::CKzgRet::BadArgs,
}
};
}
#[cfg(feature = "c_bindings")]
fn kzg_settings_to_c(rust_settings: &MclKZGSettings) -> CKZGSettings {
use kzg::eth::c_bindings::{blst_fp, blst_fp2, blst_fr, blst_p1, blst_p2};
CKZGSettings {
roots_of_unity: Box::leak(
rust_settings
.fs
.roots_of_unity
.iter()
.map(|r| blst_fr {
l: r.to_blst_fr().l,
})
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
brp_roots_of_unity: Box::leak(
rust_settings
.fs
.brp_roots_of_unity
.iter()
.map(|r| blst_fr {
l: r.to_blst_fr().l,
})
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
reverse_roots_of_unity: Box::leak(
rust_settings
.fs
.reverse_roots_of_unity
.iter()
.map(|r| blst_fr {
l: r.to_blst_fr().l,
})
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
g1_values_monomial: Box::leak(
rust_settings
.g1_values_monomial
.iter()
.map(|r| blst_p1 {
x: blst_fp { l: r.0.x.d },
y: blst_fp { l: r.0.y.d },
z: blst_fp { l: r.0.z.d },
})
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
g1_values_lagrange_brp: Box::leak(
rust_settings
.g1_values_lagrange_brp
.iter()
.map(|r| blst_p1 {
x: blst_fp { l: r.0.x.d },
y: blst_fp { l: r.0.y.d },
z: blst_fp { l: r.0.z.d },
})
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
g2_values_monomial: Box::leak(
rust_settings
.g2_values_monomial
.iter()
.map(|r| blst_p2 {
x: blst_fp2 {
fp: [blst_fp { l: r.0.x.d[0].d }, blst_fp { l: r.0.x.d[1].d }],
},
y: blst_fp2 {
fp: [blst_fp { l: r.0.y.d[0].d }, blst_fp { l: r.0.y.d[1].d }],
},
z: blst_fp2 {
fp: [blst_fp { l: r.0.z.d[0].d }, blst_fp { l: r.0.z.d[1].d }],
},
})
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
x_ext_fft_columns: Box::leak(
rust_settings
.x_ext_fft_columns
.iter()
.map(|r| {
Box::leak(
r.iter()
.map(|r| blst_p1 {
x: blst_fp { l: r.0.x.d },
y: blst_fp { l: r.0.y.d },
z: blst_fp { l: r.0.z.d },
})
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr()
})
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
tables: core::ptr::null_mut(),
wbits: 0,
scratch_size: 0,
}
}
#[cfg(feature = "std")]
pub fn load_trusted_setup_filename_rust(
filepath: &str,
) -> Result<crate::types::kzg_settings::MclKZGSettings, alloc::string::String> {
let mut file = File::open(filepath).map_err(|_| "Unable to open file".to_string())?;
let mut contents = String::new();
file.read_to_string(&mut contents)
.map_err(|_| "Unable to read file".to_string())?;
let (g1_monomial_bytes, g1_lagrange_bytes, g2_monomial_bytes) =
load_trusted_setup_string(&contents)?;
load_trusted_setup_rust(&g1_monomial_bytes, &g1_lagrange_bytes, &g2_monomial_bytes)
}
/// # Safety
#[cfg(feature = "c_bindings")]
#[no_mangle]
pub unsafe extern "C" fn blob_to_kzg_commitment(
out: *mut KZGCommitment,
blob: *const Blob,
s: &CKZGSettings,
) -> CKzgRet {
use kzg::eip_4844::blob_to_kzg_commitment_raw;
let settings: MclKZGSettings = handle_ckzg_badargs!(s.try_into());
let result = handle_ckzg_badargs!(blob_to_kzg_commitment_raw((*blob).bytes, &settings));
(*out).bytes = result.to_bytes();
CKzgRet::Ok
}
/// # Safety
#[cfg(feature = "c_bindings")]
#[no_mangle]
pub unsafe extern "C" fn load_trusted_setup(
out: *mut CKZGSettings,
g1_monomial_bytes: *const u8,
num_g1_monomial_bytes: u64,
g1_lagrange_bytes: *const u8,
num_g1_lagrange_bytes: u64,
g2_monomial_bytes: *const u8,
num_g2_monomial_bytes: u64,
_precompute: u64,
) -> CKzgRet {
*out = CKZGSettings {
brp_roots_of_unity: ptr::null_mut(),
roots_of_unity: ptr::null_mut(),
reverse_roots_of_unity: ptr::null_mut(),
g1_values_monomial: ptr::null_mut(),
g1_values_lagrange_brp: ptr::null_mut(),
g2_values_monomial: ptr::null_mut(),
x_ext_fft_columns: ptr::null_mut(),
tables: ptr::null_mut(),
wbits: 0,
scratch_size: 0,
};
let g1_monomial_bytes =
core::slice::from_raw_parts(g1_monomial_bytes, num_g1_monomial_bytes as usize);
let g1_lagrange_bytes =
core::slice::from_raw_parts(g1_lagrange_bytes, num_g1_lagrange_bytes as usize);
let g2_monomial_bytes =
core::slice::from_raw_parts(g2_monomial_bytes, num_g2_monomial_bytes as usize);
TRUSTED_SETUP_NUM_G1_POINTS = num_g1_monomial_bytes as usize / BYTES_PER_G1;
let mut settings = handle_ckzg_badargs!(load_trusted_setup_rust(
g1_monomial_bytes,
g1_lagrange_bytes,
g2_monomial_bytes
));
let c_settings = kzg_settings_to_c(&settings);
PRECOMPUTATION_TABLES.save_precomputation(settings.precomputation.take(), &c_settings);
*out = c_settings;
CKzgRet::Ok
}
/// # Safety
#[cfg(all(feature = "std", feature = "c_bindings"))]
#[no_mangle]
pub unsafe extern "C" fn load_trusted_setup_file(
out: *mut CKZGSettings,
in_: *mut FILE,
) -> CKzgRet {
*out = CKZGSettings {
brp_roots_of_unity: ptr::null_mut(),
roots_of_unity: ptr::null_mut(),
reverse_roots_of_unity: ptr::null_mut(),
g1_values_monomial: ptr::null_mut(),
g1_values_lagrange_brp: ptr::null_mut(),
g2_values_monomial: ptr::null_mut(),
x_ext_fft_columns: ptr::null_mut(),
tables: ptr::null_mut(),
wbits: 0,
scratch_size: 0,
};
let mut buf = vec![0u8; 1024 * 1024];
let len: usize = libc::fread(buf.as_mut_ptr() as *mut libc::c_void, 1, buf.len(), in_);
let s = handle_ckzg_badargs!(String::from_utf8(buf[..len].to_vec()));
let (g1_monomial_bytes, g1_lagrange_bytes, g2_monomial_bytes) =
handle_ckzg_badargs!(load_trusted_setup_string(&s));
TRUSTED_SETUP_NUM_G1_POINTS = g1_monomial_bytes.len() / BYTES_PER_G1;
if TRUSTED_SETUP_NUM_G1_POINTS != FIELD_ELEMENTS_PER_BLOB {
// Helps pass the Java test "shouldThrowExceptionOnIncorrectTrustedSetupFromFile",
// as well as 5 others that pass only if this one passes (likely because Java doesn't
// deallocate its KZGSettings pointer when no exception is thrown).
return CKzgRet::BadArgs;
}
let mut settings = handle_ckzg_badargs!(load_trusted_setup_rust(
&g1_monomial_bytes,
&g1_lagrange_bytes,
&g2_monomial_bytes
));
let c_settings = kzg_settings_to_c(&settings);
PRECOMPUTATION_TABLES.save_precomputation(settings.precomputation.take(), &c_settings);
*out = c_settings;
CKzgRet::Ok
}
/// # Safety
#[no_mangle]
#[cfg(feature = "c_bindings")]
pub unsafe extern "C" fn compute_blob_kzg_proof(
out: *mut KZGProof,
blob: *const Blob,
commitment_bytes: *const Bytes48,
s: &CKZGSettings,
) -> CKzgRet {
use kzg::eip_4844::compute_blob_kzg_proof_raw;
let settings: MclKZGSettings = handle_ckzg_badargs!(s.try_into());
let proof = handle_ckzg_badargs!(compute_blob_kzg_proof_raw(
(*blob).bytes,
(*commitment_bytes).bytes,
&settings
));
(*out).bytes = proof.to_bytes();
CKzgRet::Ok
}
/// # Safety
#[no_mangle]
#[cfg(feature = "c_bindings")]
pub unsafe extern "C" fn free_trusted_setup(s: *mut CKZGSettings) {
if s.is_null() {
return;
}
PRECOMPUTATION_TABLES.remove_precomputation(&*s);
if !(*s).g1_values_monomial.is_null() {
let v = Box::from_raw(core::slice::from_raw_parts_mut(
(*s).g1_values_monomial,
FIELD_ELEMENTS_PER_BLOB,
));
drop(v);
(*s).g1_values_monomial = ptr::null_mut();
}
if !(*s).g1_values_lagrange_brp.is_null() {
let v = Box::from_raw(core::slice::from_raw_parts_mut(
(*s).g1_values_lagrange_brp,
FIELD_ELEMENTS_PER_BLOB,
));
drop(v);
(*s).g1_values_lagrange_brp = ptr::null_mut();
}
if !(*s).g2_values_monomial.is_null() {
let v = Box::from_raw(core::slice::from_raw_parts_mut(
(*s).g2_values_monomial,
TRUSTED_SETUP_NUM_G2_POINTS,
));
drop(v);
(*s).g2_values_monomial = ptr::null_mut();
}
if !(*s).x_ext_fft_columns.is_null() {
let v = Box::from_raw(core::slice::from_raw_parts_mut(
(*s).x_ext_fft_columns,
2 * ((FIELD_ELEMENTS_PER_EXT_BLOB / 2) / FIELD_ELEMENTS_PER_CELL),
));
drop(v);
(*s).x_ext_fft_columns = ptr::null_mut();
}
if !(*s).roots_of_unity.is_null() {
let v = Box::from_raw(core::slice::from_raw_parts_mut(
(*s).roots_of_unity,
FIELD_ELEMENTS_PER_EXT_BLOB + 1,
));
drop(v);
(*s).roots_of_unity = ptr::null_mut();
}
if !(*s).reverse_roots_of_unity.is_null() {
let v = Box::from_raw(core::slice::from_raw_parts_mut(
(*s).reverse_roots_of_unity,
FIELD_ELEMENTS_PER_EXT_BLOB + 1,
));
drop(v);
(*s).reverse_roots_of_unity = ptr::null_mut();
}
if !(*s).brp_roots_of_unity.is_null() {
let v = Box::from_raw(core::slice::from_raw_parts_mut(
(*s).brp_roots_of_unity,
FIELD_ELEMENTS_PER_EXT_BLOB,
));
drop(v);
(*s).brp_roots_of_unity = ptr::null_mut();
}
}
/// # Safety
#[no_mangle]
#[cfg(feature = "c_bindings")]
pub unsafe extern "C" fn verify_kzg_proof(
ok: *mut bool,
commitment_bytes: *const Bytes48,
z_bytes: *const Bytes32,
y_bytes: *const Bytes32,
proof_bytes: *const Bytes48,
s: &CKZGSettings,
) -> CKzgRet {
use kzg::eip_4844::verify_kzg_proof_rust;
let frz = handle_ckzg_badargs!(MclFr::from_bytes(&(*z_bytes).bytes));
let fry = handle_ckzg_badargs!(MclFr::from_bytes(&(*y_bytes).bytes));
let g1commitment = handle_ckzg_badargs!(MclG1::from_bytes(&(*commitment_bytes).bytes));
let g1proof = handle_ckzg_badargs!(MclG1::from_bytes(&(*proof_bytes).bytes));
let settings: MclKZGSettings = handle_ckzg_badargs!(s.try_into());
let result = handle_ckzg_badargs!(verify_kzg_proof_rust(
&g1commitment,
&frz,
&fry,
&g1proof,
&settings
));
*ok = result;
CKzgRet::Ok
}
/// # Safety
#[no_mangle]
#[cfg(feature = "c_bindings")]
pub unsafe extern "C" fn verify_blob_kzg_proof(
ok: *mut bool,
blob: *const Blob,
commitment_bytes: *const Bytes48,
proof_bytes: *const Bytes48,
s: &CKZGSettings,
) -> CKzgRet {
use kzg::eip_4844::verify_blob_kzg_proof_raw;
let settings: MclKZGSettings = handle_ckzg_badargs!(s.try_into());
let result = handle_ckzg_badargs!(verify_blob_kzg_proof_raw(
(*blob).bytes,
(*commitment_bytes).bytes,
(*proof_bytes).bytes,
&settings,
));
*ok = result;
CKzgRet::Ok
}
/// # Safety
#[no_mangle]
#[cfg(feature = "c_bindings")]
pub unsafe extern "C" fn verify_blob_kzg_proof_batch(
ok: *mut bool,
blobs: *const Blob,
commitments_bytes: *const Bytes48,
proofs_bytes: *const Bytes48,
n: usize,
s: &CKZGSettings,
) -> CKzgRet {
use kzg::eip_4844::verify_blob_kzg_proof_batch_raw;
let raw_blobs = core::slice::from_raw_parts(blobs, n)
.iter()
.map(|blob| blob.bytes)
.collect::<Vec<_>>();
let raw_commitments = core::slice::from_raw_parts(commitments_bytes, n)
.iter()
.map(|c| c.bytes)
.collect::<Vec<_>>();
let raw_proofs = core::slice::from_raw_parts(proofs_bytes, n)
.iter()
.map(|p| p.bytes)
.collect::<Vec<_>>();
*ok = false;
let settings: MclKZGSettings = handle_ckzg_badargs!(s.try_into());
let result = handle_ckzg_badargs!(verify_blob_kzg_proof_batch_raw(
&raw_blobs,
&raw_commitments,
&raw_proofs,
&settings
));
*ok = result;
CKzgRet::Ok
}
/// # Safety
#[no_mangle]
#[cfg(feature = "c_bindings")]
pub unsafe extern "C" fn compute_kzg_proof(
proof_out: *mut KZGProof,
y_out: *mut Bytes32,
blob: *const Blob,
z_bytes: *const Bytes32,
s: &CKZGSettings,
) -> CKzgRet {
use kzg::eip_4844::compute_kzg_proof_raw;
let settings: MclKZGSettings = handle_ckzg_badargs!(s.try_into());
let (proof_out_tmp, fry_tmp) = handle_ckzg_badargs!(compute_kzg_proof_raw(
(*blob).bytes,
(*z_bytes).bytes,
&settings
));
(*proof_out).bytes = proof_out_tmp.to_bytes();
(*y_out).bytes = fry_tmp.to_bytes();
CKzgRet::Ok
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/kzg_proofs.rs | mcl/src/kzg_proofs.rs | extern crate alloc;
use crate::mcl_methods::{mcl_gt, pairing};
use crate::types::fp::MclFp;
use crate::types::g1::{MclG1, MclG1ProjAddAffine};
use crate::types::{fr::MclFr, g1::MclG1Affine};
use kzg::msm::{msm_impls::msm, precompute::PrecomputationTable};
use crate::types::g2::MclG2;
use kzg::PairingVerify;
impl PairingVerify<MclG1, MclG2> for MclG1 {
fn verify(a1: &MclG1, a2: &MclG2, b1: &MclG1, b2: &MclG2) -> bool {
pairings_verify(a1, a2, b1, b2)
}
}
pub fn g1_linear_combination(
out: &mut MclG1,
points: &[MclG1],
scalars: &[MclFr],
len: usize,
precomputation: Option<
&PrecomputationTable<MclFr, MclG1, MclFp, MclG1Affine, MclG1ProjAddAffine>,
>,
) {
*out = msm::<MclG1, MclFp, MclG1Affine, MclG1ProjAddAffine, MclFr>(
points,
scalars,
len,
precomputation,
);
}
pub fn pairings_verify(a1: &MclG1, a2: &MclG2, b1: &MclG1, b2: &MclG2) -> bool {
// Todo: make optimization
let mut gt0 = mcl_gt::default();
pairing(&mut gt0, &a1.0, &a2.0);
let mut gt1 = mcl_gt::default();
pairing(&mut gt1, &b1.0, &b2.0);
gt0 == gt1
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/kzg_settings.rs | mcl/src/kzg_settings.rs | use crate::data_types::{fr::Fr, g1::G1, g2::G2};
use crate::fk20_fft::FFTSettings;
use crate::kzg10::Curve;
use crate::kzg10::Polynomial;
use kzg::common_utils::is_power_of_2;
#[derive(Debug, Clone, Default)]
pub struct KZGSettings {
pub fft_settings: FFTSettings,
pub curve: Curve,
}
impl KZGSettings {
pub fn new_from_curve(curve: &Curve, fft_settings: &FFTSettings) -> Self {
KZGSettings {
fft_settings: fft_settings.clone(),
curve: curve.clone(),
}
}
pub fn new(
secret_g1: &[G1],
secret_g2: &[G2],
length: usize,
fft_settings: &FFTSettings,
) -> Result<Self, String> {
if length < fft_settings.max_width {
return Err(String::from(
"length must be equal to or greater than fft settings max width",
));
}
if secret_g1.len() < fft_settings.max_width {
return Err(String::from(
"secret g1 must have a length equal to or greater than fft settings max width",
));
}
if secret_g2.len() < fft_settings.max_width {
return Err(String::from(
"secret g2 must have a length equal to or greater than fft settings max width",
));
}
let mut secret1: Vec<G1> = vec![];
let mut secret2: Vec<G2> = vec![];
for i in 0..length {
secret1.push(secret_g1[i]);
secret2.push(secret_g2[i]);
}
let curve = Curve::new2(&secret1, &secret2, length);
Ok(KZGSettings {
fft_settings: fft_settings.clone(),
curve,
})
}
pub fn check_proof_single(&self, commitment: &G1, proof: &G1, x: &Fr, y: &Fr) -> bool {
self.curve.is_proof_valid(commitment, proof, x, y)
}
pub fn compute_proof_multi(&self, p: &Polynomial, x0: &Fr, n: usize) -> Result<G1, String> {
if !is_power_of_2(n) {
return Err(String::from("n must be a power of 2"));
}
let mut divisor = Polynomial::from_fr(vec![]);
let x_pow_n = x0.pow(n);
divisor.coeffs.push(x_pow_n.get_neg());
for _ in 1..n {
divisor.coeffs.push(Fr::zero());
}
divisor.coeffs.push(Fr::one());
let temp_poly = p.clone();
let q = temp_poly.div(&divisor.coeffs).unwrap();
Ok(q.commit(&self.curve.g1_points).unwrap())
}
pub fn check_proof_multi(
&self,
commitment: &G1,
proof: &G1,
x: &Fr,
ys: &[Fr],
n: usize,
) -> Result<bool, String> {
if !is_power_of_2(n) {
return Err(String::from("n must be a power of 2"));
}
let mut interpolation_poly = Polynomial::new(n);
interpolation_poly.coeffs = self.fft_settings.fft(ys, true).unwrap();
let inv_x = x.inverse();
let mut inv_x_pow = inv_x;
for i in 1..n {
interpolation_poly.coeffs[i] = interpolation_poly.coeffs[i] * inv_x_pow;
inv_x_pow = inv_x_pow * inv_x;
}
let x_pow = inv_x_pow.inverse();
let xn2 = &self.curve.g2_gen * &x_pow;
let xn_minus_yn = self.curve.g2_points[n] - xn2;
let is1 = interpolation_poly.commit(&self.curve.g1_points).unwrap();
let commit_minus_interp = commitment - &is1;
Ok(Curve::verify_pairing(
&commit_minus_interp,
&self.curve.g2_gen,
proof,
&xn_minus_yn,
))
}
pub fn generate_trusted_setup(n: usize, secret: [u8; 32usize]) -> (Vec<G1>, Vec<G2>) {
let g1_gen = G1::gen();
let g2_gen = G2::gen();
let mut g1_points = vec![G1::default(); n];
let mut g2_points = vec![G2::default(); n];
let secretfr = Fr::from_bytes(&secret);
let mut secret_to_power = Fr::one();
for i in 0..n {
g1_points[i] = &g1_gen * &secret_to_power;
g2_points[i] = &g2_gen * &secret_to_power;
secret_to_power *= secretfr.as_ref().unwrap();
}
(g1_points, g2_points)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/eip_7594.rs | mcl/src/eip_7594.rs | extern crate alloc;
use kzg::EcBackend;
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fp::MclFp;
use crate::types::g1::MclG1;
use crate::types::g1::MclG1Affine;
use crate::types::g1::MclG1ProjAddAffine;
use crate::types::g2::MclG2;
use crate::types::kzg_settings::MclKZGSettings;
use crate::types::poly::MclPoly;
use crate::types::fr::MclFr;
pub struct MclBackend;
impl EcBackend for MclBackend {
type Fr = MclFr;
type G1Fp = MclFp;
type G1Affine = MclG1Affine;
type G1ProjAddAffine = MclG1ProjAddAffine;
type G1 = MclG1;
type G2 = MclG2;
type Poly = MclPoly;
type FFTSettings = MclFFTSettings;
type KZGSettings = MclKZGSettings;
}
kzg::c_bindings_eip7594!(MclBackend);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/zero_poly.rs | mcl/src/zero_poly.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use core::cmp::{min, Ordering};
use kzg::{common_utils::next_pow_of_2, FFTFr, Fr, ZeroPoly};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
use crate::types::poly::MclPoly;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use smallvec::{smallvec, SmallVec};
// Can be tuned & optimized (must be a power of 2)
const DEGREE_OF_PARTIAL: usize = 256;
// Can be tuned & optimized (but must be a power of 2)
const REDUCTION_FACTOR: usize = 4;
/// Pad given poly it with zeros to new length
pub fn pad_poly(mut poly: Vec<MclFr>, new_length: usize) -> Result<Vec<MclFr>, String> {
if new_length < poly.len() {
return Err(String::from(
"new_length must be longer or equal to poly length",
));
}
poly.resize(new_length, MclFr::zero());
Ok(poly)
}
/// Pad given poly coefficients it with zeros to new length
pub fn pad_poly_coeffs<const N: usize, T>(
mut coeffs: SmallVec<[T; N]>,
new_length: usize,
) -> Result<SmallVec<[T; N]>, String>
where
T: Default + Clone,
{
if new_length < coeffs.len() {
return Err(String::from(
"new_length must be longer or equal to coeffs length",
));
}
coeffs.resize(new_length, T::default());
Ok(coeffs)
}
impl MclFFTSettings {
fn do_zero_poly_mul_partial(
&self,
idxs: &[usize],
stride: usize,
) -> Result<SmallVec<[MclFr; DEGREE_OF_PARTIAL]>, String> {
if idxs.is_empty() {
return Err(String::from("idx array must not be empty"));
}
// Makes use of long multiplication in terms of (x - w_0)(x - w_1)..
let mut coeffs = SmallVec::<[MclFr; DEGREE_OF_PARTIAL]>::new();
// For the first member, store -w_0 as constant term
coeffs.push(self.roots_of_unity[idxs[0] * stride].negate());
for (i, idx) in idxs.iter().copied().enumerate().skip(1) {
// For member (x - w_i) take coefficient as -(w_i + w_{i-1} + ...)
let neg_di = self.roots_of_unity[idx * stride].negate();
coeffs.push(neg_di.add(&coeffs[i - 1]));
// Multiply all previous members by (x - w_i)
// It equals multiplying by - w_i and adding x^(i - 1) coefficient (implied multiplication by x)
for j in (1..i).rev() {
coeffs[j] = coeffs[j].mul(&neg_di).add(&coeffs[j - 1]);
}
// Multiply x^0 member by - w_i
coeffs[0] = coeffs[0].mul(&neg_di);
}
coeffs.resize(idxs.len() + 1, MclFr::one());
Ok(coeffs)
}
fn reduce_partials(
&self,
domain_size: usize,
partial_coeffs: SmallVec<[SmallVec<[MclFr; DEGREE_OF_PARTIAL]>; REDUCTION_FACTOR]>,
) -> Result<SmallVec<[MclFr; DEGREE_OF_PARTIAL]>, String> {
if !domain_size.is_power_of_two() {
return Err(String::from("Expected domain size to be a power of 2"));
}
if partial_coeffs.is_empty() {
return Err(String::from("partials must not be empty"));
}
// Calculate the resulting polynomial degree
// E.g. (a * x^n + ...) (b * x^m + ...) has a degree of x^(n+m)
let out_degree = partial_coeffs
.iter()
.map(|partial| {
// TODO: Not guaranteed by function signature that this doesn't underflow
partial.len() - 1
})
.sum::<usize>();
if out_degree + 1 > domain_size {
return Err(String::from(
"Out degree is longer than possible polynomial size in domain",
));
}
let mut partial_coeffs = partial_coeffs.into_iter();
// Pad all partial polynomials to same length, compute their FFT and multiply them together
let mut padded_partial = pad_poly_coeffs(
partial_coeffs
.next()
.expect("Not empty, checked above; qed"),
domain_size,
)?;
let mut eval_result: SmallVec<[MclFr; DEGREE_OF_PARTIAL]> =
smallvec![MclFr::zero(); domain_size];
self.fft_fr_output(&padded_partial, false, &mut eval_result)?;
for partial in partial_coeffs {
padded_partial = pad_poly_coeffs(partial, domain_size)?;
let mut evaluated_partial: SmallVec<[MclFr; DEGREE_OF_PARTIAL]> =
smallvec![MclFr::zero(); domain_size];
self.fft_fr_output(&padded_partial, false, &mut evaluated_partial)?;
eval_result
.iter_mut()
.zip(evaluated_partial.iter())
.for_each(|(eval_result, evaluated_partial)| {
*eval_result = eval_result.mul(evaluated_partial);
});
}
let mut coeffs = smallvec![MclFr::zero(); domain_size];
// Apply an inverse FFT to produce a new poly. Limit its size to out_degree + 1
self.fft_fr_output(&eval_result, true, &mut coeffs)?;
coeffs.truncate(out_degree + 1);
Ok(coeffs)
}
}
impl ZeroPoly<MclFr, MclPoly> for MclFFTSettings {
fn do_zero_poly_mul_partial(&self, idxs: &[usize], stride: usize) -> Result<MclPoly, String> {
self.do_zero_poly_mul_partial(idxs, stride)
.map(|coeffs| MclPoly {
coeffs: coeffs.into_vec(),
})
}
fn reduce_partials(&self, domain_size: usize, partials: &[MclPoly]) -> Result<MclPoly, String> {
self.reduce_partials(
domain_size,
partials
.iter()
.map(|partial| SmallVec::from_slice(&partial.coeffs))
.collect(),
)
.map(|coeffs| MclPoly {
coeffs: coeffs.into_vec(),
})
}
fn zero_poly_via_multiplication(
&self,
domain_size: usize,
missing_idxs: &[usize],
) -> Result<(Vec<MclFr>, MclPoly), String> {
let zero_eval: Vec<MclFr>;
let mut zero_poly: MclPoly;
if missing_idxs.is_empty() {
zero_eval = Vec::new();
zero_poly = MclPoly { coeffs: Vec::new() };
return Ok((zero_eval, zero_poly));
}
if missing_idxs.len() >= domain_size {
return Err(String::from("Missing idxs greater than domain size"));
} else if domain_size > self.max_width {
return Err(String::from(
"Domain size greater than fft_settings.max_width",
));
} else if !domain_size.is_power_of_two() {
return Err(String::from("Domain size must be a power of 2"));
}
let missing_per_partial = DEGREE_OF_PARTIAL - 1; // Number of missing idxs needed per partial
let domain_stride = self.max_width / domain_size;
let mut partial_count = 1 + (missing_idxs.len() - 1) / missing_per_partial; // TODO: explain why -1 is used here
let next_pow: usize = next_pow_of_2(partial_count * DEGREE_OF_PARTIAL);
let domain_ceiling = min(next_pow, domain_size);
// Calculate zero poly
if missing_idxs.len() <= missing_per_partial {
// When all idxs fit into a single multiplication
zero_poly = MclPoly {
coeffs: self
.do_zero_poly_mul_partial(missing_idxs, domain_stride)?
.into_vec(),
};
} else {
// Otherwise, construct a set of partial polynomials
// Save all constructed polynomials in a shared 'work' vector
let mut work = vec![MclFr::zero(); next_pow];
let mut partial_lens = vec![DEGREE_OF_PARTIAL; partial_count];
#[cfg(not(feature = "parallel"))]
let iter = missing_idxs
.chunks(missing_per_partial)
.zip(work.chunks_exact_mut(DEGREE_OF_PARTIAL));
#[cfg(feature = "parallel")]
let iter = missing_idxs
.par_chunks(missing_per_partial)
.zip(work.par_chunks_exact_mut(DEGREE_OF_PARTIAL));
// Insert all generated partial polynomials at degree_of_partial intervals in work vector
iter.for_each(|(missing_idxs, work)| {
let partial_coeffs = self
.do_zero_poly_mul_partial(missing_idxs, domain_stride)
.expect("`missing_idxs` is guaranteed to not be empty; qed");
let partial_coeffs = pad_poly_coeffs(partial_coeffs, DEGREE_OF_PARTIAL).expect(
"`partial.coeffs.len()` (same as `missing_idxs.len() + 1`) is \
guaranteed to be at most `degree_of_partial`; qed",
);
work[..DEGREE_OF_PARTIAL].copy_from_slice(&partial_coeffs);
});
// Adjust last length to match its actual length
partial_lens[partial_count - 1] =
1 + missing_idxs.len() - (partial_count - 1) * missing_per_partial;
// Reduce all vectors into one by reducing them w/ varying size multiplications
while partial_count > 1 {
let reduced_count = 1 + (partial_count - 1) / REDUCTION_FACTOR;
let partial_size = next_pow_of_2(partial_lens[0]);
// Step over polynomial space and produce larger multiplied polynomials
for i in 0..reduced_count {
let start = i * REDUCTION_FACTOR;
let out_end = min((start + REDUCTION_FACTOR) * partial_size, domain_ceiling);
let reduced_len = min(out_end - start * partial_size, domain_size);
let partials_num = min(REDUCTION_FACTOR, partial_count - start);
// Calculate partial views from lens and offsets
// Also update offsets to match current iteration
let partial_offset = start * partial_size;
let mut partial_coeffs = SmallVec::new();
for (partial_offset, partial_len) in (partial_offset..)
.step_by(partial_size)
.zip(partial_lens.iter().skip(i).copied())
.take(partials_num)
{
// We know the capacity required in `reduce_partials()` call below to avoid
// re-allocation
let mut coeffs = SmallVec::with_capacity(reduced_len);
coeffs.extend_from_slice(&work[partial_offset..][..partial_len]);
partial_coeffs.push(coeffs);
}
if partials_num > 1 {
let mut reduced_coeffs =
self.reduce_partials(reduced_len, partial_coeffs)?;
// Update partial length to match its length after reduction
partial_lens[i] = reduced_coeffs.len();
reduced_coeffs =
pad_poly_coeffs(reduced_coeffs, partial_size * partials_num)?;
work[partial_offset..][..reduced_coeffs.len()]
.copy_from_slice(&reduced_coeffs);
} else {
// Instead of keeping track of remaining polynomials, reuse i'th partial for start'th one
partial_lens[i] = partial_lens[start];
}
}
// Number of steps done equals the number of polynomials that we still need to reduce together
partial_count = reduced_count;
}
zero_poly = MclPoly { coeffs: work };
}
// Pad resulting poly to expected
match zero_poly.coeffs.len().cmp(&domain_size) {
Ordering::Less => {
zero_poly.coeffs = pad_poly(zero_poly.coeffs, domain_size)?;
}
Ordering::Equal => {}
Ordering::Greater => {
zero_poly.coeffs.truncate(domain_size);
}
}
// Evaluate calculated poly
zero_eval = self.fft_fr(&zero_poly.coeffs, false)?;
Ok((zero_eval, zero_poly))
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/data_availability_sampling.rs | mcl/src/data_availability_sampling.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use core::cmp::Ordering;
use kzg::{DASExtension, Fr};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
// TODO: explain algo
impl MclFFTSettings {
pub fn das_fft_extension_stride(&self, evens: &mut [MclFr], stride: usize) {
match evens.len().cmp(&2) {
Ordering::Less => {
return;
}
Ordering::Equal => {
let x = evens[0].add(&evens[1]);
let y = evens[0].sub(&evens[1]);
let y_times_root = y.mul(&self.roots_of_unity[stride]);
evens[0] = x.add(&y_times_root);
evens[1] = x.sub(&y_times_root);
return;
}
Ordering::Greater => {}
}
let half: usize = evens.len() / 2;
for i in 0..half {
let tmp1 = evens[i].add(&evens[half + i]);
let tmp2 = evens[i].sub(&evens[half + i]);
evens[half + i] = tmp2.mul(&self.reverse_roots_of_unity[i * 2 * stride]);
evens[i] = tmp1;
}
#[cfg(feature = "parallel")]
{
if evens.len() > 32 {
let (lo, hi) = evens.split_at_mut(half);
rayon::join(
|| self.das_fft_extension_stride(hi, stride * 2),
|| self.das_fft_extension_stride(lo, stride * 2),
);
} else {
// Recurse
self.das_fft_extension_stride(&mut evens[..half], stride * 2);
self.das_fft_extension_stride(&mut evens[half..], stride * 2);
}
}
#[cfg(not(feature = "parallel"))]
{
// Recurse
self.das_fft_extension_stride(&mut evens[..half], stride * 2);
self.das_fft_extension_stride(&mut evens[half..], stride * 2);
}
for i in 0..half {
let x = evens[i];
let y = evens[half + i];
let y_times_root: MclFr = y.mul(&self.roots_of_unity[(1 + 2 * i) * stride]);
evens[i] = x.add(&y_times_root);
evens[half + i] = x.sub(&y_times_root);
}
}
}
impl DASExtension<MclFr> for MclFFTSettings {
/// Polynomial extension for data availability sampling. Given values of even indices, produce values of odd indices.
/// FFTSettings must hold at least 2 times the roots of provided evens.
/// The resulting odd indices make the right half of the coefficients of the inverse FFT of the combined indices zero.
fn das_fft_extension(&self, evens: &[MclFr]) -> Result<Vec<MclFr>, String> {
if evens.is_empty() {
return Err(String::from("A non-zero list ab expected"));
} else if !evens.len().is_power_of_two() {
return Err(String::from("A list with power-of-two length expected"));
} else if evens.len() * 2 > self.max_width {
return Err(String::from(
"Supplied list is longer than the available max width",
));
}
// In case more roots are provided with fft_settings, use a larger stride
let stride = self.max_width / (evens.len() * 2);
let mut odds = evens.to_vec();
self.das_fft_extension_stride(&mut odds, stride);
// TODO: explain why each odd member is multiplied by euclidean inverse of length
let mut inv_len = MclFr::from_u64(odds.len() as u64);
inv_len = inv_len.eucl_inverse();
let odds = odds.iter().map(|f| f.mul(&inv_len)).collect();
Ok(odds)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/fk20_proofs.rs | mcl/src/fk20_proofs.rs | extern crate alloc;
use alloc::vec;
use alloc::vec::Vec;
use kzg::{FFTFr, Fr, G1Mul, Poly, FFTG1, G1};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
use crate::types::g1::MclG1;
use crate::types::poly::MclPoly;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
impl MclFFTSettings {
pub fn toeplitz_part_1(&self, x: &[MclG1]) -> Vec<MclG1> {
let n = x.len();
let n2 = n * 2;
let mut x_ext = Vec::with_capacity(n2);
x_ext.extend(x.iter().take(n));
x_ext.resize(n2, MclG1::identity());
self.fft_g1(&x_ext, false).unwrap()
}
/// poly and x_ext_fft should be of same length
pub fn toeplitz_part_2(&self, poly: &MclPoly, x_ext_fft: &[MclG1]) -> Vec<MclG1> {
let coeffs_fft = self.fft_fr(&poly.coeffs, false).unwrap();
#[cfg(feature = "parallel")]
{
coeffs_fft
.into_par_iter()
.zip(x_ext_fft)
.take(poly.len())
.map(|(coeff_fft, x_ext_fft)| x_ext_fft.mul(&coeff_fft))
.collect()
}
#[cfg(not(feature = "parallel"))]
{
coeffs_fft
.into_iter()
.zip(x_ext_fft)
.take(poly.len())
.map(|(coeff_fft, x_ext_fft)| x_ext_fft.mul(&coeff_fft))
.collect()
}
}
pub fn toeplitz_part_3(&self, h_ext_fft: &[MclG1]) -> Vec<MclG1> {
let n2 = h_ext_fft.len();
let n = n2 / 2;
let mut ret = self.fft_g1(h_ext_fft, true).unwrap();
ret[n..n2].copy_from_slice(&vec![MclG1::identity(); n2 - n]);
ret
}
}
impl MclPoly {
pub fn toeplitz_coeffs_stride(&self, offset: usize, stride: usize) -> MclPoly {
let n = self.len();
let k = n / stride;
let k2 = k * 2;
let mut ret = MclPoly::default();
ret.coeffs.push(self.coeffs[n - 1 - offset]);
let num_of_zeroes = if k + 2 < k2 { k + 2 - 1 } else { k2 - 1 };
for _ in 0..num_of_zeroes {
ret.coeffs.push(MclFr::zero());
}
let mut i = k + 2;
let mut j = 2 * stride - offset - 1;
while i < k2 {
ret.coeffs.push(self.coeffs[j]);
i += 1;
j += stride;
}
ret
}
pub fn toeplitz_coeffs_step(&self) -> MclPoly {
self.toeplitz_coeffs_stride(0, 1)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/utils.rs | mcl/src/utils.rs | extern crate alloc;
use alloc::vec::Vec;
use kzg::common_utils::log2_pow2;
use kzg::eip_4844::{hash_to_bls_field, PrecomputationTableManager};
use kzg::{FFTSettings, Fr, G1Mul, G2Mul, FFTG1, G1, G2};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fp::MclFp;
use crate::types::fr::MclFr;
use crate::types::g1::{MclG1, MclG1Affine, MclG1ProjAddAffine};
use crate::types::g2::MclG2;
pub fn generate_trusted_setup(
n: usize,
secret: [u8; 32usize],
) -> (Vec<MclG1>, Vec<MclG1>, Vec<MclG2>) {
let s = hash_to_bls_field(&secret);
let mut s_pow = Fr::one();
let mut g1_monomial_values = Vec::with_capacity(n);
let mut g2_monomial_values = Vec::with_capacity(n);
for _ in 0..n {
g1_monomial_values.push(MclG1::generator().mul(&s_pow));
g2_monomial_values.push(MclG2::generator().mul(&s_pow));
s_pow = s_pow.mul(&s);
}
let s = MclFFTSettings::new(log2_pow2(n)).unwrap();
let g1_lagrange_values = s.fft_g1(&g1_monomial_values, true).unwrap();
(g1_monomial_values, g1_lagrange_values, g2_monomial_values)
}
pub(crate) static mut PRECOMPUTATION_TABLES: PrecomputationTableManager<
MclFr,
MclG1,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
> = PrecomputationTableManager::new();
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/mcl_methods.rs | mcl/src/mcl_methods.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use core::mem::MaybeUninit;
use core::ops::{Add, AddAssign};
use core::ops::{Div, DivAssign};
use core::ops::{Mul, MulAssign};
use core::ops::{Sub, SubAssign};
use core::primitive::str;
use once_cell::sync::OnceCell;
#[link(name = "mcl", kind = "static")]
#[cfg_attr(target_arch = "x86_64", link(name = "stdc++"))]
#[allow(non_snake_case, clippy::duplicated_attributes)]
extern "C" {
// global functions
fn mclBn_init(curve: i32, compiledTimeVar: i32) -> i32;
fn mclBn_getVersion() -> u32;
fn mclBn_getFrByteSize() -> u32;
fn mclBn_getFpByteSize() -> u32;
fn mclBn_getCurveOrder(buf: *mut u8, maxBufSize: usize) -> usize;
fn mclBn_getFieldOrder(buf: *mut u8, maxBufSize: usize) -> usize;
fn mclBn_pairing(z: *mut mcl_gt, x: *const mcl_g1, y: *const mcl_g2);
fn mclBn_millerLoop(z: *mut mcl_gt, x: *const mcl_g1, y: *const mcl_g2);
fn mclBn_finalExp(y: *mut mcl_gt, x: *const mcl_gt);
// mcl_fr
fn mclBnFr_isEqual(x: *const mcl_fr, y: *const mcl_fr) -> i32;
fn mclBnFr_isValid(x: *const mcl_fr) -> i32;
fn mclBnFr_isZero(x: *const mcl_fr) -> i32;
fn mclBnFr_isOne(x: *const mcl_fr) -> i32;
fn mclBnFr_isOdd(x: *const mcl_fr) -> i32;
fn mclBnFr_isNegative(x: *const mcl_fr) -> i32;
fn mclBnFr_cmp(x: *const mcl_fr, y: *const mcl_fr) -> i32;
fn mclBnFr_setStr(x: *mut mcl_fr, buf: *const u8, bufSize: usize, ioMode: i32) -> i32;
fn mclBnFr_getStr(buf: *mut u8, maxBufSize: usize, x: *const mcl_fr, ioMode: i32) -> usize;
fn mclBnFr_serialize(buf: *mut u8, maxBufSize: usize, x: *const mcl_fr) -> usize;
fn mclBnFr_deserialize(x: *mut mcl_fr, buf: *const u8, bufSize: usize) -> usize;
fn mclBnFr_setInt32(x: *mut mcl_fr, v: i32);
fn mclBnFr_setLittleEndian(x: *mut mcl_fr, buf: *const u8, bufSize: usize) -> i32;
fn mclBnFr_setLittleEndianMod(x: *mut mcl_fr, buf: *const u8, bufSize: usize) -> i32;
fn mclBnFr_setHashOf(x: *mut mcl_fr, buf: *const u8, bufSize: usize) -> i32;
fn mclBnFr_setByCSPRNG(x: *mut mcl_fr);
fn mclBnFr_add(z: *mut mcl_fr, x: *const mcl_fr, y: *const mcl_fr);
fn mclBnFr_sub(z: *mut mcl_fr, x: *const mcl_fr, y: *const mcl_fr);
fn mclBnFr_neg(y: *mut mcl_fr, x: *const mcl_fr);
fn mclBnFr_mul(z: *mut mcl_fr, x: *const mcl_fr, y: *const mcl_fr);
fn mclBnFr_div(z: *mut mcl_fr, x: *const mcl_fr, y: *const mcl_fr);
fn mclBnFr_inv(y: *mut mcl_fr, x: *const mcl_fr);
fn mclBnFr_sqr(y: *mut mcl_fr, x: *const mcl_fr);
fn mclBnFr_squareRoot(y: *mut mcl_fr, x: *const mcl_fr) -> i32;
// mcl_fp
pub fn mclBnFp_isEqual(x: *const mcl_fp, y: *const mcl_fp) -> i32;
pub fn mclBnFp_isValid(x: *const mcl_fp) -> i32;
pub fn mclBnFp_isZero(x: *const mcl_fp) -> i32;
pub fn mclBnFp_isOne(x: *const mcl_fp) -> i32;
pub fn mclBnFp_isOdd(x: *const mcl_fp) -> i32;
pub fn mclBnFp_isNegative(x: *const mcl_fp) -> i32;
pub fn mclBnFp_cmp(x: *const mcl_fp, y: *const mcl_fp) -> i32;
pub fn mclBnFp_setStr(x: *mut mcl_fp, buf: *const u8, bufSize: usize, ioMode: i32) -> i32;
pub fn mclBnFp_getStr(buf: *mut u8, maxBufSize: usize, x: *const mcl_fp, ioMode: i32) -> usize;
pub fn mclBnFp_serialize(buf: *mut u8, maxBufSize: usize, x: *const mcl_fp) -> usize;
pub fn mclBnFp_deserialize(x: *mut mcl_fp, buf: *const u8, bufSize: usize) -> usize;
pub fn mclBnFp_setInt32(x: *mut mcl_fp, v: i32);
pub fn mclBnFp_setLittleEndian(x: *mut mcl_fp, buf: *const u8, bufSize: usize) -> i32;
pub fn mclBnFp_setLittleEndianMod(x: *mut mcl_fp, buf: *const u8, bufSize: usize) -> i32;
pub fn mclBnFp_setHashOf(x: *mut mcl_fp, buf: *const u8, bufSize: usize) -> i32;
pub fn mclBnFp_setByCSPRNG(x: *mut mcl_fp);
pub fn mclBnFp_add(z: *mut mcl_fp, x: *const mcl_fp, y: *const mcl_fp);
pub fn mclBnFp_sub(z: *mut mcl_fp, x: *const mcl_fp, y: *const mcl_fp);
pub fn mclBnFp_neg(y: *mut mcl_fp, x: *const mcl_fp);
pub fn mclBnFp_mul(z: *mut mcl_fp, x: *const mcl_fp, y: *const mcl_fp);
pub fn mclBnFp_div(z: *mut mcl_fp, x: *const mcl_fp, y: *const mcl_fp);
pub fn mclBnFp_inv(y: *mut mcl_fp, x: *const mcl_fp);
pub fn mclBnFp_sqr(y: *mut mcl_fp, x: *const mcl_fp);
pub fn mclBnFp_squareRoot(y: *mut mcl_fp, x: *const mcl_fp) -> i32;
// mcl_fp2
fn mclBnFp2_isEqual(x: *const mcl_fp2, y: *const mcl_fp2) -> i32;
fn mclBnFp2_isZero(x: *const mcl_fp2) -> i32;
fn mclBnFp2_serialize(buf: *mut u8, maxBufSize: usize, x: *const mcl_fp2) -> usize;
fn mclBnFp2_deserialize(x: *mut mcl_fp2, buf: *const u8, bufSize: usize) -> usize;
fn mclBnFp2_add(z: *mut mcl_fp2, x: *const mcl_fp2, y: *const mcl_fp2);
fn mclBnFp2_sub(z: *mut mcl_fp2, x: *const mcl_fp2, y: *const mcl_fp2);
fn mclBnFp2_neg(y: *mut mcl_fp2, x: *const mcl_fp2);
fn mclBnFp2_mul(z: *mut mcl_fp2, x: *const mcl_fp2, y: *const mcl_fp2);
fn mclBnFp2_div(z: *mut mcl_fp2, x: *const mcl_fp2, y: *const mcl_fp2);
fn mclBnFp2_inv(y: *mut mcl_fp2, x: *const mcl_fp2);
fn mclBnFp2_sqr(y: *mut mcl_fp2, x: *const mcl_fp2);
fn mclBnFp2_squareRoot(y: *mut mcl_fp2, x: *const mcl_fp2) -> i32;
// mcl_g1
fn mclBnG1_isEqual(x: *const mcl_g1, y: *const mcl_g1) -> i32;
fn mclBnG1_isValid(x: *const mcl_g1) -> i32;
fn mclBnG1_isZero(x: *const mcl_g1) -> i32;
fn mclBnG1_setStr(x: *mut mcl_g1, buf: *const u8, bufSize: usize, ioMode: i32) -> i32;
fn mclBnG1_getStr(buf: *mut u8, maxBufSize: usize, x: *const mcl_g1, ioMode: i32) -> usize;
fn mclBnG1_serialize(buf: *mut u8, maxBufSize: usize, x: *const mcl_g1) -> usize;
fn mclBnG1_deserialize(x: *mut mcl_g1, buf: *const u8, bufSize: usize) -> usize;
fn mclBnG1_add(z: *mut mcl_g1, x: *const mcl_g1, y: *const mcl_g1);
fn mclBnG1_sub(z: *mut mcl_g1, x: *const mcl_g1, y: *const mcl_g1);
fn mclBnG1_neg(y: *mut mcl_g1, x: *const mcl_g1);
fn mclBnG1_dbl(y: *mut mcl_g1, x: *const mcl_g1);
fn mclBnG1_mul(z: *mut mcl_g1, x: *const mcl_g1, y: *const mcl_fr);
fn mclBnG1_normalize(y: *mut mcl_g1, x: *const mcl_g1);
fn mclBnG1_hashAndMapTo(x: *mut mcl_g1, buf: *const u8, bufSize: usize) -> i32;
fn mclBnG1_mulVec(z: *mut mcl_g1, x: *const mcl_g1, y: *const mcl_fr, n: usize);
// mcl_g2
fn mclBnG2_isEqual(x: *const mcl_g2, y: *const mcl_g2) -> i32;
fn mclBnG2_isValid(x: *const mcl_g2) -> i32;
fn mclBnG2_isZero(x: *const mcl_g2) -> i32;
fn mclBnG2_setStr(x: *mut mcl_g2, buf: *const u8, bufSize: usize, ioMode: i32) -> i32;
fn mclBnG2_getStr(buf: *mut u8, maxBufSize: usize, x: *const mcl_g2, ioMode: i32) -> usize;
fn mclBnG2_serialize(buf: *mut u8, maxBufSize: usize, x: *const mcl_g2) -> usize;
fn mclBnG2_deserialize(x: *mut mcl_g2, buf: *const u8, bufSize: usize) -> usize;
fn mclBnG2_add(z: *mut mcl_g2, x: *const mcl_g2, y: *const mcl_g2);
fn mclBnG2_sub(z: *mut mcl_g2, x: *const mcl_g2, y: *const mcl_g2);
fn mclBnG2_neg(y: *mut mcl_g2, x: *const mcl_g2);
fn mclBnG2_dbl(y: *mut mcl_g2, x: *const mcl_g2);
fn mclBnG2_mul(z: *mut mcl_g2, x: *const mcl_g2, y: *const mcl_fr);
fn mclBnG2_normalize(y: *mut mcl_g2, x: *const mcl_g2);
fn mclBnG2_hashAndMapTo(x: *mut mcl_g2, buf: *const u8, bufSize: usize) -> i32;
fn mclBnG2_mulVec(z: *mut mcl_g2, x: *const mcl_g2, y: *const mcl_fr, n: usize);
// mcl_gt
fn mclBnGT_isEqual(x: *const mcl_gt, y: *const mcl_gt) -> i32;
fn mclBnGT_isZero(x: *const mcl_gt) -> i32;
fn mclBnGT_isOne(x: *const mcl_gt) -> i32;
fn mclBnGT_setStr(x: *mut mcl_gt, buf: *const u8, bufSize: usize, ioMode: i32) -> i32;
fn mclBnGT_getStr(buf: *mut u8, maxBufSize: usize, x: *const mcl_gt, ioMode: i32) -> usize;
fn mclBnGT_serialize(buf: *mut u8, maxBufSize: usize, x: *const mcl_gt) -> usize;
fn mclBnGT_deserialize(x: *mut mcl_gt, buf: *const u8, bufSize: usize) -> usize;
fn mclBnGT_setInt32(x: *mut mcl_gt, v: i32);
fn mclBnGT_add(z: *mut mcl_gt, x: *const mcl_gt, y: *const mcl_gt);
fn mclBnGT_sub(z: *mut mcl_gt, x: *const mcl_gt, y: *const mcl_gt);
fn mclBnGT_neg(y: *mut mcl_gt, x: *const mcl_gt);
fn mclBnGT_mul(z: *mut mcl_gt, x: *const mcl_gt, y: *const mcl_gt);
fn mclBnGT_div(z: *mut mcl_gt, x: *const mcl_gt, y: *const mcl_gt);
fn mclBnGT_inv(y: *mut mcl_gt, x: *const mcl_gt);
fn mclBnGT_sqr(y: *mut mcl_gt, x: *const mcl_gt);
fn mclBnGT_pow(z: *mut mcl_gt, x: *const mcl_gt, y: *const mcl_fr);
}
pub enum CurveType {
BN254 = 0,
BN381 = 1,
SNARK = 4,
BLS12_381 = 5,
BLS12_377 = 8,
#[allow(non_camel_case_types)]
BN_P256 = 9,
}
const MCLBN_FP_UNIT_SIZE: usize = 6;
const MCLBN_FR_UNIT_SIZE: usize = 4;
const MCLBN_COMPILED_TIME_VAR: i32 = MCLBN_FR_UNIT_SIZE as i32 * 10 + MCLBN_FP_UNIT_SIZE as i32;
macro_rules! common_impl {
($t:ty, $is_equal_fn:ident, $is_zero_fn:ident) => {
impl PartialEq for $t {
fn eq(&self, rhs: &Self) -> bool {
unsafe { $is_equal_fn(self, rhs) == 1 }
}
}
impl $t {
pub fn zero() -> $t {
Default::default()
}
/// # Safety
pub unsafe fn uninit() -> $t {
let u = MaybeUninit::<$t>::uninit();
let v = unsafe { u.assume_init() };
v
}
pub fn clear(&mut self) {
*self = <$t>::zero()
}
pub fn is_zero(&self) -> bool {
unsafe { $is_zero_fn(self) == 1 }
}
}
};
}
macro_rules! is_valid_impl {
($t:ty, $is_valid_fn:ident) => {
impl $t {
pub fn is_valid(&self) -> bool {
unsafe { $is_valid_fn(self) == 1 }
}
}
};
}
macro_rules! serialize_impl {
($t:ty, $size:expr, $serialize_fn:ident, $deserialize_fn:ident) => {
impl $t {
pub fn deserialize(&mut self, buf: &[u8]) -> bool {
unsafe { $deserialize_fn(self, buf.as_ptr(), buf.len()) > 0 }
}
pub fn serialize(&self) -> Vec<u8> {
let size = unsafe { $size } as usize;
let mut buf: Vec<u8> = Vec::with_capacity(size);
let n: usize;
unsafe {
n = $serialize_fn(buf.as_mut_ptr(), size, self);
}
if n == 0 {
panic!("serialize");
}
unsafe {
buf.set_len(n);
}
buf
}
}
};
}
macro_rules! str_impl {
($t:ty, $maxBufSize:expr, $get_str_fn:ident, $set_str_fn:ident) => {
impl $t {
pub fn from_str(s: &str, base: i32) -> Option<$t> {
let mut v = unsafe { <$t>::uninit() };
if v.set_str(s, base) {
return Some(v);
}
None
}
pub fn set_str(&mut self, s: &str, base: i32) -> bool {
unsafe { $set_str_fn(self, s.as_ptr(), s.len(), base) == 0 }
}
pub fn get_str(&self, io_mode: i32) -> String {
let u = MaybeUninit::<[u8; $maxBufSize]>::uninit();
let mut buf = unsafe { u.assume_init() };
let n: usize;
unsafe {
n = $get_str_fn(buf.as_mut_ptr(), buf.len(), self, io_mode);
}
if n == 0 {
panic!("mclBnFr_getStr");
}
unsafe { core::str::from_utf8_unchecked(&buf[0..n]).into() }
}
}
};
}
macro_rules! int_impl {
($t:ty, $set_int_fn:ident, $is_one_fn:ident) => {
impl $t {
pub fn from_int(x: i32) -> $t {
let mut v = unsafe { <$t>::uninit() };
v.set_int(x);
v
}
pub fn set_int(&mut self, x: i32) {
unsafe {
$set_int_fn(self, x);
}
}
pub fn is_one(&self) -> bool {
unsafe { $is_one_fn(self) == 1 }
}
}
};
}
macro_rules! base_field_impl {
($t:ty, $set_little_endian_fn:ident, $set_little_endian_mod_fn:ident, $set_hash_of_fn:ident, $set_by_csprng_fn:ident, $is_odd_fn:ident, $is_negative_fn:ident, $cmp_fn:ident, $square_root_fn:ident) => {
impl $t {
pub fn set_little_endian(&mut self, buf: &[u8]) -> bool {
unsafe { $set_little_endian_fn(self, buf.as_ptr(), buf.len()) == 0 }
}
pub fn set_little_endian_mod(&mut self, buf: &[u8]) -> bool {
unsafe { $set_little_endian_mod_fn(self, buf.as_ptr(), buf.len()) == 0 }
}
pub fn set_hash_of(&mut self, buf: &[u8]) -> bool {
unsafe { $set_hash_of_fn(self, buf.as_ptr(), buf.len()) == 0 }
}
pub fn set_by_csprng(&mut self) {
unsafe { $set_by_csprng_fn(self) }
}
pub fn is_odd(&self) -> bool {
unsafe { $is_odd_fn(self) == 1 }
}
pub fn is_negative(&self) -> bool {
unsafe { $is_negative_fn(self) == 1 }
}
pub fn mcl_cmp(&self, rhs: &$t) -> i32 {
unsafe { $cmp_fn(self, rhs) }
}
pub fn square_root(y: &mut $t, x: &$t) -> bool {
unsafe { $square_root_fn(y, x) == 0 }
}
}
};
}
macro_rules! add_op_impl {
($t:ty, $add_fn:ident, $sub_fn:ident, $neg_fn:ident) => {
impl $t {
pub fn add(z: &mut $t, x: &$t, y: &$t) {
unsafe { $add_fn(z, x, y) }
}
pub fn sub(z: &mut $t, x: &$t, y: &$t) {
unsafe { $sub_fn(z, x, y) }
}
pub fn neg(y: &mut $t, x: &$t) {
unsafe { $neg_fn(y, x) }
}
}
impl<'a> Add for &'a $t {
type Output = $t;
fn add(self, other: &$t) -> $t {
let mut v = unsafe { <$t>::uninit() };
<$t>::add(&mut v, &self, &other);
v
}
}
impl<'a> AddAssign<&'a $t> for $t {
fn add_assign(&mut self, other: &$t) {
let z: *mut $t = self;
unsafe {
$add_fn(z, z as *const $t, other as *const $t);
}
}
}
impl<'a> Sub for &'a $t {
type Output = $t;
fn sub(self, other: &$t) -> $t {
let mut v = unsafe { <$t>::uninit() };
<$t>::sub(&mut v, &self, &other);
v
}
}
impl<'a> SubAssign<&'a $t> for $t {
fn sub_assign(&mut self, other: &$t) {
let z: *mut $t = self;
unsafe {
$sub_fn(z, z as *const $t, other as *const $t);
}
}
}
};
}
macro_rules! field_mul_op_impl {
($t:ty, $mul_fn:ident, $div_fn:ident, $inv_fn:ident, $sqr_fn:ident) => {
impl $t {
pub fn mul(z: &mut $t, x: &$t, y: &$t) {
unsafe { $mul_fn(z, x, y) }
}
pub fn div(z: &mut $t, x: &$t, y: &$t) {
unsafe { $div_fn(z, x, y) }
}
pub fn inv(y: &mut $t, x: &$t) {
unsafe { $inv_fn(y, x) }
}
pub fn sqr(y: &mut $t, x: &$t) {
unsafe { $sqr_fn(y, x) }
}
}
impl<'a> Mul for &'a $t {
type Output = $t;
fn mul(self, other: &$t) -> $t {
let mut v = unsafe { <$t>::uninit() };
<$t>::mul(&mut v, &self, &other);
v
}
}
impl<'a> MulAssign<&'a $t> for $t {
fn mul_assign(&mut self, other: &$t) {
let z: *mut $t = self;
unsafe {
$mul_fn(z, z as *const $t, other as *const $t);
}
}
}
impl<'a> Div for &'a $t {
type Output = $t;
fn div(self, other: &$t) -> $t {
let mut v = unsafe { <$t>::uninit() };
<$t>::div(&mut v, &self, &other);
v
}
}
impl<'a> DivAssign<&'a $t> for $t {
fn div_assign(&mut self, other: &$t) {
let z: *mut $t = self;
unsafe {
$div_fn(z, z as *const $t, other as *const $t);
}
}
}
};
}
macro_rules! ec_impl {
($t:ty, $dbl_fn:ident, $mul_fn:ident, $normalize_fn:ident, $set_hash_and_map_fn:ident, $mul_vec_fn:ident) => {
impl $t {
pub fn dbl(y: &mut $t, x: &$t) {
unsafe { $dbl_fn(y, x) }
}
pub fn mul(z: &mut $t, x: &$t, y: &mcl_fr) {
unsafe { $mul_fn(z, x, y) }
}
pub fn normalize(y: &mut $t, x: &$t) {
unsafe { $normalize_fn(y, x) }
}
pub fn set_hash_of(&mut self, buf: &[u8]) -> bool {
unsafe { $set_hash_and_map_fn(self, buf.as_ptr(), buf.len()) == 0 }
}
pub fn mul_vec(z: &mut $t, x: &[$t], y: &[mcl_fr]) {
unsafe { $mul_vec_fn(z, x.as_ptr(), y.as_ptr(), x.len()) }
}
}
};
}
#[derive(Default, Debug, Clone, Copy, Eq)]
#[repr(C)]
pub struct mcl_fp {
pub d: [u64; MCLBN_FP_UNIT_SIZE],
}
impl mcl_fp {
pub fn get_order() -> String {
get_field_order()
}
}
common_impl![mcl_fp, mclBnFp_isEqual, mclBnFp_isZero];
is_valid_impl![mcl_fp, mclBnFp_isValid];
serialize_impl![
mcl_fp,
mclBn_getFpByteSize(),
mclBnFp_serialize,
mclBnFp_deserialize
];
str_impl![mcl_fp, 128, mclBnFp_getStr, mclBnFp_setStr];
int_impl![mcl_fp, mclBnFp_setInt32, mclBnFp_isOne];
base_field_impl![
mcl_fp,
mclBnFp_setLittleEndian,
mclBnFp_setLittleEndianMod,
mclBnFp_setHashOf,
mclBnFp_setByCSPRNG,
mclBnFp_isOdd,
mclBnFp_isNegative,
mclBnFp_cmp,
mclBnFp_squareRoot
];
add_op_impl![mcl_fp, mclBnFp_add, mclBnFp_sub, mclBnFp_neg];
field_mul_op_impl![mcl_fp, mclBnFp_mul, mclBnFp_div, mclBnFp_inv, mclBnFp_sqr];
#[derive(Debug, Default, Clone, Copy, Eq)]
#[repr(C)]
pub struct mcl_fp2 {
pub d: [mcl_fp; 2],
}
common_impl![mcl_fp2, mclBnFp2_isEqual, mclBnFp2_isZero];
serialize_impl![
mcl_fp2,
mclBn_getFpByteSize() * 2,
mclBnFp2_serialize,
mclBnFp2_deserialize
];
add_op_impl![mcl_fp2, mclBnFp2_add, mclBnFp2_sub, mclBnFp2_neg];
field_mul_op_impl![
mcl_fp2,
mclBnFp2_mul,
mclBnFp2_div,
mclBnFp2_inv,
mclBnFp2_sqr
];
impl mcl_fp2 {
pub fn square_root(y: &mut mcl_fp2, x: &mcl_fp2) -> bool {
unsafe { mclBnFp2_squareRoot(y, x) == 0 }
}
}
#[derive(Debug, Clone, Copy, Eq, Default)]
#[repr(C)]
pub struct mcl_fr {
pub d: [u64; MCLBN_FR_UNIT_SIZE],
}
impl mcl_fr {
pub fn get_order() -> String {
get_curve_order()
}
}
common_impl![mcl_fr, mclBnFr_isEqual, mclBnFr_isZero];
is_valid_impl![mcl_fr, mclBnFr_isValid];
serialize_impl![
mcl_fr,
mclBn_getFrByteSize(),
mclBnFr_serialize,
mclBnFr_deserialize
];
str_impl![mcl_fr, 128, mclBnFr_getStr, mclBnFr_setStr];
int_impl![mcl_fr, mclBnFr_setInt32, mclBnFr_isOne];
base_field_impl![
mcl_fr,
mclBnFr_setLittleEndian,
mclBnFr_setLittleEndianMod,
mclBnFr_setHashOf,
mclBnFr_setByCSPRNG,
mclBnFr_isOdd,
mclBnFr_isNegative,
mclBnFr_cmp,
mclBnFr_squareRoot
];
add_op_impl![mcl_fr, mclBnFr_add, mclBnFr_sub, mclBnFr_neg];
field_mul_op_impl![mcl_fr, mclBnFr_mul, mclBnFr_div, mclBnFr_inv, mclBnFr_sqr];
#[derive(Debug, Default, Clone, Copy, Eq)]
#[repr(C)]
pub struct mcl_g1 {
pub x: mcl_fp,
pub y: mcl_fp,
pub z: mcl_fp,
}
common_impl![mcl_g1, mclBnG1_isEqual, mclBnG1_isZero];
is_valid_impl![mcl_g1, mclBnG1_isValid];
serialize_impl![
mcl_g1,
mclBn_getFpByteSize(),
mclBnG1_serialize,
mclBnG1_deserialize
];
str_impl![mcl_g1, 128 * 3, mclBnG1_getStr, mclBnG1_setStr];
add_op_impl![mcl_g1, mclBnG1_add, mclBnG1_sub, mclBnG1_neg];
ec_impl![
mcl_g1,
mclBnG1_dbl,
mclBnG1_mul,
mclBnG1_normalize,
mclBnG1_hashAndMapTo,
mclBnG1_mulVec
];
#[derive(Debug, Default, Clone, Copy, Eq)]
#[repr(C)]
pub struct mcl_g2 {
pub x: mcl_fp2,
pub y: mcl_fp2,
pub z: mcl_fp2,
}
common_impl![mcl_g2, mclBnG2_isEqual, mclBnG2_isZero];
is_valid_impl![mcl_g2, mclBnG2_isValid];
serialize_impl![
mcl_g2,
mclBn_getFpByteSize() * 2,
mclBnG2_serialize,
mclBnG2_deserialize
];
str_impl![mcl_g2, 128 * 3 * 2, mclBnG2_getStr, mclBnG2_setStr];
add_op_impl![mcl_g2, mclBnG2_add, mclBnG2_sub, mclBnG2_neg];
ec_impl![
mcl_g2,
mclBnG2_dbl,
mclBnG2_mul,
mclBnG2_normalize,
mclBnG2_hashAndMapTo,
mclBnG2_mulVec
];
#[derive(Default, Debug, Clone)]
#[repr(C)]
pub struct mcl_gt {
d: [mcl_fp; 12],
}
common_impl![mcl_gt, mclBnGT_isEqual, mclBnGT_isZero];
serialize_impl![
mcl_gt,
mclBn_getFpByteSize() * 12,
mclBnGT_serialize,
mclBnGT_deserialize
];
str_impl![mcl_gt, 128 * 12, mclBnGT_getStr, mclBnGT_setStr];
int_impl![mcl_gt, mclBnGT_setInt32, mclBnGT_isOne];
add_op_impl![mcl_gt, mclBnGT_add, mclBnGT_sub, mclBnGT_neg];
field_mul_op_impl![mcl_gt, mclBnGT_mul, mclBnGT_div, mclBnGT_inv, mclBnGT_sqr];
impl mcl_gt {
pub fn pow(z: &mut mcl_gt, x: &mcl_gt, y: &mcl_fr) {
unsafe { mclBnGT_pow(z, x, y) }
}
}
pub fn get_version() -> u32 {
unsafe { mclBn_getVersion() }
}
pub fn init(curve: CurveType) -> bool {
unsafe { mclBn_init(curve as i32, MCLBN_COMPILED_TIME_VAR) == 0 }
}
pub fn get_fr_serialized_size() -> u32 {
unsafe { mclBn_getFrByteSize() }
}
pub fn get_fp_serialized_size() -> u32 {
unsafe { mclBn_getFpByteSize() }
}
pub fn get_g1_serialized_size() -> u32 {
get_fp_serialized_size()
}
pub fn get_g2_serialized_size() -> u32 {
get_fp_serialized_size() * 2
}
pub fn get_gt_serialized_size() -> u32 {
get_fp_serialized_size() * 12
}
macro_rules! get_str_impl {
($get_str_fn:ident) => {{
let u = MaybeUninit::<[u8; 256]>::uninit();
let mut buf = unsafe { u.assume_init() };
let n: usize;
unsafe {
n = $get_str_fn(buf.as_mut_ptr(), buf.len());
}
if n == 0 {
panic!("get_str");
}
unsafe { core::str::from_utf8_unchecked(&buf[0..n]).into() }
}};
}
pub fn get_field_order() -> String {
get_str_impl![mclBn_getFieldOrder]
}
pub fn get_curve_order() -> String {
get_str_impl![mclBn_getCurveOrder]
}
pub fn pairing(z: &mut mcl_gt, x: &mcl_g1, y: &mcl_g2) {
unsafe {
mclBn_pairing(z, x, y);
}
}
pub fn miller_loop(z: &mut mcl_gt, x: &mcl_g1, y: &mcl_g2) {
unsafe {
mclBn_millerLoop(z, x, y);
}
}
pub fn final_exp(y: &mut mcl_gt, x: &mcl_gt) {
unsafe {
mclBn_finalExp(y, x);
}
}
static MCL_INIT: OnceCell<bool> = OnceCell::new();
pub fn try_init_mcl() {
MCL_INIT.get_or_init(|| init(CurveType::BLS12_381));
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/fft_g1.rs | mcl/src/fft_g1.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::{Fr, G1Mul, FFTG1, G1};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
use crate::types::g1::MclG1;
pub fn fft_g1_fast(
ret: &mut [MclG1],
data: &[MclG1],
stride: usize,
roots: &[MclFr],
roots_stride: usize,
) {
let half = ret.len() / 2;
if half > 0 {
#[cfg(feature = "parallel")]
{
let (lo, hi) = ret.split_at_mut(half);
rayon::join(
|| fft_g1_fast(lo, data, stride * 2, roots, roots_stride * 2),
|| fft_g1_fast(hi, &data[stride..], stride * 2, roots, roots_stride * 2),
);
}
#[cfg(not(feature = "parallel"))]
{
fft_g1_fast(&mut ret[..half], data, stride * 2, roots, roots_stride * 2);
fft_g1_fast(
&mut ret[half..],
&data[stride..],
stride * 2,
roots,
roots_stride * 2,
);
}
for i in 0..half {
let y_times_root = ret[i + half].mul(&roots[i * roots_stride]);
ret[i + half] = ret[i].sub(&y_times_root);
ret[i] = ret[i].add_or_dbl(&y_times_root);
}
} else {
ret[0] = data[0];
}
}
impl FFTG1<MclG1> for MclFFTSettings {
fn fft_g1(&self, data: &[MclG1], inverse: bool) -> Result<Vec<MclG1>, String> {
if data.len() > self.max_width {
return Err(String::from(
"Supplied list is longer than the available max width",
));
} else if !data.len().is_power_of_two() {
return Err(String::from("A list with power-of-two length expected"));
}
let stride = self.max_width / data.len();
let mut ret = vec![MclG1::default(); data.len()];
let roots = if inverse {
&self.reverse_roots_of_unity
} else {
&self.roots_of_unity
};
fft_g1_fast(&mut ret, data, 1, roots, stride);
if inverse {
let inv_fr_len = MclFr::from_u64(data.len() as u64).inverse();
ret[..data.len()]
.iter_mut()
.for_each(|f| *f = f.mul(&inv_fr_len));
}
Ok(ret)
}
}
// Used for testing
pub fn fft_g1_slow(
ret: &mut [MclG1],
data: &[MclG1],
stride: usize,
roots: &[MclFr],
roots_stride: usize,
) {
for i in 0..data.len() {
// Evaluate first member at 1
ret[i] = data[0].mul(&roots[0]);
// Evaluate the rest of members using a step of (i * J) % data.len() over the roots
// This distributes the roots over correct x^n members and saves on multiplication
for j in 1..data.len() {
let v = data[j * stride].mul(&roots[((i * j) % data.len()) * roots_stride]);
ret[i] = ret[i].add_or_dbl(&v);
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/kzg10.rs | mcl/src/kzg10.rs | use crate::data_types::{fr::*, g1::*, g2::*, gt::*};
use crate::fk20_fft::{FFTSettings, G1_GENERATOR};
use crate::mcl_methods::{final_exp, mclBn_FrEvaluatePolynomial, pairing};
use kzg::common_utils::{log_2, next_pow_of_2};
use std::{cmp::min, iter, ops};
#[cfg(feature = "parallel")]
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
const G1_GEN_X: &str = "3685416753713387016781088315183077757961620795782546409894578378688607592378376318836054947676345821548104185464507";
const G1_GEN_Y: &str = "1339506544944476473020471379941921221584933875938349620426543736416511423956333506472724655353366534992391756441569";
const G2_GEN_X_D0: &str = "352701069587466618187139116011060144890029952792775240219908644239793785735715026873347600343865175952761926303160";
const G2_GEN_X_D1: &str = "3059144344244213709971259814753781636986470325476647558659373206291635324768958432433509563104347017837885763365758";
const G2_GEN_Y_D0: &str = "1985150602287291935568054521177171638300868978215655730859378665066344726373823718423869104263333984641494340347905";
const G2_GEN_Y_D1: &str = "927553665492332455747201965776037880757740193453592970025027978793976877002675564980949289727957565575433344219582";
impl G1 {
pub fn gen() -> G1 {
let mut g1 = G1::default();
g1.x.set_str(G1_GEN_X, 10);
g1.y.set_str(G1_GEN_Y, 10);
g1.z.set_int(1);
g1
}
pub fn pair(&self, rhs: &G2) -> GT {
let mut gt = GT::default();
pairing(&mut gt, self, rhs);
gt
}
pub fn random() -> G1 {
let fr = Fr::random();
&G1_GENERATOR * &fr
}
}
impl ops::Mul<&Fr> for G1 {
type Output = G1;
fn mul(self, rhs: &Fr) -> Self::Output {
let mut g1 = G1::default();
G1::mul(&mut g1, &self, rhs);
g1
}
}
impl ops::Mul<&Fr> for &G1 {
type Output = G1;
fn mul(self, rhs: &Fr) -> Self::Output {
let mut g1 = G1::default();
G1::mul(&mut g1, self, rhs);
g1
}
}
impl ops::Mul<&Fr> for &mut G1 {
type Output = G1;
fn mul(self, rhs: &Fr) -> Self::Output {
let mut g1 = G1::default();
G1::mul(&mut g1, self, rhs);
g1
}
}
impl ops::Sub<G1> for G1 {
type Output = G1;
fn sub(self, rhs: G1) -> Self::Output {
let mut g1 = G1::default();
G1::sub(&mut g1, &self, &rhs);
g1
}
}
impl GT {
pub fn get_final_exp(&self) -> GT {
let mut gt = GT::default();
final_exp(&mut gt, self);
gt
}
pub fn get_inv(&self) -> GT {
let mut gt = GT::default();
GT::inv(&mut gt, self);
gt
}
}
impl ops::Mul<GT> for GT {
type Output = GT;
fn mul(self, rhs: GT) -> Self::Output {
let mut gt = GT::default();
GT::mul(&mut gt, &self, &rhs);
gt
}
}
impl G2 {
pub fn gen() -> G2 {
let mut g2 = G2::default();
g2.x.d[0].set_str(G2_GEN_X_D0, 10);
g2.x.d[1].set_str(G2_GEN_X_D1, 10);
g2.y.d[0].set_str(G2_GEN_Y_D0, 10);
g2.y.d[1].set_str(G2_GEN_Y_D1, 10);
g2.z.d[0].set_int(1);
g2.z.d[1].clear();
g2
}
}
impl ops::Mul<&Fr> for &G2 {
type Output = G2;
fn mul(self, rhs: &Fr) -> Self::Output {
let mut g2 = G2::default();
G2::mul(&mut g2, self, rhs);
g2
}
}
impl ops::Sub<G2> for G2 {
type Output = G2;
fn sub(self, rhs: G2) -> Self::Output {
let mut g2 = G2::default();
G2::sub(&mut g2, &self, &rhs);
g2
}
}
impl Fr {
pub fn one() -> Fr {
Fr::from_int(1)
}
pub fn get_neg(&self) -> Fr {
let mut fr = Fr::default();
Fr::neg(&mut fr, self);
fr
}
pub fn get_inv(&self) -> Fr {
let mut fr = Fr::default();
Fr::inv(&mut fr, self);
fr
}
pub fn random() -> Fr {
let mut fr = Fr::default();
Fr::set_by_csprng(&mut fr);
fr
}
}
impl ops::Mul<Fr> for Fr {
type Output = Fr;
fn mul(self, rhs: Fr) -> Self::Output {
let mut result = Fr::default();
Fr::mul(&mut result, &self, &rhs);
result
}
}
impl ops::Div<Fr> for Fr {
type Output = Fr;
fn div(self, rhs: Fr) -> Self::Output {
let mut result = Fr::default();
Fr::div(&mut result, &self, &rhs);
result
}
}
impl ops::Sub<Fr> for Fr {
type Output = Fr;
fn sub(self, rhs: Fr) -> Self::Output {
let mut result = Fr::default();
Fr::sub(&mut result, &self, &rhs);
result
}
}
impl ops::Add<Fr> for Fr {
type Output = Fr;
fn add(self, rhs: Fr) -> Self::Output {
let mut result = Fr::default();
Fr::add(&mut result, &self, &rhs);
result
}
}
// KZG 10 Impl
#[derive(Debug, Clone, PartialEq, Default)]
pub struct Polynomial {
pub coeffs: Vec<Fr>,
}
impl Polynomial {
pub fn new(size: usize) -> Self {
Polynomial {
coeffs: vec![Fr::default(); size],
}
}
pub fn from_fr(data: Vec<Fr>) -> Self {
Self { coeffs: data }
}
pub fn from_i32(data: &[i32]) -> Self {
Self {
coeffs: data.iter().map(|x| Fr::from_int(*x)).collect(),
}
}
pub fn order(&self) -> usize {
self.coeffs.len()
}
pub fn eval_at(&self, point: &Fr) -> Fr {
let mut result = Fr::default();
unsafe {
mclBn_FrEvaluatePolynomial(&mut result, self.coeffs.as_ptr(), self.order(), point)
};
result
}
pub fn gen_proof_at(&self, g1_points: &[G1], point: &Fr) -> Result<G1, String> {
let divisor = vec![point.get_neg(), Fr::one()];
let quotient_poly = self.long_division(&divisor).unwrap();
let mut result = G1::default();
g1_linear_combination(
&mut result,
g1_points,
quotient_poly.coeffs.as_slice(),
min(g1_points.len(), quotient_poly.order()),
);
Ok(result)
}
pub fn poly_quotient_length(dividend: &[Fr], divisor: &[Fr]) -> usize {
if dividend.len() >= divisor.len() {
dividend.len() - divisor.len() + 1
} else {
0
}
}
pub fn long_division(&self, divisor: &[Fr]) -> Result<Polynomial, String> {
if divisor.is_empty() {
return Err(String::from("Dividing by zero is undefined"));
}
if divisor.last().unwrap().is_zero() {
return Err(String::from(
"The divisor's highest coefficient must be non-zero",
));
}
let out_length = Polynomial::poly_quotient_length(&self.coeffs, divisor);
if out_length == 0 {
return Ok(Polynomial::default());
}
let mut a_pos = self.order() - 1;
let b_pos = divisor.len() - 1;
let mut diff = a_pos - b_pos;
let mut a = self.coeffs.clone();
let mut out_coeffs = vec![Fr::default(); out_length];
while diff > 0 {
out_coeffs[diff] = a[a_pos] / divisor[b_pos];
for i in 0..b_pos {
// a[diff + i] -= b[i] * quot
let tmp = out_coeffs[diff] * divisor[i];
a[diff + i] = a[diff + i] - tmp;
}
a_pos -= 1;
diff -= 1;
}
out_coeffs[0] = a[a_pos] / divisor[b_pos];
Ok(Polynomial::from_fr(out_coeffs))
}
pub fn fast_div(&self, divisor: &[Fr]) -> Result<Polynomial, String> {
if divisor.is_empty() {
return Err(String::from("Dividing by zero is undefined"));
}
if divisor.last().unwrap().is_zero() {
return Err(String::from(
"The divisor's highest coefficient must be non-zero",
));
}
let mut out_length = Polynomial::poly_quotient_length(&self.coeffs, divisor);
if out_length == 0 {
return Ok(Polynomial::default());
}
// Special case for divisor.length == 1 (it's a constant)
if divisor.len() == 1 {
let mut out_coeffs: Vec<Fr> = vec![];
out_length = self.order();
for i in 0..out_length {
out_coeffs.push(self.coeffs[i] / divisor[0]);
}
return Ok(Polynomial::from_fr(out_coeffs));
}
let a_flip = Polynomial::from_fr(Polynomial::flip_coeffs(&self.coeffs));
let b_flip = Polynomial::from_fr(Polynomial::flip_coeffs(divisor));
let inv_b_flip = b_flip.inverse(out_length).unwrap();
let q_flip = a_flip.mul(&inv_b_flip, out_length).unwrap();
Ok(q_flip.flip())
}
fn normalise_coeffs(coeffs: &[Fr]) -> Vec<Fr> {
let mut ret_length = coeffs.len();
while ret_length > 0 && coeffs[ret_length - 1].is_zero() {
ret_length -= 1;
}
coeffs[0..ret_length].to_vec()
}
fn normalise(&self) -> Polynomial {
Polynomial::from_fr(Polynomial::normalise_coeffs(&self.coeffs))
}
fn flip_coeffs(coeffs: &[Fr]) -> Vec<Fr> {
let mut result: Vec<Fr> = vec![];
for i in (0..coeffs.len()).rev() {
result.push(coeffs[i]);
}
result
}
fn flip(&self) -> Polynomial {
Polynomial::from_fr(Polynomial::flip_coeffs(&self.coeffs))
}
pub fn div(&self, _divisor: &[Fr]) -> Result<Polynomial, String> {
let dividend = self.normalise();
let divisor = Polynomial::normalise_coeffs(_divisor);
if divisor.len() >= dividend.order() || divisor.len() < 128 {
// Tunable paramter
self.long_division(&divisor)
} else {
self.fast_div(&divisor)
}
}
pub fn commit(&self, g1_points: &[G1]) -> Result<G1, String> {
if self.order() > g1_points.len() {
return Err(String::from("Provided polynomial is longer than G1!"));
}
let mut result = G1::default();
g1_linear_combination(
&mut result,
g1_points,
self.coeffs.as_slice(),
min(g1_points.len(), self.order()),
);
Ok(result)
}
pub fn random(order: usize) -> Polynomial {
let coeffs = iter::repeat(0).take(order).map(|_| Fr::random()).collect();
Polynomial { coeffs }
}
pub fn mul_(
&self,
b: &Self,
ft: Option<&FFTSettings>,
len: usize,
) -> Result<Polynomial, String> {
if self.order() < 64 || b.order() < 64 || len < 128 {
// Tunable parameter
Polynomial::mul_direct(self, b, len)
} else {
Polynomial::mul_fft(self, b, ft, len)
}
}
pub fn mul(&self, b: &Self, len: usize) -> Result<Polynomial, String> {
Polynomial::mul_(self, b, None, len)
}
/// @param[in] n_in The number of elements of @p in to take
/// @param[in] n_out The length of @p out
pub fn pad_coeffs(coeffs: &[Fr], n_in: usize, n_out: usize) -> Vec<Fr> {
let num = min(n_in, n_out);
let mut ret_coeffs: Vec<Fr> = vec![];
for item in coeffs.iter().take(num) {
ret_coeffs.push(*item);
}
for _ in num..n_out {
ret_coeffs.push(Fr::zero());
}
ret_coeffs
}
pub fn pad_coeffs_mut(&mut self, n_in: usize, n_out: usize) {
let num = min(n_in, n_out);
self.coeffs = self.coeffs[..num].to_vec();
for _ in num..n_out {
self.coeffs.push(Fr::zero());
}
}
/// @param[in] n_in The number of elements of @p in to take
/// @param[in] n_out The length of @p out
fn pad(&self, n_in: usize, n_out: usize) -> Polynomial {
Polynomial::from_fr(Polynomial::pad_coeffs(&self.coeffs, n_in, n_out))
}
// #[cfg(feature = "parallel")]
pub fn mul_fft(
&self,
b: &Self,
ft: Option<&FFTSettings>,
len: usize,
) -> Result<Polynomial, String> {
// Truncate a and b so as not to do excess work for the number of coefficients required.
let a_len = min(self.order(), len);
let b_len = min(b.order(), len);
let length = next_pow_of_2(a_len + b_len - 1);
//TO DO remove temp_fft, can't find a nice way to declare fft and only use it as ref
let temp_fft = FFTSettings::new(log_2(length) as u8);
let fft_settings = match ft {
Some(x) => x,
None => &temp_fft,
};
let ft = fft_settings;
if length > ft.max_width {
return Err(String::from("Mul fft only good up to length < 32 bits"));
}
let a_pad = self.pad(a_len, length);
let b_pad = b.pad(b_len, length);
let a_fft: Vec<Fr>;
let b_fft: Vec<Fr>;
#[cfg(feature = "parallel")]
{
if length > 1024 {
let mut a_fft_temp = vec![];
let mut b_fft_temp = vec![];
rayon::join(
|| a_fft_temp = ft.fft(&a_pad.coeffs, false).unwrap(),
|| b_fft_temp = ft.fft(&b_pad.coeffs, false).unwrap(),
);
a_fft = a_fft_temp;
b_fft = b_fft_temp;
} else {
a_fft = ft.fft(&a_pad.coeffs, false).unwrap();
b_fft = ft.fft(&b_pad.coeffs, false).unwrap();
}
}
#[cfg(not(feature = "parallel"))]
{
a_fft = ft.fft(&a_pad.coeffs, false).unwrap();
b_fft = ft.fft(&b_pad.coeffs, false).unwrap();
}
let mut ab_fft = a_fft;
for i in 0..length {
ab_fft[i] = ab_fft[i] * b_fft[i];
}
let ab = ft.fft(&ab_fft, true).unwrap();
let mut ret_coeffs: Vec<Fr> = ab;
//pad if too short, else take first len if too long
if len > length {
for _ in length..len {
ret_coeffs.push(Fr::zero());
}
} else {
unsafe {
ret_coeffs.set_len(len);
}
}
Ok(Polynomial::from_fr(ret_coeffs))
}
pub fn mul_direct(&self, b: &Self, len: usize) -> Result<Polynomial, String> {
let mut coeffs: Vec<Fr> = vec![];
for _ in 0..len {
coeffs.push(Fr::zero());
}
for i in 0..self.order() {
let mut j = 0;
while j < b.order() && i + j < len {
let temp = self.coeffs[i] * b.coeffs[j];
coeffs[i + j] = coeffs[i + j] + temp;
j += 1;
}
}
Ok(Polynomial::from_fr(coeffs))
}
pub fn inverse(&self, new_length: usize) -> Result<Polynomial, String> {
let self_length = self.order();
if self_length == 0 || new_length == 0 {
return Ok(Polynomial::default());
}
if self.coeffs[0].is_zero() {
return Err(String::from("The constant term of self must be nonzero."));
}
// If the input polynomial is constant, the remainder of the series is zero
if self_length == 1 {
let mut coeffs = vec![self.coeffs[0].inverse()];
for _ in 1..new_length {
coeffs.push(Fr::zero());
}
return Ok(Polynomial::from_fr(coeffs));
}
let maxd = new_length - 1;
let mut d = 0;
// Max space for multiplications is (2 * length - 1)
//use a more efficent log_2?
let scale = log_2(next_pow_of_2(2 * new_length - 1));
//check if scale actually always fits in u8
//fftsettings to be used, if multiplacation is done with fft
let fs = FFTSettings::new(scale as u8);
let coeffs = vec![self.coeffs[0].inverse()];
let mut out = Polynomial::from_fr(coeffs);
//if new length is 1, max d is 0
let mut mask = 1 << log_2(maxd);
while mask != 0 {
d = 2 * d + ((maxd & mask) != 0) as usize;
mask >>= 1;
// b.c -> tmp0 (we're using out for c)
let temp_0_len = min(d + 1, self.order() + out.order() - 1);
let mut poly_temp_0: Polynomial = self.mul_(&out, Some(&fs), temp_0_len).unwrap();
// 2 - b.c -> tmp0
for i in 0..temp_0_len {
poly_temp_0.coeffs[i] = poly_temp_0.coeffs[i].get_neg();
}
let fr_two = Fr::from_int(2);
poly_temp_0.coeffs[0] = poly_temp_0.coeffs[0] + fr_two;
// c.(2 - b.c) -> tmp1;
let temp_1_len = d + 1;
let poly_temp_1: Polynomial = out.mul_(&poly_temp_0, Some(&fs), temp_1_len).unwrap();
out = Polynomial::from_fr(poly_temp_1.coeffs);
}
if d + 1 != new_length {
return Err(String::from("d + 1 != new_length"));
}
Ok(out)
}
}
#[derive(Debug, Clone)]
pub struct Curve {
pub g1_gen: G1,
pub g2_gen: G2,
pub g1_points: Vec<G1>,
pub g2_points: Vec<G2>,
}
impl Default for Curve {
fn default() -> Self {
let g1_gen = G1::gen();
let g2_gen = G2::gen();
let g1_points: Vec<G1> = vec![];
let g2_points: Vec<G2> = vec![];
Self {
g1_gen,
g2_gen,
g1_points,
g2_points,
}
}
}
impl Curve {
pub fn new(secret: &Fr, order: usize) -> Self {
let g1_gen = G1::gen();
let g2_gen = G2::gen();
let mut g1_points = vec![G1::default(); order];
let mut g2_points = vec![G2::default(); order];
let mut secret_to_power = Fr::one();
for i in 0..order {
G1::mul(&mut (g1_points[i]), &g1_gen, &secret_to_power);
G2::mul(&mut (g2_points[i]), &g2_gen, &secret_to_power);
secret_to_power *= secret;
}
Self {
g1_gen,
g2_gen,
g1_points,
g2_points,
}
}
pub fn new2(secret_g1: &[G1], secret_g2: &[G2], order: usize) -> Self {
let g1_gen = G1::gen();
let g2_gen = G2::gen();
let mut g1_points: Vec<G1> = vec![];
let mut g2_points: Vec<G2> = vec![];
for i in 0..order {
g1_points.push(secret_g1[i]);
g2_points.push(secret_g2[i]);
}
Self {
g1_gen,
g2_gen,
g1_points,
g2_points,
}
}
pub fn is_proof_valid(&self, commitment: &G1, proof: &G1, x: &Fr, y: &Fr) -> bool {
let secret_minus_x = self.g2_points[1] - (&self.g2_gen * x); // g2 * x to get x on g2
let commitment_minus_y = commitment - &(self.g1_gen * y);
Curve::verify_pairing(&commitment_minus_y, &self.g2_gen, proof, &secret_minus_x)
}
#[cfg(not(feature = "parallel"))]
pub fn verify_pairing(a1: &G1, a2: &G2, b1: &G1, b2: &G2) -> bool {
let pairing1 = a1.pair(a2).get_inv();
let pairing2 = b1.pair(b2);
let result = (pairing1 * pairing2).get_final_exp();
result.is_one()
}
#[cfg(feature = "parallel")]
pub fn verify_pairing(a1: &G1, a2: &G2, b1: &G1, b2: &G2) -> bool {
let g1 = [(a1, a2), (b1, b2)];
let mut pairings = g1
.par_iter()
.map(|(v1, v2)| v1.pair(v2))
.collect::<Vec<crate::data_types::gt::GT>>();
let result = (pairings.pop().unwrap() * pairings.pop().unwrap().get_inv()).get_final_exp();
result.is_one()
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/fft_fr.rs | mcl/src/fft_fr.rs | extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::{FFTFr, Fr};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
/// Fast Fourier Transform for finite field elements. Polynomial ret is operated on in reverse order: ret_i * x ^ (len - i - 1)
pub fn fft_fr_fast(
ret: &mut [MclFr],
data: &[MclFr],
stride: usize,
roots: &[MclFr],
roots_stride: usize,
) {
let half: usize = ret.len() / 2;
if half > 0 {
// Recurse
// Offsetting data by stride = 1 on the first iteration forces the even members to the first half
// and the odd members to the second half
#[cfg(not(feature = "parallel"))]
{
fft_fr_fast(&mut ret[..half], data, stride * 2, roots, roots_stride * 2);
fft_fr_fast(
&mut ret[half..],
&data[stride..],
stride * 2,
roots,
roots_stride * 2,
);
}
#[cfg(feature = "parallel")]
{
if half > 256 {
let (lo, hi) = ret.split_at_mut(half);
rayon::join(
|| fft_fr_fast(lo, data, stride * 2, roots, roots_stride * 2),
|| fft_fr_fast(hi, &data[stride..], stride * 2, roots, roots_stride * 2),
);
} else {
fft_fr_fast(&mut ret[..half], data, stride * 2, roots, roots_stride * 2);
fft_fr_fast(
&mut ret[half..],
&data[stride..],
stride * 2,
roots,
roots_stride * 2,
);
}
}
for i in 0..half {
let y_times_root = ret[i + half].mul(&roots[i * roots_stride]);
ret[i + half] = ret[i].sub(&y_times_root);
ret[i] = ret[i].add(&y_times_root);
}
} else {
// When len = 1, return the permuted element
ret[0] = data[0];
}
}
impl MclFFTSettings {
/// Fast Fourier Transform for finite field elements, `output` must be zeroes
pub(crate) fn fft_fr_output(
&self,
data: &[MclFr],
inverse: bool,
output: &mut [MclFr],
) -> Result<(), String> {
if data.len() > self.max_width {
return Err(String::from(
"Supplied list is longer than the available max width",
));
}
if data.len() != output.len() {
return Err(format!(
"Output length {} doesn't match data length {}",
data.len(),
output.len()
));
}
if !data.len().is_power_of_two() {
return Err(String::from("A list with power-of-two length expected"));
}
// In case more roots are provided with fft_settings, use a larger stride
let stride = self.max_width / data.len();
// Inverse is same as regular, but all constants are reversed and results are divided by n
// This is a property of the DFT matrix
let roots = if inverse {
&self.reverse_roots_of_unity
} else {
&self.roots_of_unity
};
fft_fr_fast(output, data, 1, roots, stride);
if inverse {
let inv_fr_len = MclFr::from_u64(data.len() as u64).inverse();
output.iter_mut().for_each(|f| *f = f.mul(&inv_fr_len));
}
Ok(())
}
}
impl FFTFr<MclFr> for MclFFTSettings {
/// Fast Fourier Transform for finite field elements
fn fft_fr(&self, data: &[MclFr], inverse: bool) -> Result<Vec<MclFr>, String> {
let mut ret = vec![MclFr::default(); data.len()];
self.fft_fr_output(data, inverse, &mut ret)?;
Ok(ret)
}
}
/// Simplified Discrete Fourier Transform, mainly used for testing
pub fn fft_fr_slow(
ret: &mut [MclFr],
data: &[MclFr],
stride: usize,
roots: &[MclFr],
roots_stride: usize,
) {
for i in 0..data.len() {
// Evaluate first member at 1
ret[i] = data[0].mul(&roots[0]);
// Evaluate the rest of members using a step of (i * J) % data.len() over the roots
// This distributes the roots over correct x^n members and saves on multiplication
for j in 1..data.len() {
let v = data[j * stride].mul(&roots[((i * j) % data.len()) * roots_stride]);
ret[i] = ret[i].add(&v);
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/recovery.rs | mcl/src/recovery.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use kzg::{FFTFr, Fr, PolyRecover, ZeroPoly};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
use crate::types::poly::MclPoly;
use once_cell::sync::OnceCell;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
const SCALE_FACTOR: u64 = 5;
static INVERSE_FACTORS: OnceCell<Vec<MclFr>> = OnceCell::new();
static UNSCALE_FACTOR_POWERS: OnceCell<Vec<MclFr>> = OnceCell::new();
pub fn scale_poly(p: &mut [MclFr], len_p: usize) {
let factors = INVERSE_FACTORS.get_or_init(|| {
let scale_factor = MclFr::from_u64(SCALE_FACTOR);
let inv_factor = MclFr::inverse(&scale_factor);
let mut temp = Vec::with_capacity(65536);
temp.push(MclFr::one());
for i in 1..65536 {
temp.push(temp[i - 1].mul(&inv_factor));
}
temp
});
p.iter_mut()
.zip(factors)
.take(len_p)
.skip(1)
.for_each(|(p, factor)| {
*p = p.mul(factor);
});
}
pub fn unscale_poly(p: &mut [MclFr], len_p: usize) {
let factors = UNSCALE_FACTOR_POWERS.get_or_init(|| {
let scale_factor = MclFr::from_u64(SCALE_FACTOR);
let mut temp = Vec::with_capacity(65536);
temp.push(MclFr::one());
for i in 1..65536 {
temp.push(temp[i - 1].mul(&scale_factor));
}
temp
});
p.iter_mut()
.zip(factors)
.take(len_p)
.skip(1)
.for_each(|(p, factor)| {
*p = p.mul(factor);
});
}
impl PolyRecover<MclFr, MclPoly, MclFFTSettings> for MclPoly {
fn recover_poly_coeffs_from_samples(
samples: &[Option<MclFr>],
fs: &MclFFTSettings,
) -> Result<Self, String> {
let len_samples = samples.len();
if !len_samples.is_power_of_two() {
return Err(String::from(
"Samples must have a length that is a power of two",
));
}
let mut missing = Vec::with_capacity(len_samples / 2);
for (i, sample) in samples.iter().enumerate() {
if sample.is_none() {
missing.push(i);
}
}
if missing.len() > len_samples / 2 {
return Err(String::from(
"Impossible to recover, too many shards are missing",
));
}
// Calculate `Z_r,I`
let (zero_eval, mut zero_poly) = fs.zero_poly_via_multiplication(len_samples, &missing)?;
// Construct E * Z_r,I: the loop makes the evaluation polynomial
let poly_evaluations_with_zero = samples
.iter()
.zip(zero_eval)
.map(|(maybe_sample, zero_eval)| {
debug_assert_eq!(maybe_sample.is_none(), zero_eval.is_zero());
match maybe_sample {
Some(sample) => sample.mul(&zero_eval),
None => MclFr::zero(),
}
})
.collect::<Vec<_>>();
// Now inverse FFT so that poly_with_zero is (E * Z_r,I)(x) = (D * Z_r,I)(x)
let mut poly_with_zero = fs.fft_fr(&poly_evaluations_with_zero, true).unwrap();
drop(poly_evaluations_with_zero);
// x -> k * x
let len_zero_poly = zero_poly.coeffs.len();
scale_poly(&mut poly_with_zero, len_samples);
scale_poly(&mut zero_poly.coeffs, len_zero_poly);
// Q1 = (D * Z_r,I)(k * x)
let scaled_poly_with_zero = poly_with_zero;
// Q2 = Z_r,I(k * x)
let scaled_zero_poly = zero_poly.coeffs;
// Polynomial division by convolution: Q3 = Q1 / Q2
#[cfg(feature = "parallel")]
let (eval_scaled_poly_with_zero, eval_scaled_zero_poly) = {
if len_zero_poly - 1 > 1024 {
rayon::join(
|| fs.fft_fr(&scaled_poly_with_zero, false).unwrap(),
|| fs.fft_fr(&scaled_zero_poly, false).unwrap(),
)
} else {
(
fs.fft_fr(&scaled_poly_with_zero, false).unwrap(),
fs.fft_fr(&scaled_zero_poly, false).unwrap(),
)
}
};
#[cfg(not(feature = "parallel"))]
let (eval_scaled_poly_with_zero, eval_scaled_zero_poly) = {
(
fs.fft_fr(&scaled_poly_with_zero, false).unwrap(),
fs.fft_fr(&scaled_zero_poly, false).unwrap(),
)
};
drop(scaled_zero_poly);
let mut eval_scaled_reconstructed_poly = eval_scaled_poly_with_zero;
#[cfg(not(feature = "parallel"))]
let eval_scaled_reconstructed_poly_iter = eval_scaled_reconstructed_poly.iter_mut();
#[cfg(feature = "parallel")]
let eval_scaled_reconstructed_poly_iter = eval_scaled_reconstructed_poly.par_iter_mut();
eval_scaled_reconstructed_poly_iter
.zip(eval_scaled_zero_poly)
.for_each(
|(eval_scaled_reconstructed_poly, eval_scaled_poly_with_zero)| {
*eval_scaled_reconstructed_poly = eval_scaled_reconstructed_poly
.div(&eval_scaled_poly_with_zero)
.unwrap();
},
);
// The result of the division is D(k * x):
let mut scaled_reconstructed_poly =
fs.fft_fr(&eval_scaled_reconstructed_poly, true).unwrap();
drop(eval_scaled_reconstructed_poly);
// k * x -> x
unscale_poly(&mut scaled_reconstructed_poly, len_samples);
// Finally we have D(x) which evaluates to our original data at the powers of roots of unity
Ok(Self {
coeffs: scaled_reconstructed_poly,
})
}
fn recover_poly_from_samples(
samples: &[Option<MclFr>],
fs: &MclFFTSettings,
) -> Result<Self, String> {
let reconstructed_poly = Self::recover_poly_coeffs_from_samples(samples, fs)?;
// The evaluation polynomial for D(x) is the reconstructed data:
let reconstructed_data = fs.fft_fr(&reconstructed_poly.coeffs, false).unwrap();
// Check all is well
samples
.iter()
.zip(&reconstructed_data)
.for_each(|(sample, reconstructed_data)| {
debug_assert!(sample.is_none() || reconstructed_data.equals(&sample.unwrap()));
});
Ok(Self {
coeffs: reconstructed_data,
})
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/fk20_matrix.rs | mcl/src/fk20_matrix.rs | use crate::data_types::fr::Fr;
use crate::data_types::g1::G1;
use crate::fk20_fft::*;
use crate::kzg10::*;
use crate::kzg_settings::KZGSettings;
use std::iter;
use kzg::common_utils::is_power_of_2;
use kzg::common_utils::reverse_bit_order;
#[cfg(feature = "parallel")]
use rayon::prelude::*;
impl FFTSettings {
pub fn toeplitz_part_1(&self, x: &[G1]) -> Result<Vec<G1>, String> {
let n = x.len();
// extend x with zeroes
let tail = vec![G1::zero(); n];
let x_ext: Vec<G1> = x.iter().cloned().chain(tail).collect();
self.fft_g1(&x_ext)
}
pub fn toeplitz_part_2(&self, coeffs: &[Fr], x_ext_fft: &[G1]) -> Result<Vec<G1>, String> {
let toeplitz_coeffs_fft = self.fft(coeffs, false).unwrap();
#[cfg(feature = "parallel")]
{
let ret: Vec<_> = (0..coeffs.len())
.into_par_iter()
.map(|i| x_ext_fft[i] * &toeplitz_coeffs_fft[i])
.collect();
Ok(ret)
}
#[cfg(not(feature = "parallel"))]
{
let mut ret = Vec::new();
for i in 0..coeffs.len() {
ret.push(x_ext_fft[i] * &toeplitz_coeffs_fft[i]);
}
Ok(ret)
}
}
pub fn toeplitz_part_3(&self, h_ext_fft: &[G1]) -> Result<Vec<G1>, String> {
let n2 = h_ext_fft.len();
let n = n2 / 2;
let mut ret = self.fft_g1_inv(h_ext_fft).unwrap();
for item in ret.iter_mut().take(n2).skip(n) {
*item = G1::G1_IDENTITY;
}
Ok(ret)
}
}
#[derive(Debug, Clone, Default)]
pub struct FK20SingleMatrix {
pub x_ext_fft: Vec<G1>,
pub kzg_settings: KZGSettings,
}
impl FK20SingleMatrix {
pub fn new(kzg_settings: &KZGSettings, n2: usize) -> Result<Self, String> {
let n = n2 >> 1; // div by 2
if !is_power_of_2(n2) {
return Err(String::from("n2 must be a power of two"));
}
if n2 < 2 {
return Err(String::from("n2 must be greater than or equal to 2"));
}
if n2 > kzg_settings.fft_settings.max_width {
return Err(String::from(
"n2 must be less than or equal to fft settings max width",
));
}
let mut x = Vec::new();
for i in 0..n - 1 {
x.push(kzg_settings.curve.g1_points[n - 2 - i]);
}
x.push(G1::G1_IDENTITY);
let x_ext_fft = kzg_settings.fft_settings.toeplitz_part_1(&x).unwrap();
let kzg_settings = kzg_settings.clone();
Ok(Self {
kzg_settings,
x_ext_fft,
})
}
pub fn dau_using_fk20_single(&self, polynomial: &Polynomial) -> Result<Vec<G1>, String> {
let n = polynomial.order();
let n2 = n << 1;
if !is_power_of_2(n2) {
return Err(String::from("n2 must be a power of two"));
}
if n2 > self.kzg_settings.fft_settings.max_width {
return Err(String::from(
"n2 must be less than or equal to fft settings max width",
));
}
let mut proofs = self.fk20_single_dao_optimized(polynomial).unwrap();
reverse_bit_order(&mut proofs)?;
Ok(proofs)
}
pub fn fk20_single_dao_optimized(&self, polynomial: &Polynomial) -> Result<Vec<G1>, String> {
let n = polynomial.order();
let n2 = n * 2;
if !is_power_of_2(n2) {
return Err(String::from("n2 must be a power of two"));
}
if n2 > self.kzg_settings.fft_settings.max_width {
return Err(String::from(
"n2 must be less than or equal to fft settings max width",
));
}
let toeplitz_coeffs = polynomial.toeplitz_coeffs_step_strided(0, 1);
let h_ext_fft = self
.kzg_settings
.fft_settings
.toeplitz_part_2(&toeplitz_coeffs, &self.x_ext_fft)
.unwrap();
let h = self
.kzg_settings
.fft_settings
.toeplitz_part_3(&h_ext_fft)
.unwrap();
self.kzg_settings.fft_settings.fft_g1(&h)
}
}
#[derive(Debug, Clone)]
pub struct FK20Matrix {
pub x_ext_fft_files: Vec<Vec<G1>>,
pub chunk_len: usize,
pub kzg_settings: KZGSettings,
}
impl Default for FK20Matrix {
fn default() -> Self {
Self {
kzg_settings: KZGSettings::default(),
chunk_len: 1,
x_ext_fft_files: vec![],
}
}
}
impl FK20Matrix {
pub fn new(kzg_settings: &KZGSettings, n2: usize, chunk_len: usize) -> Result<Self, String> {
let n = n2 >> 1; // div by 2
let k = n / chunk_len;
if !is_power_of_2(n2) {
return Err(String::from("n2 must be a power of two"));
}
if !is_power_of_2(chunk_len) {
return Err(String::from("chunk_len must be a power of two"));
}
if n2 < 2 {
return Err(String::from("n2 must be greater than or equal to 2"));
}
if n2 > kzg_settings.fft_settings.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
}
if n2 > kzg_settings.fft_settings.max_width {
return Err(String::from(
"n2 must be less than or equal to fft settings max width",
));
}
if chunk_len > n2 / 2 {
return Err(String::from("chunk_len must be greater or equal to n2 / 2"));
}
let mut x_ext_fft_files: Vec<Vec<G1>> = vec![vec![]; chunk_len];
for (i, item) in x_ext_fft_files.iter_mut().enumerate().take(chunk_len) {
*item = FK20Matrix::x_ext_fft_precompute(
&kzg_settings.fft_settings,
&kzg_settings.curve,
n,
k,
chunk_len,
i,
)
.unwrap();
}
Ok(FK20Matrix {
x_ext_fft_files,
chunk_len,
kzg_settings: kzg_settings.clone(),
})
}
#[allow(clippy::many_single_char_names)]
fn x_ext_fft_precompute(
fft_settings: &FFTSettings,
curve: &Curve,
n: usize,
k: usize,
chunk_len: usize,
offset: usize,
) -> Result<Vec<G1>, String> {
let mut x: Vec<G1> = vec![G1::default(); k];
let mut start = 0;
let temp = chunk_len + 1 + offset;
if n >= temp {
start = n - temp;
}
let mut i = 0;
let mut j = start + chunk_len;
while i + 1 < k {
// hack to remove overflow checking,
// could just move this to the bottom and define j as start, but then need to check for overflows
// basically last j -= chunk_len overflows, but it's not used to access the array, as the i + 1 < k is false
j -= chunk_len;
x[i] = curve.g1_points[j];
i += 1;
}
x[k - 1] = G1::zero();
fft_settings.toeplitz_part_1(&x)
}
pub fn dau_using_fk20_multi(&self, polynomial: &Polynomial) -> Result<Vec<G1>, String> {
let n = polynomial.order();
let n2 = n << 1;
if !is_power_of_2(n2) {
return Err(String::from("n2 must be a power of two"));
}
if n2 > self.kzg_settings.fft_settings.max_width {
return Err(String::from(
"n2 must be less than or equal to fft settings max width",
));
}
let extended_poly = polynomial.get_extended(n2);
let mut proofs = self.fk20_multi_dao_optimized(&extended_poly).unwrap();
reverse_bit_order(&mut proofs)?;
Ok(proofs)
}
pub fn fk20_multi_dao_optimized(&self, polynomial: &Polynomial) -> Result<Vec<G1>, String> {
let n = polynomial.order() >> 1;
let k = n / self.chunk_len;
let k2 = k << 1;
let n2 = n << 1;
if !is_power_of_2(n2) {
return Err(String::from("n2 must be a power of two"));
}
if n2 > self.kzg_settings.fft_settings.max_width {
return Err(String::from(
"n2 must be less than or equal to fft settings max width",
));
}
let mut h_ext_fft = vec![G1::zero(); k2];
// TODO: this operates on an extended poly, but doesn't use the extended values?
// literally just using the poly without the zero trailing tail, makes more sense to take it in as a param, or use without the tail;
let reduced_poly = Polynomial::from_fr(polynomial.coeffs.iter().copied().take(n).collect());
for i in 0..self.chunk_len {
let toeplitz_coeffs = reduced_poly.toeplitz_coeffs_step_strided(i, self.chunk_len);
let h_ext_fft_file = self
.kzg_settings
.fft_settings
.toeplitz_part_2(&toeplitz_coeffs, &self.x_ext_fft_files[i])
.unwrap();
for j in 0..k2 {
let tmp = &h_ext_fft[j] + &h_ext_fft_file[j];
h_ext_fft[j] = tmp;
}
}
let tail = iter::repeat(G1::zero()).take(k);
let h: Vec<G1> = self
.kzg_settings
.fft_settings
.toeplitz_part_3(&h_ext_fft)
.unwrap()
.into_iter()
.take(k)
.chain(tail)
.collect();
self.kzg_settings.fft_settings.fft_g1(&h)
}
}
impl Polynomial {
pub fn extend(vec: &[Fr], size: usize) -> Vec<Fr> {
if size < vec.len() {
return vec.to_owned();
}
let to_pad = size - vec.len();
let tail = iter::repeat(Fr::zero()).take(to_pad);
let result: Vec<Fr> = vec.iter().copied().chain(tail).collect();
result
}
pub fn get_extended(&self, size: usize) -> Polynomial {
Polynomial::from_fr(Polynomial::extend(&self.coeffs, size))
}
fn toeplitz_coeffs_step_strided(&self, offset: usize, stride: usize) -> Vec<Fr> {
let n = self.order();
let k = n / stride;
let k2 = k << 1;
// [last] + [0]*(n+1) + [1 .. n-2]
let mut toeplitz_coeffs = vec![Fr::zero(); k2];
toeplitz_coeffs[0] = self.coeffs[n - 1 - offset];
let mut j = (stride << 1) - offset - 1;
for item in toeplitz_coeffs.iter_mut().take(k2).skip(k + 2) {
*item = self.coeffs[j];
j += stride;
}
toeplitz_coeffs
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/fr.rs | mcl/src/types/fr.rs | extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use arbitrary::Arbitrary;
use blst::blst_fr;
use blst::blst_fr_from_uint64;
use blst::blst_scalar;
use blst::blst_scalar_from_fr;
use blst::blst_uint64_from_fr;
use crate::mcl_methods::mcl_fr;
use crate::mcl_methods::try_init_mcl;
use kzg::eip_4844::BYTES_PER_FIELD_ELEMENT;
use kzg::Fr;
use kzg::Scalar256;
#[repr(C)]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub struct MclFr(pub mcl_fr);
impl<'a> Arbitrary<'a> for MclFr {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let val: [u8; 32] = u.arbitrary()?;
Ok(Self::from_bytes_unchecked(&val).unwrap())
}
}
impl Fr for MclFr {
fn null() -> Self {
try_init_mcl();
Self::from_u64_arr(&[u64::MAX, u64::MAX, u64::MAX, u64::MAX])
}
fn zero() -> Self {
try_init_mcl();
Self::from_u64(0)
}
fn one() -> Self {
try_init_mcl();
Self::from_u64(1)
}
#[cfg(feature = "rand")]
fn rand() -> Self {
try_init_mcl();
let val: [u64; 4] = [
rand::random(),
rand::random(),
rand::random(),
rand::random(),
];
let ret = Self::default();
let mut blst = MclFr::to_blst_fr(&ret);
unsafe {
blst_fr_from_uint64(&mut blst, val.as_ptr());
}
MclFr::from_blst_fr(blst)
}
fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
bytes
.try_into()
.map_err(|_| {
format!(
"Invalid byte length. Expected {}, got {}",
BYTES_PER_FIELD_ELEMENT,
bytes.len()
)
})
.and_then(|bytes: &[u8; BYTES_PER_FIELD_ELEMENT]| {
let mut bls_scalar = blst_scalar::default();
let mut fr = blst_fr::default();
unsafe {
blst::blst_scalar_from_bendian(&mut bls_scalar, bytes.as_ptr());
if !blst::blst_scalar_fr_check(&bls_scalar) {
return Err("Invalid scalar".to_string());
}
blst::blst_fr_from_scalar(&mut fr, &bls_scalar);
}
Ok(Self(mcl_fr { d: fr.l }))
})
}
fn from_bytes_unchecked(bytes: &[u8]) -> Result<Self, String> {
bytes
.try_into()
.map_err(|_| {
format!(
"Invalid byte length. Expected {}, got {}",
BYTES_PER_FIELD_ELEMENT,
bytes.len()
)
})
.map(|bytes: &[u8; BYTES_PER_FIELD_ELEMENT]| {
let mut bls_scalar = blst_scalar::default();
let mut fr = blst_fr::default();
unsafe {
blst::blst_scalar_from_bendian(&mut bls_scalar, bytes.as_ptr());
blst::blst_fr_from_scalar(&mut fr, &bls_scalar);
}
Self(mcl_fr { d: fr.l })
})
}
fn from_hex(hex: &str) -> Result<Self, String> {
let bytes = hex::decode(&hex[2..]).unwrap();
Self::from_bytes(&bytes)
}
fn from_u64_arr(val: &[u64; 4]) -> Self {
try_init_mcl();
let ret = Self::default();
let mut blst = MclFr::to_blst_fr(&ret);
unsafe {
blst_fr_from_uint64(&mut blst, val.as_ptr());
}
MclFr::from_blst_fr(blst)
}
fn from_u64(val: u64) -> Self {
try_init_mcl();
Self::from_u64_arr(&[val, 0, 0, 0])
}
fn to_bytes(&self) -> [u8; 32] {
try_init_mcl();
let mut scalar = blst_scalar::default();
let mut bytes = [0u8; 32];
unsafe {
blst_scalar_from_fr(&mut scalar, &self.to_blst_fr());
blst::blst_bendian_from_scalar(bytes.as_mut_ptr(), &scalar);
}
bytes
}
fn to_u64_arr(&self) -> [u64; 4] {
try_init_mcl();
let blst = self.to_blst_fr();
let mut val: [u64; 4] = [0; 4];
unsafe {
blst_uint64_from_fr(val.as_mut_ptr(), &blst);
}
val
}
fn is_one(&self) -> bool {
try_init_mcl();
self.0.is_one()
}
fn is_zero(&self) -> bool {
try_init_mcl();
self.0.is_zero()
}
fn is_null(&self) -> bool {
try_init_mcl();
try_init_mcl();
let n = Self::null();
self.0.eq(&n.0)
}
fn sqr(&self) -> Self {
try_init_mcl();
let mut ret = Self::default();
mcl_fr::sqr(&mut ret.0, &self.0);
ret
}
fn mul(&self, b: &Self) -> Self {
try_init_mcl();
let mut ret = Self::default();
mcl_fr::mul(&mut ret.0, &self.0, &b.0);
ret
}
fn add(&self, b: &Self) -> Self {
try_init_mcl();
let mut ret = Self::default();
mcl_fr::add(&mut ret.0, &self.0, &b.0);
ret
}
fn sub(&self, b: &Self) -> Self {
try_init_mcl();
let mut ret = Self::default();
mcl_fr::sub(&mut ret.0, &self.0, &b.0);
ret
}
fn eucl_inverse(&self) -> Self {
try_init_mcl();
let mut ret = Self::default();
mcl_fr::inv(&mut ret.0, &self.0);
ret
}
fn negate(&self) -> Self {
try_init_mcl();
let mut ret = Self::default();
mcl_fr::neg(&mut ret.0, &self.0);
ret
}
fn inverse(&self) -> Self {
try_init_mcl();
let mut ret = Self::default();
mcl_fr::inv(&mut ret.0, &self.0);
ret
}
fn pow(&self, n: usize) -> Self {
try_init_mcl();
let mut out = Self::one();
let mut temp = *self;
let mut n = n;
loop {
if (n & 1) == 1 {
out = out.mul(&temp);
}
n >>= 1;
if n == 0 {
break;
}
temp = temp.sqr();
}
out
}
fn div(&self, b: &Self) -> Result<Self, String> {
try_init_mcl();
if b.is_zero() {
return Ok(*b);
}
let tmp = b.eucl_inverse();
let out = self.mul(&tmp);
Ok(out)
}
fn equals(&self, b: &Self) -> bool {
try_init_mcl();
mcl_fr::eq(&self.0, &b.0)
}
fn to_scalar(&self) -> Scalar256 {
try_init_mcl();
let blst = self.to_blst_fr();
let mut blst_scalar = blst_scalar::default();
unsafe {
blst_scalar_from_fr(&mut blst_scalar, &blst);
}
Scalar256::from_u8(&blst_scalar.b)
}
}
impl MclFr {
pub fn from_blst_fr(fr: blst_fr) -> Self {
try_init_mcl();
Self(mcl_fr { d: fr.l })
}
pub fn to_blst_fr(&self) -> blst_fr {
try_init_mcl();
blst_fr { l: self.0.d }
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/fk20_single_settings.rs | mcl/src/types/fk20_single_settings.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use kzg::common_utils::reverse_bit_order;
use kzg::{FK20SingleSettings, Poly, FFTG1, G1};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
use crate::types::g1::MclG1;
use crate::types::g2::MclG2;
use crate::types::kzg_settings::MclKZGSettings;
use crate::types::poly::MclPoly;
use super::fp::MclFp;
use super::g1::{MclG1Affine, MclG1ProjAddAffine};
#[derive(Debug, Clone, Default)]
pub struct MclFK20SingleSettings {
pub kzg_settings: MclKZGSettings,
pub x_ext_fft: Vec<MclG1>,
}
impl
FK20SingleSettings<
MclFr,
MclG1,
MclG2,
MclFFTSettings,
MclPoly,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
> for MclFK20SingleSettings
{
fn new(kzg_settings: &MclKZGSettings, n2: usize) -> Result<Self, String> {
let n = n2 / 2;
if n2 > kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
} else if n2 < 2 {
return Err(String::from("n2 must be greater than or equal to 2"));
}
let mut x = Vec::with_capacity(n);
for i in 0..n - 1 {
x.push(kzg_settings.g1_values_monomial[n - 2 - i]);
}
x.push(MclG1::identity());
let x_ext_fft = kzg_settings.fs.toeplitz_part_1(&x);
drop(x);
let kzg_settings = kzg_settings.clone();
let ret = Self {
kzg_settings,
x_ext_fft,
};
Ok(ret)
}
fn data_availability(&self, p: &MclPoly) -> Result<Vec<MclG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
}
let mut ret = self.data_availability_optimized(p).unwrap();
reverse_bit_order(&mut ret)?;
Ok(ret)
}
fn data_availability_optimized(&self, p: &MclPoly) -> Result<Vec<MclG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
}
let toeplitz_coeffs = p.toeplitz_coeffs_step();
let h_ext_fft = self
.kzg_settings
.fs
.toeplitz_part_2(&toeplitz_coeffs, &self.x_ext_fft);
let h = self.kzg_settings.fs.toeplitz_part_3(&h_ext_fft);
let ret = self.kzg_settings.fs.fft_g1(&h, false).unwrap();
Ok(ret)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/kzg_settings.rs | mcl/src/types/kzg_settings.rs | extern crate alloc;
use alloc::string::{String, ToString};
use alloc::sync::Arc;
use alloc::{vec, vec::Vec};
use kzg::eth::c_bindings::CKZGSettings;
use kzg::eth::{self, FIELD_ELEMENTS_PER_EXT_BLOB};
use kzg::msm::precompute::{precompute, PrecomputationTable};
use kzg::{FFTFr, FFTSettings, Fr, G1Mul, G2Mul, KZGSettings, Poly, G1, G2};
use crate::consts::{G1_GENERATOR, G2_GENERATOR};
use crate::fft_g1::fft_g1_fast;
use crate::kzg_proofs::{g1_linear_combination, pairings_verify};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
use crate::types::g1::MclG1;
use crate::types::g2::MclG2;
use crate::types::poly::MclPoly;
use crate::utils::PRECOMPUTATION_TABLES;
use super::fp::MclFp;
use super::g1::{MclG1Affine, MclG1ProjAddAffine};
#[derive(Debug, Clone, Default)]
#[allow(clippy::type_complexity)]
pub struct MclKZGSettings {
pub fs: MclFFTSettings,
pub g1_values_monomial: Vec<MclG1>,
pub g1_values_lagrange_brp: Vec<MclG1>,
pub g2_values_monomial: Vec<MclG2>,
pub precomputation:
Option<Arc<PrecomputationTable<MclFr, MclG1, MclFp, MclG1Affine, MclG1ProjAddAffine>>>,
pub x_ext_fft_columns: Vec<Vec<MclG1>>,
pub cell_size: usize,
}
fn toeplitz_part_1(
field_elements_per_ext_blob: usize,
output: &mut [MclG1],
x: &[MclG1],
s: &MclFFTSettings,
) -> Result<(), String> {
let n = x.len();
let n2 = n * 2;
let mut x_ext = vec![MclG1::identity(); n2];
x_ext[..n].copy_from_slice(x);
let x_ext = &x_ext[..];
/* Ensure the length is valid */
if x_ext.len() > field_elements_per_ext_blob || !x_ext.len().is_power_of_two() {
return Err("Invalid input size".to_string());
}
let roots_stride = field_elements_per_ext_blob / x_ext.len();
fft_g1_fast(output, x_ext, 1, &s.roots_of_unity, roots_stride);
Ok(())
}
impl
KZGSettings<
MclFr,
MclG1,
MclG2,
MclFFTSettings,
MclPoly,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
> for MclKZGSettings
{
fn new(
g1_monomial: &[MclG1],
g1_lagrange_brp: &[MclG1],
g2_monomial: &[MclG2],
fft_settings: &MclFFTSettings,
cell_size: usize,
) -> Result<Self, String> {
if g1_monomial.len() != g1_lagrange_brp.len() {
return Err("G1 point length mismatch".to_string());
}
let field_elements_per_blob = g1_monomial.len();
let field_elements_per_ext_blob = field_elements_per_blob * 2;
let n = field_elements_per_ext_blob / 2;
let k = n / cell_size;
let k2 = 2 * k;
let mut points = vec![MclG1::default(); k2];
let mut x = vec![MclG1::default(); k];
let mut x_ext_fft_columns = vec![vec![MclG1::default(); cell_size]; k2];
for offset in 0..cell_size {
let start = n - cell_size - 1 - offset;
for (i, p) in x.iter_mut().enumerate().take(k - 1) {
let j = start - i * cell_size;
*p = g1_monomial[j];
}
x[k - 1] = MclG1::identity();
toeplitz_part_1(field_elements_per_ext_blob, &mut points, &x, fft_settings)?;
for row in 0..k2 {
x_ext_fft_columns[row][offset] = points[row];
}
}
Ok(Self {
g1_values_monomial: g1_monomial.to_vec(),
g1_values_lagrange_brp: g1_lagrange_brp.to_vec(),
g2_values_monomial: g2_monomial.to_vec(),
fs: fft_settings.clone(),
precomputation: {
precompute(g1_lagrange_brp, &x_ext_fft_columns)
.ok()
.flatten()
.map(Arc::new)
},
x_ext_fft_columns,
cell_size,
})
}
fn commit_to_poly(&self, poly: &MclPoly) -> Result<MclG1, String> {
if poly.coeffs.len() > self.g1_values_monomial.len() {
return Err(String::from("Polynomial is longer than secret g1"));
}
let mut out = MclG1::default();
g1_linear_combination(
&mut out,
&self.g1_values_monomial,
&poly.coeffs,
poly.coeffs.len(),
None,
);
Ok(out)
}
fn compute_proof_single(&self, p: &MclPoly, x: &MclFr) -> Result<MclG1, String> {
if p.coeffs.is_empty() {
return Err(String::from("Polynomial must not be empty"));
}
// `-(x0^n)`, where `n` is `1`
let divisor_0 = x.negate();
// Calculate `q = p / (x^n - x0^n)` for our reduced case (see `compute_proof_multi` for
// generic implementation)
let mut out_coeffs = Vec::from(&p.coeffs[1..]);
for i in (1..out_coeffs.len()).rev() {
let tmp = out_coeffs[i].mul(&divisor_0);
out_coeffs[i - 1] = out_coeffs[i - 1].sub(&tmp);
}
let q = MclPoly { coeffs: out_coeffs };
let ret = self.commit_to_poly(&q)?;
Ok(ret)
}
fn check_proof_single(
&self,
com: &MclG1,
proof: &MclG1,
x: &MclFr,
y: &MclFr,
) -> Result<bool, String> {
let x_g2: MclG2 = G2_GENERATOR.mul(x);
let s_minus_x: MclG2 = self.g2_values_monomial[1].sub(&x_g2);
let y_g1 = G1_GENERATOR.mul(y);
let commitment_minus_y: MclG1 = com.sub(&y_g1);
Ok(pairings_verify(
&commitment_minus_y,
&G2_GENERATOR,
proof,
&s_minus_x,
))
}
fn compute_proof_multi(&self, p: &MclPoly, x0: &MclFr, n: usize) -> Result<MclG1, String> {
if p.coeffs.is_empty() {
return Err(String::from("Polynomial must not be empty"));
}
if !n.is_power_of_two() {
return Err(String::from("n must be a power of two"));
}
// Construct x^n - x0^n = (x - x0.w^0)(x - x0.w^1)...(x - x0.w^(n-1))
let mut divisor = MclPoly {
coeffs: Vec::with_capacity(n + 1),
};
// -(x0^n)
let x_pow_n = x0.pow(n);
divisor.coeffs.push(x_pow_n.negate());
// Zeros
for _ in 1..n {
divisor.coeffs.push(Fr::zero());
}
// x^n
divisor.coeffs.push(Fr::one());
let mut new_polina = p.clone();
// Calculate q = p / (x^n - x0^n)
// let q = p.div(&divisor).unwrap();
let q = new_polina.div(&divisor)?;
let ret = self.commit_to_poly(&q)?;
Ok(ret)
}
fn check_proof_multi(
&self,
com: &MclG1,
proof: &MclG1,
x: &MclFr,
ys: &[MclFr],
n: usize,
) -> Result<bool, String> {
if !n.is_power_of_two() {
return Err(String::from("n is not a power of two"));
}
// Interpolate at a coset.
let mut interp = MclPoly {
coeffs: self.fs.fft_fr(ys, true)?,
};
let inv_x = x.inverse(); // Not euclidean?
let mut inv_x_pow = inv_x;
for i in 1..n {
interp.coeffs[i] = interp.coeffs[i].mul(&inv_x_pow);
inv_x_pow = inv_x_pow.mul(&inv_x);
}
// [x^n]_2
let x_pow = inv_x_pow.inverse();
let xn2 = G2_GENERATOR.mul(&x_pow);
// [s^n - x^n]_2
let xn_minus_yn = self.g2_values_monomial[n].sub(&xn2);
// [interpolation_polynomial(s)]_1
let is1 = self.commit_to_poly(&interp).unwrap();
// [commitment - interpolation_polynomial(s)]_1 = [commit]_1 - [interpolation_polynomial(s)]_1
let commit_minus_interp = com.sub(&is1);
let ret = pairings_verify(&commit_minus_interp, &G2_GENERATOR, proof, &xn_minus_yn);
Ok(ret)
}
fn get_roots_of_unity_at(&self, i: usize) -> MclFr {
self.fs.get_roots_of_unity_at(i)
}
fn get_fft_settings(&self) -> &MclFFTSettings {
&self.fs
}
fn get_g1_lagrange_brp(&self) -> &[MclG1] {
&self.g1_values_lagrange_brp
}
fn get_g1_monomial(&self) -> &[MclG1] {
&self.g1_values_monomial
}
fn get_g2_monomial(&self) -> &[MclG2] {
&self.g2_values_monomial
}
fn get_precomputation(
&self,
) -> Option<&PrecomputationTable<MclFr, MclG1, MclFp, MclG1Affine, MclG1ProjAddAffine>> {
self.precomputation.as_ref().map(|v| v.as_ref())
}
fn get_x_ext_fft_columns(&self) -> &[Vec<MclG1>] {
&self.x_ext_fft_columns
}
fn get_cell_size(&self) -> usize {
self.cell_size
}
}
impl<'a> TryFrom<&'a CKZGSettings> for MclKZGSettings {
type Error = String;
fn try_from(settings: &'a CKZGSettings) -> Result<Self, Self::Error> {
let roots_of_unity = unsafe {
core::slice::from_raw_parts(settings.roots_of_unity, FIELD_ELEMENTS_PER_EXT_BLOB + 1)
.iter()
.map(|r| MclFr::from_blst_fr(blst::blst_fr { l: r.l }))
.collect::<Vec<MclFr>>()
};
let brp_roots_of_unity = unsafe {
core::slice::from_raw_parts(settings.brp_roots_of_unity, FIELD_ELEMENTS_PER_EXT_BLOB)
.iter()
.map(|r| MclFr::from_blst_fr(blst::blst_fr { l: r.l }))
.collect::<Vec<MclFr>>()
};
let reverse_roots_of_unity = unsafe {
core::slice::from_raw_parts(
settings.reverse_roots_of_unity,
FIELD_ELEMENTS_PER_EXT_BLOB + 1,
)
.iter()
.map(|r| MclFr::from_blst_fr(blst::blst_fr { l: r.l }))
.collect::<Vec<MclFr>>()
};
let fft_settings = MclFFTSettings {
max_width: FIELD_ELEMENTS_PER_EXT_BLOB,
root_of_unity: roots_of_unity[1],
roots_of_unity,
brp_roots_of_unity,
reverse_roots_of_unity,
};
Ok(MclKZGSettings {
fs: fft_settings,
g1_values_monomial: unsafe {
core::slice::from_raw_parts(
settings.g1_values_monomial,
eth::FIELD_ELEMENTS_PER_BLOB,
)
}
.iter()
.map(|r| {
MclG1::from_blst_p1(blst::blst_p1 {
x: blst::blst_fp { l: r.x.l },
y: blst::blst_fp { l: r.y.l },
z: blst::blst_fp { l: r.z.l },
})
})
.collect::<Vec<_>>(),
g1_values_lagrange_brp: unsafe {
core::slice::from_raw_parts(
settings.g1_values_lagrange_brp,
eth::FIELD_ELEMENTS_PER_BLOB,
)
}
.iter()
.map(|r| {
MclG1::from_blst_p1(blst::blst_p1 {
x: blst::blst_fp { l: r.x.l },
y: blst::blst_fp { l: r.y.l },
z: blst::blst_fp { l: r.z.l },
})
})
.collect::<Vec<_>>(),
g2_values_monomial: unsafe {
core::slice::from_raw_parts(
settings.g2_values_monomial,
eth::TRUSTED_SETUP_NUM_G2_POINTS,
)
}
.iter()
.map(|r| {
MclG2::from_blst_p2(blst::blst_p2 {
x: blst::blst_fp2 {
fp: [
blst::blst_fp { l: r.x.fp[0].l },
blst::blst_fp { l: r.x.fp[1].l },
],
},
y: blst::blst_fp2 {
fp: [
blst::blst_fp { l: r.y.fp[0].l },
blst::blst_fp { l: r.y.fp[1].l },
],
},
z: blst::blst_fp2 {
fp: [
blst::blst_fp { l: r.z.fp[0].l },
blst::blst_fp { l: r.z.fp[1].l },
],
},
})
})
.collect::<Vec<_>>(),
x_ext_fft_columns: unsafe {
core::slice::from_raw_parts(
settings.x_ext_fft_columns,
2 * ((FIELD_ELEMENTS_PER_EXT_BLOB / 2) / eth::FIELD_ELEMENTS_PER_CELL),
)
}
.iter()
.map(|it| {
unsafe { core::slice::from_raw_parts(*it, eth::FIELD_ELEMENTS_PER_CELL) }
.iter()
.map(|r| {
MclG1::from_blst_p1(blst::blst_p1 {
x: blst::blst_fp { l: r.x.l },
y: blst::blst_fp { l: r.y.l },
z: blst::blst_fp { l: r.z.l },
})
})
.collect::<Vec<_>>()
})
.collect::<Vec<_>>(),
#[allow(static_mut_refs)]
precomputation: unsafe { PRECOMPUTATION_TABLES.get_precomputation(settings) },
cell_size: eth::FIELD_ELEMENTS_PER_CELL,
})
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/g2.rs | mcl/src/types/g2.rs | extern crate alloc;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use kzg::eip_4844::BYTES_PER_G2;
#[cfg(feature = "rand")]
use kzg::Fr;
use kzg::{G2Mul, G2};
use crate::consts::{G2_GENERATOR, G2_NEGATIVE_GENERATOR};
use crate::mcl_methods::mcl_fp;
use crate::mcl_methods::mcl_fp2;
use crate::mcl_methods::mcl_g2;
use crate::mcl_methods::try_init_mcl;
use crate::types::fr::MclFr;
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub struct MclG2(pub mcl_g2);
impl MclG2 {
pub fn from_blst_p2(p2: blst::blst_p2) -> Self {
try_init_mcl();
Self(mcl_g2 {
x: mcl_fp2 {
d: [mcl_fp { d: p2.x.fp[0].l }, mcl_fp { d: p2.x.fp[1].l }],
},
y: mcl_fp2 {
d: [mcl_fp { d: p2.y.fp[0].l }, mcl_fp { d: p2.y.fp[1].l }],
},
z: mcl_fp2 {
d: [mcl_fp { d: p2.z.fp[0].l }, mcl_fp { d: p2.z.fp[1].l }],
},
})
// Self(blst_p2_into_pc_g2projective(&p2))
}
pub const fn to_blst_p2(&self) -> blst::blst_p2 {
blst::blst_p2 {
x: blst::blst_fp2 {
fp: [
blst::blst_fp { l: self.0.x.d[0].d },
blst::blst_fp { l: self.0.x.d[1].d },
],
},
y: blst::blst_fp2 {
fp: [
blst::blst_fp { l: self.0.y.d[0].d },
blst::blst_fp { l: self.0.y.d[1].d },
],
},
z: blst::blst_fp2 {
fp: [
blst::blst_fp { l: self.0.z.d[0].d },
blst::blst_fp { l: self.0.z.d[1].d },
],
},
}
// pc_g2projective_into_blst_p2(self.0)
}
#[cfg(feature = "rand")]
pub fn rand() -> Self {
try_init_mcl();
let result: MclG2 = G2_GENERATOR;
result.mul(&MclFr::rand())
}
}
impl G2 for MclG2 {
fn generator() -> Self {
try_init_mcl();
G2_GENERATOR
}
fn negative_generator() -> Self {
try_init_mcl();
G2_NEGATIVE_GENERATOR
}
fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
try_init_mcl();
bytes
.try_into()
.map_err(|_| {
format!(
"Invalid byte length. Expected {}, got {}",
BYTES_PER_G2,
bytes.len()
)
})
.and_then(|bytes: &[u8; BYTES_PER_G2]| {
use blst::{blst_p2, blst_p2_affine};
let mut tmp = blst_p2_affine::default();
let mut g2 = blst_p2::default();
unsafe {
// The uncompress routine also checks that the point is on the curve
if blst::blst_p2_uncompress(&mut tmp, bytes.as_ptr())
!= blst::BLST_ERROR::BLST_SUCCESS
{
return Err("Failed to uncompress".to_string());
}
blst::blst_p2_from_affine(&mut g2, &tmp);
}
Ok(MclG2::from_blst_p2(g2))
})
}
fn to_bytes(&self) -> [u8; 96] {
todo!()
}
fn add_or_dbl(&mut self, b: &Self) -> Self {
try_init_mcl();
let mut out: mcl_g2 = mcl_g2::default();
mcl_g2::add(&mut out, &self.0, &b.0);
Self(out)
}
fn dbl(&self) -> Self {
try_init_mcl();
let mut out = mcl_g2::default();
mcl_g2::dbl(&mut out, &self.0);
Self(out)
}
fn sub(&self, b: &Self) -> Self {
try_init_mcl();
let mut out: mcl_g2 = mcl_g2::default();
mcl_g2::sub(&mut out, &self.0, &b.0);
Self(out)
}
fn equals(&self, b: &Self) -> bool {
try_init_mcl();
mcl_g2::eq(&self.0, &b.0)
}
}
impl G2Mul<MclFr> for MclG2 {
fn mul(&self, b: &MclFr) -> Self {
try_init_mcl();
let mut out: mcl_g2 = mcl_g2::default();
mcl_g2::mul(&mut out, &self.0, &b.0);
Self(out)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/poly.rs | mcl/src/types/poly.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::common_utils::{log2_pow2, log2_u64, next_pow_of_2};
use kzg::{FFTFr, FFTSettings, FFTSettingsPoly, Fr, Poly};
use crate::consts::SCALE_FACTOR;
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct MclPoly {
pub coeffs: Vec<MclFr>,
}
impl Poly<MclFr> for MclPoly {
fn new(size: usize) -> Self {
Self {
coeffs: vec![MclFr::default(); size],
}
}
fn get_coeff_at(&self, i: usize) -> MclFr {
self.coeffs[i]
}
fn set_coeff_at(&mut self, i: usize, x: &MclFr) {
self.coeffs[i] = *x
}
fn get_coeffs(&self) -> &[MclFr] {
&self.coeffs
}
fn len(&self) -> usize {
self.coeffs.len()
}
fn eval(&self, x: &MclFr) -> MclFr {
if self.coeffs.is_empty() {
return MclFr::zero();
} else if x.is_zero() {
return self.coeffs[0];
}
let mut ret = self.coeffs[self.coeffs.len() - 1];
let mut i = self.coeffs.len() - 2;
loop {
let temp = ret.mul(x);
ret = temp.add(&self.coeffs[i]);
if i == 0 {
break;
}
i -= 1;
}
ret
}
fn scale(&mut self) {
let scale_factor = MclFr::from_u64(SCALE_FACTOR);
let inv_factor = scale_factor.inverse();
let mut factor_power = MclFr::one();
for i in 0..self.coeffs.len() {
factor_power = factor_power.mul(&inv_factor);
self.coeffs[i] = self.coeffs[i].mul(&factor_power);
}
}
fn unscale(&mut self) {
let scale_factor = MclFr::from_u64(SCALE_FACTOR);
let mut factor_power = MclFr::one();
for i in 0..self.coeffs.len() {
factor_power = factor_power.mul(&scale_factor);
self.coeffs[i] = self.coeffs[i].mul(&factor_power);
}
}
// TODO: analyze how algo works
fn inverse(&mut self, output_len: usize) -> Result<Self, String> {
if output_len == 0 {
return Err(String::from("Can't produce a zero-length result"));
} else if self.coeffs.is_empty() {
return Err(String::from("Can't inverse a zero-length poly"));
} else if self.coeffs[0].is_zero() {
return Err(String::from(
"First coefficient of polynomial mustn't be zero",
));
}
let mut ret = MclPoly {
coeffs: vec![MclFr::zero(); output_len],
};
// If the input polynomial is constant, the remainder of the series is zero
if self.coeffs.len() == 1 {
ret.coeffs[0] = self.coeffs[0].eucl_inverse();
return Ok(ret);
}
let maxd = output_len - 1;
// Max space for multiplications is (2 * length - 1)
// Don't need the following as its recalculated inside
// let scale: usize = log2_pow2(next_pow_of_2(2 * output_len - 1));
// let fft_settings = MclFFTSettings::new(scale).unwrap();
// To store intermediate results
// Base case for d == 0
ret.coeffs[0] = self.coeffs[0].eucl_inverse();
let mut d: usize = 0;
let mut mask: usize = 1 << log2_u64(maxd);
while mask != 0 {
d = 2 * d + usize::from((maxd & mask) != 0);
mask >>= 1;
// b.c -> tmp0 (we're using out for c)
// tmp0.length = min_u64(d + 1, b->length + output->length - 1);
let len_temp = (d + 1).min(self.len() + output_len - 1);
let mut tmp0 = self.mul(&ret, len_temp).unwrap();
// 2 - b.c -> tmp0
for i in 0..tmp0.len() {
tmp0.coeffs[i] = tmp0.coeffs[i].negate();
}
let fr_two = Fr::from_u64(2);
tmp0.coeffs[0] = tmp0.coeffs[0].add(&fr_two);
// c.(2 - b.c) -> tmp1;
let tmp1 = ret.mul(&tmp0, d + 1).unwrap();
for i in 0..tmp1.len() {
ret.coeffs[i] = tmp1.coeffs[i];
}
}
if d + 1 != output_len {
return Err(String::from("D + 1 must be equal to output_len"));
}
Ok(ret)
}
fn div(&mut self, divisor: &Self) -> Result<Self, String> {
if divisor.len() >= self.len() || divisor.len() < 128 {
// Tunable parameter
self.long_div(divisor)
} else {
self.fast_div(divisor)
}
}
fn long_div(&mut self, divisor: &Self) -> Result<Self, String> {
if divisor.coeffs.is_empty() {
return Err(String::from("Can't divide by zero"));
} else if divisor.coeffs[divisor.coeffs.len() - 1].is_zero() {
return Err(String::from("Highest coefficient must be non-zero"));
}
let out_length = self.poly_quotient_length(divisor);
if out_length == 0 {
return Ok(MclPoly { coeffs: vec![] });
}
// Special case for divisor.len() == 2
if divisor.len() == 2 {
let divisor_0 = divisor.coeffs[0];
let divisor_1 = divisor.coeffs[1];
let mut out_coeffs = Vec::from(&self.coeffs[1..]);
for i in (1..out_length).rev() {
out_coeffs[i] = out_coeffs[i].div(&divisor_1).unwrap();
let tmp = out_coeffs[i].mul(&divisor_0);
out_coeffs[i - 1] = out_coeffs[i - 1].sub(&tmp);
}
out_coeffs[0] = out_coeffs[0].div(&divisor_1).unwrap();
Ok(MclPoly { coeffs: out_coeffs })
} else {
let mut out: MclPoly = MclPoly {
coeffs: vec![MclFr::default(); out_length],
};
let mut a_pos = self.len() - 1;
let b_pos = divisor.len() - 1;
let mut diff = a_pos - b_pos;
let mut a = self.coeffs.clone();
while diff > 0 {
out.coeffs[diff] = a[a_pos].div(&divisor.coeffs[b_pos]).unwrap();
for i in 0..(b_pos + 1) {
let tmp = out.coeffs[diff].mul(&divisor.coeffs[i]);
a[diff + i] = a[diff + i].sub(&tmp);
}
diff -= 1;
a_pos -= 1;
}
out.coeffs[0] = a[a_pos].div(&divisor.coeffs[b_pos]).unwrap();
Ok(out)
}
}
fn fast_div(&mut self, divisor: &Self) -> Result<Self, String> {
if divisor.coeffs.is_empty() {
return Err(String::from("Cant divide by zero"));
} else if divisor.coeffs[divisor.coeffs.len() - 1].is_zero() {
return Err(String::from("Highest coefficient must be non-zero"));
}
let m: usize = self.len() - 1;
let n: usize = divisor.len() - 1;
// If the divisor is larger than the dividend, the result is zero-length
if n > m {
return Ok(MclPoly { coeffs: Vec::new() });
}
// Special case for divisor.length == 1 (it's a constant)
if divisor.len() == 1 {
let mut out = MclPoly {
coeffs: vec![MclFr::zero(); self.len()],
};
for i in 0..out.len() {
out.coeffs[i] = self.coeffs[i].div(&divisor.coeffs[0]).unwrap();
}
return Ok(out);
}
let mut a_flip = self.flip().unwrap();
let mut b_flip = divisor.flip().unwrap();
let inv_b_flip = b_flip.inverse(m - n + 1).unwrap();
let q_flip = a_flip.mul(&inv_b_flip, m - n + 1).unwrap();
let out = q_flip.flip().unwrap();
Ok(out)
}
fn mul_direct(&mut self, multiplier: &Self, output_len: usize) -> Result<Self, String> {
if self.len() == 0 || multiplier.len() == 0 {
return Ok(MclPoly::new(0));
}
let a_degree = self.len() - 1;
let b_degree = multiplier.len() - 1;
let mut ret = MclPoly {
coeffs: vec![Fr::zero(); output_len],
};
// Truncate the output to the length of the output polynomial
for i in 0..(a_degree + 1) {
let mut j = 0;
while (j <= b_degree) && ((i + j) < output_len) {
let tmp = self.coeffs[i].mul(&multiplier.coeffs[j]);
let tmp = ret.coeffs[i + j].add(&tmp);
ret.coeffs[i + j] = tmp;
j += 1;
}
}
Ok(ret)
}
}
impl FFTSettingsPoly<MclFr, MclPoly, MclFFTSettings> for MclFFTSettings {
fn poly_mul_fft(
a: &MclPoly,
b: &MclPoly,
len: usize,
_fs: Option<&MclFFTSettings>,
) -> Result<MclPoly, String> {
b.mul_fft(a, len)
}
}
impl MclPoly {
pub fn _poly_norm(&self) -> Self {
let mut ret = self.clone();
let mut temp_len: usize = ret.coeffs.len();
while temp_len > 0 && ret.coeffs[temp_len - 1].is_zero() {
temp_len -= 1;
}
if temp_len == 0 {
ret.coeffs = Vec::new();
} else {
ret.coeffs = ret.coeffs[0..temp_len].to_vec();
}
ret
}
pub fn poly_quotient_length(&self, divisor: &Self) -> usize {
if self.len() >= divisor.len() {
self.len() - divisor.len() + 1
} else {
0
}
}
pub fn pad(&self, out_length: usize) -> Self {
let mut ret = Self {
coeffs: vec![MclFr::zero(); out_length],
};
for i in 0..self.len().min(out_length) {
ret.coeffs[i] = self.coeffs[i];
}
ret
}
pub fn flip(&self) -> Result<MclPoly, String> {
let mut ret = MclPoly {
coeffs: vec![MclFr::default(); self.len()],
};
for i in 0..self.len() {
ret.coeffs[i] = self.coeffs[self.coeffs.len() - i - 1]
}
Ok(ret)
}
pub fn mul_fft(&self, multiplier: &Self, output_len: usize) -> Result<Self, String> {
let length = next_pow_of_2(self.len() + multiplier.len() - 1);
let scale = log2_pow2(length);
let fft_settings = MclFFTSettings::new(scale).unwrap();
let a_pad = self.pad(length);
let b_pad = multiplier.pad(length);
let a_fft: Vec<MclFr>;
let b_fft: Vec<MclFr>;
#[cfg(feature = "parallel")]
{
if length > 1024 {
let mut a_fft_temp = vec![];
let mut b_fft_temp = vec![];
rayon::join(
|| a_fft_temp = fft_settings.fft_fr(&a_pad.coeffs, false).unwrap(),
|| b_fft_temp = fft_settings.fft_fr(&b_pad.coeffs, false).unwrap(),
);
a_fft = a_fft_temp;
b_fft = b_fft_temp;
} else {
a_fft = fft_settings.fft_fr(&a_pad.coeffs, false).unwrap();
b_fft = fft_settings.fft_fr(&b_pad.coeffs, false).unwrap();
}
}
#[cfg(not(feature = "parallel"))]
{
// Convert Poly to values
a_fft = fft_settings.fft_fr(&a_pad.coeffs, false).unwrap();
b_fft = fft_settings.fft_fr(&b_pad.coeffs, false).unwrap();
}
// Multiply two value ranges
let mut ab_fft = a_fft;
ab_fft.iter_mut().zip(b_fft).for_each(|(a, b)| {
*a = a.mul(&b);
});
// Convert value range multiplication to a resulting polynomial
let ab = fft_settings.fft_fr(&ab_fft, true).unwrap();
drop(ab_fft);
let mut ret = MclPoly {
coeffs: vec![MclFr::zero(); output_len],
};
let range = ..output_len.min(length);
ret.coeffs[range].clone_from_slice(&ab[range]);
Ok(ret)
}
pub fn mul(&mut self, multiplier: &Self, output_len: usize) -> Result<Self, String> {
if self.len() < 64 || multiplier.len() < 64 || output_len < 128 {
// Tunable parameter
self.mul_direct(multiplier, output_len)
} else {
self.mul_fft(multiplier, output_len)
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/fft_settings.rs | mcl/src/types/fft_settings.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::common_utils::reverse_bit_order;
use kzg::{FFTSettings, Fr};
use crate::consts::SCALE2_ROOT_OF_UNITY;
use crate::types::fr::MclFr;
#[derive(Debug, Clone)]
pub struct MclFFTSettings {
pub max_width: usize,
pub root_of_unity: MclFr,
pub roots_of_unity: Vec<MclFr>,
pub brp_roots_of_unity: Vec<MclFr>,
pub reverse_roots_of_unity: Vec<MclFr>,
}
impl Default for MclFFTSettings {
fn default() -> Self {
Self::new(0).unwrap()
}
}
impl FFTSettings<MclFr> for MclFFTSettings {
/// Create FFTSettings with roots of unity for a selected scale. Resulting roots will have a magnitude of 2 ^ max_scale.
fn new(scale: usize) -> Result<MclFFTSettings, String> {
if scale >= SCALE2_ROOT_OF_UNITY.len() {
return Err(String::from(
"Scale is expected to be within root of unity matrix row size",
));
}
// max_width = 2 ^ max_scale
let max_width: usize = 1 << scale;
let root_of_unity = MclFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[scale]);
// create max_width of roots & store them reversed as well
let roots_of_unity = expand_root_of_unity(&root_of_unity, max_width)?;
let mut brp_roots_of_unity = roots_of_unity.clone();
brp_roots_of_unity.pop();
reverse_bit_order(&mut brp_roots_of_unity)?;
let mut reverse_roots_of_unity = roots_of_unity.clone();
reverse_roots_of_unity.reverse();
Ok(MclFFTSettings {
max_width,
root_of_unity,
reverse_roots_of_unity,
roots_of_unity,
brp_roots_of_unity,
})
}
fn get_max_width(&self) -> usize {
self.max_width
}
fn get_reverse_roots_of_unity_at(&self, i: usize) -> MclFr {
self.reverse_roots_of_unity[i]
}
fn get_reversed_roots_of_unity(&self) -> &[MclFr] {
&self.reverse_roots_of_unity
}
fn get_roots_of_unity_at(&self, i: usize) -> MclFr {
self.roots_of_unity[i]
}
fn get_roots_of_unity(&self) -> &[MclFr] {
&self.roots_of_unity
}
fn get_brp_roots_of_unity(&self) -> &[MclFr] {
&self.brp_roots_of_unity
}
fn get_brp_roots_of_unity_at(&self, i: usize) -> MclFr {
self.brp_roots_of_unity[i]
}
}
/// Multiply a given root of unity by itself until it results in a 1 and result all multiplication values in a vector
pub fn expand_root_of_unity(root: &MclFr, width: usize) -> Result<Vec<MclFr>, String> {
let mut generated_powers = vec![MclFr::one(), *root];
while !(generated_powers.last().unwrap().is_one()) {
if generated_powers.len() > width {
return Err(String::from("Root of unity multiplied for too long"));
}
generated_powers.push(generated_powers.last().unwrap().mul(root));
}
if generated_powers.len() != width + 1 {
return Err(String::from("Root of unity has invalid scale"));
}
Ok(generated_powers)
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/g1.rs | mcl/src/types/g1.rs | extern crate alloc;
use core::hash::Hash;
use core::ops::Add;
use core::ops::Sub;
use alloc::borrow::ToOwned;
use alloc::format;
use alloc::string::String;
use alloc::string::ToString;
use arbitrary::Arbitrary;
use blst::blst_fp;
use blst::blst_p1;
use blst::blst_p1_affine;
use blst::blst_p1_in_g1;
use blst::BLST_ERROR;
use kzg::eip_4844::BYTES_PER_G1;
use kzg::msm::precompute::PrecomputationTable;
use kzg::G1Affine;
use kzg::G1GetFp;
use kzg::G1LinComb;
use kzg::G1ProjAddAffine;
use kzg::{G1Mul, G1};
use crate::consts::{G1_GENERATOR, G1_IDENTITY, G1_NEGATIVE_GENERATOR};
use crate::kzg_proofs::g1_linear_combination;
use crate::mcl_methods::mclBnFp_neg;
use crate::mcl_methods::mcl_fp;
use crate::mcl_methods::mcl_g1;
use crate::mcl_methods::try_init_mcl;
use crate::types::fr::MclFr;
use super::fp::MclFp;
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub struct MclG1(pub mcl_g1);
impl Hash for MclG1 {
fn hash<H: core::hash::Hasher>(&self, state: &mut H) {
self.0.x.d.hash(state);
self.0.y.d.hash(state);
self.0.z.d.hash(state);
}
}
impl MclG1 {
pub(crate) const fn from_xyz(x: mcl_fp, y: mcl_fp, z: mcl_fp) -> Self {
MclG1(mcl_g1 { x, y, z })
}
pub fn from_blst_p1(p1: blst_p1) -> Self {
Self(mcl_g1 {
x: mcl_fp { d: p1.x.l },
y: mcl_fp { d: p1.y.l },
z: mcl_fp { d: p1.z.l },
})
// Self(blst_p1_into_pc_g1projective(&p1))
}
pub const fn to_blst_p1(&self) -> blst_p1 {
blst_p1 {
x: blst_fp { l: self.0.x.d },
y: blst_fp { l: self.0.y.d },
z: blst_fp { l: self.0.z.d },
}
// pc_g1projective_into_blst_p1(self.0)
}
}
impl G1 for MclG1 {
fn zero() -> Self {
try_init_mcl();
Self(mcl_g1 {
x: mcl_fp {
d: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
},
y: mcl_fp {
d: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
},
z: mcl_fp {
d: [0, 0, 0, 0, 0, 0],
},
})
}
fn identity() -> Self {
try_init_mcl();
G1_IDENTITY
}
fn generator() -> Self {
try_init_mcl();
G1_GENERATOR
}
fn negative_generator() -> Self {
try_init_mcl();
G1_NEGATIVE_GENERATOR
}
#[cfg(feature = "rand")]
fn rand() -> Self {
try_init_mcl();
let result: MclG1 = G1_GENERATOR;
result.mul(&kzg::Fr::rand())
}
fn from_bytes(bytes: &[u8]) -> Result<Self, String> {
try_init_mcl();
bytes
.try_into()
.map_err(|_| {
format!(
"Invalid byte length. Expected {}, got {}",
BYTES_PER_G1,
bytes.len()
)
})
.and_then(|bytes: &[u8; BYTES_PER_G1]| {
let mut tmp = blst_p1_affine::default();
let mut g1 = blst_p1::default();
unsafe {
// The uncompress routine also checks that the point is on the curve
if blst::blst_p1_uncompress(&mut tmp, bytes.as_ptr())
!= blst::BLST_ERROR::BLST_SUCCESS
{
return Err("Failed to uncompress".to_string());
}
blst::blst_p1_from_affine(&mut g1, &tmp);
}
Ok(MclG1::from_blst_p1(g1))
})
}
fn from_hex(hex: &str) -> Result<Self, String> {
let bytes = hex::decode(&hex[2..]).unwrap();
Self::from_bytes(&bytes)
}
fn to_bytes(&self) -> [u8; 48] {
try_init_mcl();
let mut out = [0u8; BYTES_PER_G1];
unsafe {
blst::blst_p1_compress(out.as_mut_ptr(), &self.to_blst_p1());
}
out
}
fn add_or_dbl(&self, b: &Self) -> Self {
try_init_mcl();
let mut out = mcl_g1::default();
mcl_g1::add(&mut out, &self.0, &b.0);
Self(out)
}
fn is_inf(&self) -> bool {
try_init_mcl();
self.0.get_str(0).eq("0")
}
fn is_valid(&self) -> bool {
try_init_mcl();
let blst = self.to_blst_p1();
unsafe { blst_p1_in_g1(&blst) }
}
fn dbl(&self) -> Self {
try_init_mcl();
let mut out = mcl_g1::default();
mcl_g1::dbl(&mut out, &self.0);
Self(out)
}
fn add(&self, b: &Self) -> Self {
try_init_mcl();
Self(self.0.add(&b.0))
}
fn sub(&self, b: &Self) -> Self {
try_init_mcl();
Self(self.0.sub(&b.0))
}
fn equals(&self, b: &Self) -> bool {
try_init_mcl();
mcl_g1::eq(&self.0, &b.0)
}
fn add_or_dbl_assign(&mut self, b: &Self) {
try_init_mcl();
self.0 = self.0.add(&b.0);
}
fn add_assign(&mut self, b: &Self) {
try_init_mcl();
self.0 = self.0.add(&b.0);
}
fn dbl_assign(&mut self) {
try_init_mcl();
let mut r = mcl_g1::default();
mcl_g1::dbl(&mut r, &self.0);
self.0 = r;
}
}
impl G1GetFp<MclFp> for MclG1 {
fn x(&self) -> &MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&self.0.x)
}
}
fn y(&self) -> &MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&self.0.y)
}
}
fn z(&self) -> &MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&self.0.z)
}
}
fn x_mut(&mut self) -> &mut MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&mut self.0.x)
}
}
fn y_mut(&mut self) -> &mut MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&mut self.0.y)
}
}
fn z_mut(&mut self) -> &mut MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&mut self.0.z)
}
}
fn from_jacobian(x: MclFp, y: MclFp, z: MclFp) -> Self {
Self(mcl_g1 {
x: x.0,
y: y.0,
z: z.0,
})
}
}
impl G1Mul<MclFr> for MclG1 {
fn mul(&self, b: &MclFr) -> Self {
try_init_mcl();
let mut out = MclG1::default();
mcl_g1::mul(&mut out.0, &self.0, &b.0);
out
}
}
impl G1LinComb<MclFr, MclFp, MclG1Affine, MclG1ProjAddAffine> for MclG1 {
fn g1_lincomb(
points: &[Self],
scalars: &[MclFr],
len: usize,
precomputation: Option<
&PrecomputationTable<MclFr, Self, MclFp, MclG1Affine, MclG1ProjAddAffine>,
>,
) -> Self {
try_init_mcl();
let mut out = MclG1::default();
g1_linear_combination(&mut out, points, scalars, len, precomputation);
out
}
}
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub struct MclG1Affine {
pub x: mcl_fp,
pub y: mcl_fp,
}
impl MclG1Affine {
#[allow(clippy::wrong_self_convention)]
fn to_blst_p1_affine(&self) -> blst_p1_affine {
blst_p1_affine {
x: blst_fp { l: self.x.d },
y: blst_fp { l: self.y.d },
}
}
}
impl<'a> Arbitrary<'a> for MclG1Affine {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(MclG1Affine::into_affine(
&MclG1::generator().mul(&u.arbitrary()?),
))
}
}
impl G1Affine<MclG1, MclFp> for MclG1Affine {
fn zero() -> Self {
try_init_mcl();
Self {
x: {
mcl_fp {
d: [0, 0, 0, 0, 0, 0],
}
},
y: {
mcl_fp {
d: [0, 0, 0, 0, 0, 0],
}
},
}
}
fn into_affine(g1: &MclG1) -> Self {
try_init_mcl();
let mut out: mcl_g1 = Default::default();
mcl_g1::normalize(&mut out, &g1.0);
Self { x: out.x, y: out.y }
}
fn into_affines_loc(out: &mut [Self], g1: &[MclG1]) {
try_init_mcl();
for (i, g) in g1.iter().enumerate() {
out[i] = Self::into_affine(g);
}
}
fn to_proj(&self) -> MclG1 {
try_init_mcl();
let mut ret: MclG1 = MclG1::generator();
ret.0.x = self.x;
ret.0.y = self.y;
ret
}
fn x(&self) -> &MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&self.x)
}
}
fn y(&self) -> &MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&self.y)
}
}
fn x_mut(&mut self) -> &mut MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&mut self.x)
}
}
fn y_mut(&mut self) -> &mut MclFp {
try_init_mcl();
unsafe {
// Transmute safe due to repr(C) on MclFp
core::mem::transmute(&mut self.y)
}
}
fn is_infinity(&self) -> bool {
todo!()
}
fn neg(&self) -> Self {
try_init_mcl();
let mut output = *self;
unsafe {
mclBnFp_neg(&mut output.y, &output.x);
}
output
}
fn from_xy(x: MclFp, y: MclFp) -> Self {
Self { x: x.0, y: y.0 }
}
fn to_bytes_uncompressed(&self) -> [u8; 96] {
let mut buffer = [0u8; 96];
unsafe {
blst::blst_p1_affine_serialize(buffer.as_mut_ptr(), &self.to_blst_p1_affine());
};
buffer
}
fn from_bytes_uncompressed(bytes: [u8; 96]) -> Result<Self, String> {
let mut aff = blst::blst_p1_affine::default();
let res = unsafe { blst::blst_p1_deserialize(&mut aff, bytes.as_ptr()) };
if res == BLST_ERROR::BLST_SUCCESS {
Ok(Self {
x: mcl_fp { d: aff.x.l },
y: mcl_fp { d: aff.y.l },
})
} else {
Err("Failed to deserialize point".to_owned())
}
}
}
#[derive(Debug)]
pub struct MclG1ProjAddAffine;
impl G1ProjAddAffine<MclG1, MclFp, MclG1Affine> for MclG1ProjAddAffine {
fn add_assign_affine(_proj: &mut MclG1, _aff: &MclG1Affine) {
todo!()
}
fn add_or_double_assign_affine(_proj: &mut MclG1, _aff: &MclG1Affine) {
todo!()
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/fp.rs | mcl/src/types/fp.rs | use kzg::G1Fp;
use crate::mcl_methods::{mclBnFp_add, mclBnFp_mul, mclBnFp_neg, mcl_fp, try_init_mcl};
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub struct MclFp(pub mcl_fp);
impl G1Fp for MclFp {
fn one() -> Self {
try_init_mcl();
Self(mcl_fp {
d: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
})
}
fn zero() -> Self {
try_init_mcl();
Self(mcl_fp {
d: [0, 0, 0, 0, 0, 0],
})
}
fn bls12_381_rx_p() -> Self {
try_init_mcl();
Self(mcl_fp {
d: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
})
}
fn inverse(&self) -> Option<Self> {
try_init_mcl();
let mut out: Self = *self;
mcl_fp::inv(&mut out.0, &self.0);
Some(out)
}
fn square(&self) -> Self {
try_init_mcl();
let mut out: Self = *self;
mcl_fp::sqr(&mut out.0, &self.0);
out
}
fn double(&self) -> Self {
try_init_mcl();
let mut out: Self = Default::default();
unsafe {
mclBnFp_add(&mut out.0, &self.0, &self.0);
}
out
}
fn from_underlying_arr(arr: &[u64; 6]) -> Self {
try_init_mcl();
Self(mcl_fp { d: *arr })
}
fn neg_assign(&mut self) {
try_init_mcl();
unsafe {
mclBnFp_neg(&mut self.0, &self.0);
}
}
fn mul_assign_fp(&mut self, b: &Self) {
try_init_mcl();
self.0 *= &b.0;
}
fn sub_assign_fp(&mut self, b: &Self) {
try_init_mcl();
self.0 -= &b.0;
}
fn add_assign_fp(&mut self, b: &Self) {
try_init_mcl();
self.0 += &b.0;
}
fn mul3(&self) -> Self {
try_init_mcl();
const THREE: mcl_fp = mcl_fp {
d: [
17157870155352091297,
9692872460839157767,
5726366251156250088,
11420128032487956561,
9069687087735597977,
1000072309349998725,
],
};
let mut z = *self;
unsafe {
mclBnFp_mul(&mut z.0, &z.0, &THREE);
}
z
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/mod.rs | mcl/src/types/mod.rs | pub mod fft_settings;
pub mod fk20_multi_settings;
pub mod fk20_single_settings;
pub mod fp;
pub mod fr;
pub mod g1;
pub mod g2;
pub mod kzg_settings;
pub mod poly;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/types/fk20_multi_settings.rs | mcl/src/types/fk20_multi_settings.rs | extern crate alloc;
use alloc::string::String;
use alloc::vec;
use alloc::vec::Vec;
use kzg::common_utils::reverse_bit_order;
use kzg::{FK20MultiSettings, Poly, FFTG1, G1};
use crate::types::fft_settings::MclFFTSettings;
use crate::types::fr::MclFr;
use crate::types::g1::MclG1;
use crate::types::g2::MclG2;
use crate::types::kzg_settings::MclKZGSettings;
use crate::types::poly::MclPoly;
use super::fp::MclFp;
use super::g1::{MclG1Affine, MclG1ProjAddAffine};
pub struct MclFK20MultiSettings {
pub kzg_settings: MclKZGSettings,
pub chunk_len: usize,
pub x_ext_fft_files: Vec<Vec<MclG1>>,
}
impl Clone for MclFK20MultiSettings {
fn clone(&self) -> Self {
Self {
kzg_settings: self.kzg_settings.clone(),
chunk_len: self.chunk_len,
x_ext_fft_files: self.x_ext_fft_files.clone(),
}
}
}
impl Default for MclFK20MultiSettings {
fn default() -> Self {
Self {
kzg_settings: MclKZGSettings::default(),
chunk_len: 1,
x_ext_fft_files: vec![],
}
}
}
impl
FK20MultiSettings<
MclFr,
MclG1,
MclG2,
MclFFTSettings,
MclPoly,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
> for MclFK20MultiSettings
{
#[allow(clippy::many_single_char_names)]
fn new(ks: &MclKZGSettings, n2: usize, chunk_len: usize) -> Result<Self, String> {
if n2 > ks.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
} else if n2 < 2 {
return Err(String::from("n2 must be greater than or equal to 2"));
} else if chunk_len > n2 / 2 {
return Err(String::from("chunk_len must be greater or equal to n2 / 2"));
} else if !chunk_len.is_power_of_two() {
return Err(String::from("chunk_len must be a power of two"));
}
let n = n2 / 2;
let k = n / chunk_len;
let mut ext_fft_files = Vec::with_capacity(chunk_len);
{
let mut x = Vec::with_capacity(k);
for offset in 0..chunk_len {
let mut start = 0;
if n >= chunk_len + 1 + offset {
start = n - chunk_len - 1 - offset;
}
let mut i = 0;
let mut j = start;
while i + 1 < k {
x.push(ks.g1_values_monomial[j]);
i += 1;
if j >= chunk_len {
j -= chunk_len;
} else {
j = 0;
}
}
x.push(MclG1::identity());
let ext_fft_file = ks.fs.toeplitz_part_1(&x);
x.clear();
ext_fft_files.push(ext_fft_file);
}
}
let ret = Self {
kzg_settings: ks.clone(),
chunk_len,
x_ext_fft_files: ext_fft_files,
};
Ok(ret)
}
fn data_availability(&self, p: &MclPoly) -> Result<Vec<MclG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
}
if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
}
let mut ret = self.data_availability_optimized(p).unwrap();
reverse_bit_order(&mut ret)?;
Ok(ret)
}
fn data_availability_optimized(&self, p: &MclPoly) -> Result<Vec<MclG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.kzg_settings.fs.max_width {
return Err(String::from(
"n2 must be less than or equal to kzg settings max width",
));
} else if !n2.is_power_of_two() {
return Err(String::from("n2 must be a power of two"));
}
let n = n2 / 2;
let k = n / self.chunk_len;
let k2 = k * 2;
let mut h_ext_fft = vec![MclG1::identity(); k2];
for i in 0..self.chunk_len {
let toeplitz_coeffs = p.toeplitz_coeffs_stride(i, self.chunk_len);
let h_ext_fft_file = self
.kzg_settings
.fs
.toeplitz_part_2(&toeplitz_coeffs, &self.x_ext_fft_files[i]);
for j in 0..k2 {
h_ext_fft[j] = h_ext_fft[j].add_or_dbl(&h_ext_fft_file[j]);
}
}
let mut h = self.kzg_settings.fs.toeplitz_part_3(&h_ext_fft);
h[k..k2].copy_from_slice(&vec![MclG1::identity(); k2 - k]);
let ret = self.kzg_settings.fs.fft_g1(&h, false).unwrap();
Ok(ret)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/trait_implementations/kzg_settings.rs | mcl/src/trait_implementations/kzg_settings.rs | use crate::data_types::{fr::Fr, g1::G1, g2::G2};
use crate::fk20_fft::FFTSettings;
use crate::kzg10::Polynomial;
use crate::kzg_settings::KZGSettings;
use kzg::KZGSettings as CommonKZGSettings;
impl CommonKZGSettings<Fr, G1, G2, FFTSettings, Polynomial> for KZGSettings {
fn new(
secret_g1: &[G1],
secret_g2: &[G2],
length: usize,
fs: &FFTSettings,
) -> Result<Self, String> {
KZGSettings::new(secret_g1, secret_g2, length, fs)
}
fn commit_to_poly(&self, polynomial: &Polynomial) -> Result<G1, String> {
polynomial.commit(&self.curve.g1_points)
}
fn compute_proof_single(&self, polynomial: &Polynomial, x: &Fr) -> Result<G1, String> {
polynomial.gen_proof_at(&self.curve.g1_points, x)
}
fn check_proof_single(&self, com: &G1, proof: &G1, x: &Fr, value: &Fr) -> Result<bool, String> {
Ok(KZGSettings::check_proof_single(self, com, proof, x, value))
}
fn compute_proof_multi(&self, p: &Polynomial, x: &Fr, n: usize) -> Result<G1, String> {
KZGSettings::compute_proof_multi(self, p, x, n)
}
fn check_proof_multi(
&self,
com: &G1,
proof: &G1,
x: &Fr,
values: &[Fr],
n: usize,
) -> Result<bool, String> {
KZGSettings::check_proof_multi(self, com, proof, x, values, n)
}
fn get_expanded_roots_of_unity_at(&self, i: usize) -> Fr {
self.fft_settings.expanded_roots_of_unity[i]
}
fn get_roots_of_unity_at(&self, i: usize) -> Fr {
self.fft_settings.roots_of_unity[i]
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/src/trait_implementations/fft_settings.rs | mcl/src/trait_implementations/fft_settings.rs | use crate::data_types::fr::Fr;
use crate::fk20_fft::{FFTSettings, SCALE_2_ROOT_OF_UNITY_PR7_STRINGS};
use kzg::FFTSettings as CommonFFTSettings;
impl CommonFFTSettings<Fr> for FFTSettings {
fn new(scale: usize) -> Result<FFTSettings, String> {
//currently alawys use PR 7 for shared tests
FFTSettings::new_custom_primitive_roots(scale as u8, SCALE_2_ROOT_OF_UNITY_PR7_STRINGS)
}
fn get_max_width(&self) -> usize {
self.max_width
}
fn get_expanded_roots_of_unity_at(&self, i: usize) -> Fr {
self.expanded_roots_of_unity[i]
}
fn get_expanded_roots_of_unity(&self) -> &[Fr] {
&self.expanded_roots_of_unity
}
fn get_reverse_roots_of_unity_at(&self, i: usize) -> Fr {
self.reverse_roots_of_unity[i]
}
fn get_reversed_roots_of_unity(&self) -> &[Fr] {
&self.reverse_roots_of_unity
}
fn get_roots_of_unity_at(&self, i: usize) -> Fr {
self.roots_of_unity[i]
}
fn get_roots_of_unity(&self) -> &[Fr] {
&self.roots_of_unity
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/consts.rs | mcl/tests/consts.rs | // #[path = "./local_tests/local_consts.rs"]
// pub mod local_consts;
#[cfg(test)]
mod tests {
use kzg_bench::tests::consts::{
expand_roots_is_plausible, new_fft_settings_is_plausible, roots_of_unity_are_plausible,
roots_of_unity_is_the_expected_size, roots_of_unity_out_of_bounds_fails,
};
use rust_kzg_mcl::consts::SCALE2_ROOT_OF_UNITY;
use rust_kzg_mcl::types::fft_settings::{expand_root_of_unity, MclFFTSettings};
use rust_kzg_mcl::types::fr::MclFr;
// Shared tests
#[test]
fn roots_of_unity_is_the_expected_size_() {
roots_of_unity_is_the_expected_size(&SCALE2_ROOT_OF_UNITY);
}
#[test]
fn roots_of_unity_out_of_bounds_fails_() {
roots_of_unity_out_of_bounds_fails::<MclFr, MclFFTSettings>();
}
#[test]
fn roots_of_unity_are_plausible_() {
roots_of_unity_are_plausible::<MclFr>(&SCALE2_ROOT_OF_UNITY);
}
#[test]
fn expand_roots_is_plausible_() {
expand_roots_is_plausible::<MclFr>(&SCALE2_ROOT_OF_UNITY, &expand_root_of_unity);
}
#[test]
fn new_fft_settings_is_plausible_() {
new_fft_settings_is_plausible::<MclFr, MclFFTSettings>();
}
// Local tests
// #[test]
// fn roots_of_unity_repeat_at_stride_() {
// roots_of_unity_repeat_at_stride::<MclFr, MclFFTSettings>();
// }
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/das.rs | mcl/tests/das.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::das::{das_extension_test_known, das_extension_test_random};
use rust_kzg_mcl::types::fft_settings::MclFFTSettings;
use rust_kzg_mcl::types::fr::MclFr;
#[test]
fn das_extension_test_known_() {
das_extension_test_known::<MclFr, MclFFTSettings>();
}
#[test]
fn das_extension_test_random_() {
das_extension_test_random::<MclFr, MclFFTSettings>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/eip_4844.rs | mcl/tests/eip_4844.rs | #[cfg(test)]
mod tests {
use kzg::eip_4844::{
blob_to_kzg_commitment_rust, blob_to_polynomial, bytes_to_blob,
compute_blob_kzg_proof_rust, compute_challenge_rust, compute_kzg_proof_rust,
compute_powers, evaluate_polynomial_in_evaluation_form, verify_blob_kzg_proof_batch_rust,
verify_blob_kzg_proof_rust, verify_kzg_proof_rust,
};
use kzg::Fr;
use kzg_bench::tests::eip_4844::{
blob_to_kzg_commitment_test, bytes_to_bls_field_test,
compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test,
compute_and_verify_blob_kzg_proof_test,
compute_and_verify_kzg_proof_fails_with_incorrect_proof_test,
compute_and_verify_kzg_proof_round_trip_test,
compute_and_verify_kzg_proof_within_domain_test, compute_kzg_proof_empty_blob_vector_test,
compute_kzg_proof_incorrect_blob_length_test,
compute_kzg_proof_incorrect_commitments_len_test,
compute_kzg_proof_incorrect_poly_length_test, compute_kzg_proof_incorrect_proofs_len_test,
compute_kzg_proof_test, compute_powers_test, test_vectors_blob_to_kzg_commitment,
test_vectors_compute_blob_kzg_proof, test_vectors_compute_challenge,
test_vectors_compute_kzg_proof, test_vectors_verify_blob_kzg_proof,
test_vectors_verify_blob_kzg_proof_batch, test_vectors_verify_kzg_proof,
validate_batched_input_test, verify_kzg_proof_batch_fails_with_incorrect_proof_test,
verify_kzg_proof_batch_test,
};
use rust_kzg_mcl::consts::SCALE2_ROOT_OF_UNITY;
use rust_kzg_mcl::eip_4844::load_trusted_setup_filename_rust;
use rust_kzg_mcl::types::fft_settings::expand_root_of_unity;
use rust_kzg_mcl::types::fp::MclFp;
use rust_kzg_mcl::types::g1::{MclG1Affine, MclG1ProjAddAffine};
use rust_kzg_mcl::types::{
fft_settings::MclFFTSettings, fr::MclFr, g1::MclG1, g2::MclG2,
kzg_settings::MclKZGSettings, poly::MclPoly,
};
#[test]
pub fn bytes_to_bls_field_test_() {
bytes_to_bls_field_test::<MclFr>();
}
#[test]
pub fn compute_powers_test_() {
compute_powers_test::<MclFr>(&compute_powers);
}
#[test]
pub fn blob_to_kzg_commitment_test_() {
blob_to_kzg_commitment_test::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
);
}
#[test]
pub fn compute_kzg_proof_test_() {
compute_kzg_proof_test::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&compute_kzg_proof_rust,
&blob_to_polynomial,
&evaluate_polynomial_in_evaluation_form,
);
}
#[test]
pub fn compute_and_verify_kzg_proof_round_trip_test_() {
compute_and_verify_kzg_proof_round_trip_test::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_kzg_proof_rust,
&blob_to_polynomial,
&evaluate_polynomial_in_evaluation_form,
&verify_kzg_proof_rust,
);
}
#[test]
pub fn compute_and_verify_kzg_proof_within_domain_test_() {
compute_and_verify_kzg_proof_within_domain_test::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_kzg_proof_rust,
&blob_to_polynomial,
&evaluate_polynomial_in_evaluation_form,
&verify_kzg_proof_rust,
);
}
#[test]
pub fn compute_and_verify_kzg_proof_fails_with_incorrect_proof_test_() {
compute_and_verify_kzg_proof_fails_with_incorrect_proof_test::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_kzg_proof_rust,
&blob_to_polynomial,
&evaluate_polynomial_in_evaluation_form,
&verify_kzg_proof_rust,
);
}
#[test]
pub fn compute_and_verify_blob_kzg_proof_test_() {
compute_and_verify_blob_kzg_proof_test::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
&verify_blob_kzg_proof_rust,
);
}
#[test]
pub fn compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test_() {
compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
&verify_blob_kzg_proof_rust,
);
}
#[test]
pub fn verify_kzg_proof_batch_test_() {
verify_kzg_proof_batch_test::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
&verify_blob_kzg_proof_batch_rust,
);
}
#[test]
pub fn verify_kzg_proof_batch_fails_with_incorrect_proof_test_() {
verify_kzg_proof_batch_fails_with_incorrect_proof_test::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
&verify_blob_kzg_proof_batch_rust,
);
}
#[test]
pub fn test_vectors_blob_to_kzg_commitment_() {
test_vectors_blob_to_kzg_commitment::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
&bytes_to_blob,
);
}
#[test]
pub fn test_vectors_compute_kzg_proof_() {
test_vectors_compute_kzg_proof::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&compute_kzg_proof_rust,
&bytes_to_blob,
);
}
#[test]
pub fn test_vectors_compute_blob_kzg_proof_() {
test_vectors_compute_blob_kzg_proof::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&bytes_to_blob,
&compute_blob_kzg_proof_rust,
);
}
#[test]
pub fn test_vectors_verify_kzg_proof_() {
test_vectors_verify_kzg_proof::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(&load_trusted_setup_filename_rust, &verify_kzg_proof_rust);
}
#[test]
pub fn test_vectors_verify_blob_kzg_proof_() {
test_vectors_verify_blob_kzg_proof::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&bytes_to_blob,
&verify_blob_kzg_proof_rust,
);
}
#[test]
pub fn test_vectors_verify_blob_kzg_proof_batch_() {
test_vectors_verify_blob_kzg_proof_batch::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&bytes_to_blob,
&verify_blob_kzg_proof_batch_rust,
);
}
#[test]
pub fn test_vectors_compute_challenge_() {
test_vectors_compute_challenge::<MclFr, MclG1>(&bytes_to_blob, &compute_challenge_rust);
}
#[test]
pub fn expand_root_of_unity_too_long() {
let out = expand_root_of_unity(&MclFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[1]), 1);
assert!(out.is_err());
}
#[test]
pub fn expand_root_of_unity_too_short() {
let out = expand_root_of_unity(&MclFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[1]), 3);
assert!(out.is_err());
}
#[test]
pub fn compute_kzg_proof_incorrect_blob_length() {
compute_kzg_proof_incorrect_blob_length_test::<MclFr, MclPoly>(&blob_to_polynomial);
}
#[test]
pub fn compute_kzg_proof_incorrect_poly_length() {
compute_kzg_proof_incorrect_poly_length_test::<
MclPoly,
MclFr,
MclG1,
MclG2,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(&evaluate_polynomial_in_evaluation_form);
}
#[test]
pub fn compute_kzg_proof_empty_blob_vector() {
compute_kzg_proof_empty_blob_vector_test::<
MclPoly,
MclFr,
MclG1,
MclG2,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(&verify_blob_kzg_proof_batch_rust)
}
#[test]
pub fn compute_kzg_proof_incorrect_commitments_len() {
compute_kzg_proof_incorrect_commitments_len_test::<
MclPoly,
MclFr,
MclG1,
MclG2,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(&verify_blob_kzg_proof_batch_rust)
}
#[test]
pub fn compute_kzg_proof_incorrect_proofs_len() {
compute_kzg_proof_incorrect_proofs_len_test::<
MclPoly,
MclFr,
MclG1,
MclG2,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(&verify_blob_kzg_proof_batch_rust)
}
#[test]
pub fn validate_batched_input() {
validate_batched_input_test::<
MclPoly,
MclFr,
MclG1,
MclG2,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
&verify_blob_kzg_proof_batch_rust,
&load_trusted_setup_filename_rust,
)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/kzg_proofs.rs | mcl/tests/kzg_proofs.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::kzg_proofs::{
commit_to_nil_poly, commit_to_too_long_poly_returns_err, proof_multi, proof_single,
trusted_setup_in_correct_form,
};
use rust_kzg_mcl::eip_7594::MclBackend;
use rust_kzg_mcl::utils::generate_trusted_setup;
#[test]
pub fn test_trusted_setup_in_correct_form() {
trusted_setup_in_correct_form::<MclBackend>(&generate_trusted_setup);
}
#[test]
pub fn test_proof_single() {
proof_single::<MclBackend>(&generate_trusted_setup);
}
#[test]
pub fn test_commit_to_nil_poly() {
commit_to_nil_poly::<MclBackend>(&generate_trusted_setup);
}
#[test]
pub fn test_commit_to_too_long_poly() {
commit_to_too_long_poly_returns_err::<MclBackend>(&generate_trusted_setup);
}
#[test]
pub fn test_proof_multi() {
proof_multi::<MclBackend>(&generate_trusted_setup);
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/eip_7594.rs | mcl/tests/eip_7594.rs | #[cfg(test)]
mod tests {
use kzg::{
eip_4844::{blob_to_kzg_commitment_rust, bytes_to_blob},
eth, DAS,
};
use kzg_bench::tests::{
eip_4844::generate_random_blob_bytes,
eip_7594::{
test_vectors_compute_cells, test_vectors_compute_cells_and_kzg_proofs,
test_vectors_compute_verify_cell_kzg_proof_batch_challenge,
test_vectors_recover_cells_and_kzg_proofs, test_vectors_verify_cell_kzg_proof_batch,
},
utils::get_trusted_setup_path,
};
use rust_kzg_mcl::{
eip_4844::load_trusted_setup_filename_rust,
eip_7594::MclBackend,
types::{fr::MclFr, g1::MclG1, kzg_settings::MclKZGSettings},
};
#[test]
pub fn test_vectors_compute_cells_() {
test_vectors_compute_cells::<MclBackend>(&load_trusted_setup_filename_rust, &bytes_to_blob);
}
#[test]
pub fn test_vectors_compute_cells_and_kzg_proofs_() {
test_vectors_compute_cells_and_kzg_proofs::<MclBackend>(
&load_trusted_setup_filename_rust,
&bytes_to_blob,
);
}
#[test]
pub fn test_vectors_recover_cells_and_kzg_proofs_() {
test_vectors_recover_cells_and_kzg_proofs::<MclBackend>(&load_trusted_setup_filename_rust);
}
#[test]
pub fn test_vectors_verify_cell_kzg_proof_batch_() {
test_vectors_verify_cell_kzg_proof_batch::<MclBackend>(&load_trusted_setup_filename_rust);
}
#[test]
pub fn test_vectors_compute_verify_cell_kzg_proof_batch_challenge_() {
test_vectors_compute_verify_cell_kzg_proof_batch_challenge::<MclBackend>();
}
#[test]
pub fn test_recover_cells_and_kzg_proofs_succeeds_random_blob() {
let settings = load_trusted_setup_filename_rust(get_trusted_setup_path().as_str()).unwrap();
let mut rng = rand::thread_rng();
/* Get a random blob */
let blob_bytes = generate_random_blob_bytes(&mut rng);
let blob: Vec<MclFr> = bytes_to_blob(&blob_bytes).unwrap();
let mut cells =
vec![MclFr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
let mut proofs = vec![MclG1::default(); eth::CELLS_PER_EXT_BLOB];
/* Get the cells and proofs */
let mut result = <MclKZGSettings as DAS<MclBackend>>::compute_cells_and_kzg_proofs(
&settings,
Some(&mut cells),
Some(&mut proofs),
&blob,
);
assert!(result.is_ok());
let cell_indices: Vec<usize> = (0..).step_by(2).take(eth::CELLS_PER_EXT_BLOB / 2).collect();
let mut partial_cells =
vec![MclFr::default(); (eth::CELLS_PER_EXT_BLOB / 2) * eth::FIELD_ELEMENTS_PER_CELL];
/* Erase half of the cells */
for i in 0..(eth::CELLS_PER_EXT_BLOB / 2) {
partial_cells[i * eth::FIELD_ELEMENTS_PER_CELL..(i + 1) * eth::FIELD_ELEMENTS_PER_CELL]
.clone_from_slice(
&cells[cell_indices[i] * eth::FIELD_ELEMENTS_PER_CELL
..(cell_indices[i] + 1) * eth::FIELD_ELEMENTS_PER_CELL],
);
}
let mut recovered_cells =
vec![MclFr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
let mut recovered_proofs = vec![MclG1::default(); eth::CELLS_PER_EXT_BLOB];
/* Reconstruct with half of the cells */
result = <MclKZGSettings as DAS<MclBackend>>::recover_cells_and_kzg_proofs(
&settings,
&mut recovered_cells,
Some(&mut recovered_proofs),
&cell_indices,
&partial_cells,
);
assert!(result.is_ok());
/* Check that all of the cells match */
assert!(recovered_cells == cells, "Cells do not match");
assert!(recovered_proofs == proofs, "Proofs do not match");
}
#[test]
pub fn test_verify_cell_kzg_proof_batch_succeeds_random_blob() {
let settings = load_trusted_setup_filename_rust(get_trusted_setup_path().as_str()).unwrap();
let mut rng = rand::thread_rng();
/* Get a random blob */
let blob_bytes = generate_random_blob_bytes(&mut rng);
let blob = bytes_to_blob(&blob_bytes).unwrap();
/* Get the commitment to the blob */
let commitment_result = blob_to_kzg_commitment_rust(&blob, &settings);
assert!(commitment_result.is_ok());
let commitment = commitment_result.unwrap();
let mut cells: Vec<MclFr> =
vec![MclFr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
let mut proofs = vec![MclG1::default(); eth::CELLS_PER_EXT_BLOB];
/* Compute cells and proofs */
let result = <MclKZGSettings as DAS<MclBackend>>::compute_cells_and_kzg_proofs(
&settings,
Some(&mut cells),
Some(&mut proofs),
&blob,
);
assert!(result.is_ok());
/* Initialize list of commitments & cell indices */
let commitments = vec![commitment; eth::CELLS_PER_EXT_BLOB];
let cell_indices: Vec<usize> = (0..).step_by(1).take(eth::CELLS_PER_EXT_BLOB).collect();
/* Verify all the proofs */
let verify_result = <MclKZGSettings as DAS<MclBackend>>::verify_cell_kzg_proof_batch(
&settings,
&commitments,
&cell_indices,
&cells,
&proofs,
);
assert!(verify_result.is_ok());
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/poly.rs | mcl/tests/poly.rs | // #[path = "./local_tests/local_poly.rs"]
// pub mod local_poly;
#[cfg(test)]
mod tests {
use kzg_bench::tests::poly::{
create_poly_of_length_ten, poly_div_by_zero, poly_div_fast_test, poly_div_long_test,
poly_div_random, poly_eval_0_check, poly_eval_check, poly_eval_nil_check,
poly_inverse_simple_0, poly_inverse_simple_1, poly_mul_direct_test, poly_mul_fft_test,
poly_mul_random, poly_test_div,
};
use rust_kzg_mcl::types::fft_settings::MclFFTSettings;
use rust_kzg_mcl::types::fr::MclFr;
use rust_kzg_mcl::types::poly::MclPoly;
// Local tests
// #[test]
// fn local_create_poly_of_length_ten_() {
// create_poly_of_length_ten()
// }
//
// #[test]
// fn local_poly_pad_works_rand_() {
// poly_pad_works_rand()
// }
//
// #[test]
// fn local_poly_eval_check_() {
// poly_eval_check()
// }
//
// #[test]
// fn local_poly_eval_0_check_() { poly_eval_0_check() }
//
// #[test]
// fn local_poly_eval_nil_check_() {
// poly_eval_nil_check()
// }
//
// #[test]
// fn local_poly_inverse_simple_0_() {
// poly_inverse_simple_0()
// }
//
// #[test]
// fn local_poly_inverse_simple_1_() {
// poly_inverse_simple_1()
// }
//
// #[test]
// fn local_test_poly_div_by_zero_() {
// test_poly_div_by_zero()
// }
//
// #[test]
// fn local_poly_div_long_test_() {
// poly_div_long_test()
// }
//
// #[test]
// fn local_poly_div_fast_test_() {
// poly_div_fast_test()
// }
//
// #[test]
// fn local_poly_mul_direct_test_() {
// poly_mul_direct_test()
// }
//
// #[test]
// fn local_poly_mul_fft_test_() {
// poly_mul_fft_test()
// }
//
// #[test]
// fn local_poly_mul_random_() {
// poly_mul_random()
// }
//
// #[test]
// fn local_poly_div_random_() {
// poly_div_random()
// }
// Shared tests
#[test]
fn create_poly_of_length_ten_() {
create_poly_of_length_ten::<MclFr, MclPoly>()
}
#[test]
fn poly_eval_check_() {
poly_eval_check::<MclFr, MclPoly>()
}
#[test]
fn poly_eval_0_check_() {
poly_eval_0_check::<MclFr, MclPoly>()
}
#[test]
fn poly_eval_nil_check_() {
poly_eval_nil_check::<MclFr, MclPoly>()
}
#[test]
fn poly_inverse_simple_0_() {
poly_inverse_simple_0::<MclFr, MclPoly>()
}
#[test]
fn poly_inverse_simple_1_() {
poly_inverse_simple_1::<MclFr, MclPoly>()
}
#[test]
fn poly_test_div_() {
poly_test_div::<MclFr, MclPoly>()
}
#[test]
fn poly_div_by_zero_() {
poly_div_by_zero::<MclFr, MclPoly>()
}
#[test]
fn poly_mul_direct_test_() {
poly_mul_direct_test::<MclFr, MclPoly>()
}
#[test]
fn poly_mul_fft_test_() {
poly_mul_fft_test::<MclFr, MclPoly, MclFFTSettings>()
}
#[test]
fn poly_mul_random_() {
poly_mul_random::<MclFr, MclPoly, MclFFTSettings>()
}
#[test]
fn poly_div_random_() {
poly_div_random::<MclFr, MclPoly>()
}
#[test]
fn poly_div_long_test_() {
poly_div_long_test::<MclFr, MclPoly>()
}
#[test]
fn poly_div_fast_test_() {
poly_div_fast_test::<MclFr, MclPoly>()
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/zero_poly.rs | mcl/tests/zero_poly.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::zero_poly::{
check_test_data, reduce_partials_random, test_reduce_partials, zero_poly_252,
zero_poly_all_but_one, zero_poly_known, zero_poly_random,
};
use rust_kzg_mcl::types::fft_settings::MclFFTSettings;
use rust_kzg_mcl::types::fr::MclFr;
use rust_kzg_mcl::types::poly::MclPoly;
#[test]
fn test_reduce_partials_() {
test_reduce_partials::<MclFr, MclFFTSettings, MclPoly>();
}
#[test]
fn reduce_partials_random_() {
reduce_partials_random::<MclFr, MclFFTSettings, MclPoly>();
}
#[test]
fn check_test_data_() {
check_test_data::<MclFr, MclFFTSettings, MclPoly>();
}
#[test]
fn zero_poly_known_() {
zero_poly_known::<MclFr, MclFFTSettings, MclPoly>();
}
#[test]
fn zero_poly_random_() {
zero_poly_random::<MclFr, MclFFTSettings, MclPoly>();
}
#[test]
fn zero_poly_all_but_one_() {
zero_poly_all_but_one::<MclFr, MclFFTSettings, MclPoly>();
}
#[test]
fn zero_poly_252_() {
zero_poly_252::<MclFr, MclFFTSettings, MclPoly>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/bls12_381.rs | mcl/tests/bls12_381.rs | #[cfg(test)]
mod tests {
use kzg::common_utils::log_2_byte;
use kzg_bench::tests::bls12_381::{
fr_div_by_zero, fr_div_works, fr_equal_works, fr_from_uint64_works, fr_is_null_works,
fr_is_one_works, fr_is_zero_works, fr_negate_works, fr_pow_works, fr_uint64s_roundtrip,
g1_identity_is_identity, g1_identity_is_infinity, g1_linear_combination_infinity_points,
g1_make_linear_combination, g1_random_linear_combination, g1_small_linear_combination,
log_2_byte_works, p1_mul_works, p1_sub_works, p2_add_or_dbl_works, p2_mul_works,
p2_sub_works, pairings_work,
};
use rust_kzg_mcl::kzg_proofs::{g1_linear_combination, pairings_verify};
use rust_kzg_mcl::types::fp::MclFp;
use rust_kzg_mcl::types::fr::MclFr;
use rust_kzg_mcl::types::g1::{MclG1, MclG1Affine, MclG1ProjAddAffine};
use rust_kzg_mcl::types::g2::MclG2;
#[test]
fn log_2_byte_works_() {
log_2_byte_works(&log_2_byte)
}
#[test]
fn fr_is_null_works_() {
fr_is_null_works::<MclFr>()
}
#[test]
fn fr_is_zero_works_() {
fr_is_zero_works::<MclFr>()
}
#[test]
fn fr_is_one_works_() {
fr_is_one_works::<MclFr>()
}
#[test]
fn fr_from_uint64_works_() {
fr_from_uint64_works::<MclFr>()
}
#[test]
fn fr_equal_works_() {
fr_equal_works::<MclFr>()
}
#[test]
fn fr_negate_works_() {
fr_negate_works::<MclFr>()
}
#[test]
fn fr_pow_works_() {
fr_pow_works::<MclFr>()
}
#[test]
fn fr_div_works_() {
fr_div_works::<MclFr>()
}
#[test]
fn fr_div_by_zero_() {
fr_div_by_zero::<MclFr>()
}
#[test]
fn fr_uint64s_roundtrip_() {
fr_uint64s_roundtrip::<MclFr>()
}
#[test]
fn p1_mul_works_() {
p1_mul_works::<MclFr, MclG1>()
}
#[test]
fn p1_sub_works_() {
p1_sub_works::<MclG1>()
}
#[test]
fn p2_add_or_dbl_works_() {
p2_add_or_dbl_works::<MclG2>()
}
#[test]
fn p2_mul_works_() {
p2_mul_works::<MclFr, MclG2>()
}
#[test]
fn p2_sub_works_() {
p2_sub_works::<MclG2>()
}
#[test]
fn g1_identity_is_infinity_() {
g1_identity_is_infinity::<MclG1>()
}
#[test]
fn g1_identity_is_identity_() {
g1_identity_is_identity::<MclG1>()
}
#[test]
fn g1_make_linear_combination_() {
g1_make_linear_combination::<MclFr, MclG1, MclFp, MclG1Affine, MclG1ProjAddAffine>(
&g1_linear_combination,
)
}
#[test]
fn g1_random_linear_combination_() {
g1_random_linear_combination::<MclFr, MclG1, MclFp, MclG1Affine, MclG1ProjAddAffine>(
&g1_linear_combination,
)
}
#[ignore = "TODO: handle infinity points"]
#[test]
pub fn g1_linear_combination_infinity_points_() {
g1_linear_combination_infinity_points::<MclFr, MclG1, MclFp, MclG1Affine, MclG1ProjAddAffine>(
&g1_linear_combination,
);
}
#[test]
fn g1_small_linear_combination_() {
g1_small_linear_combination::<MclFr, MclG1, MclFp, MclG1Affine, MclG1ProjAddAffine>(
&g1_linear_combination,
)
}
#[test]
fn pairings_work_() {
pairings_work::<MclFr, MclG1, MclG2>(&pairings_verify)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/fk20_proofs.rs | mcl/tests/fk20_proofs.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::fk20_proofs::*;
use rust_kzg_mcl::eip_7594::MclBackend;
use rust_kzg_mcl::types::fk20_multi_settings::MclFK20MultiSettings;
use rust_kzg_mcl::types::fk20_single_settings::MclFK20SingleSettings;
use rust_kzg_mcl::utils::generate_trusted_setup;
#[test]
fn test_fk_single() {
fk_single::<MclBackend, MclFK20SingleSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_single_strided() {
fk_single_strided::<MclBackend, MclFK20SingleSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_settings() {
fk_multi_settings::<MclBackend, MclFK20MultiSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_chunk_len_1_512() {
fk_multi_chunk_len_1_512::<MclBackend, MclFK20MultiSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_chunk_len_16_512() {
fk_multi_chunk_len_16_512::<MclBackend, MclFK20MultiSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_chunk_len_16_16() {
fk_multi_chunk_len_16_16::<MclBackend, MclFK20MultiSettings>(&generate_trusted_setup);
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/mod.rs | mcl/tests/mod.rs | pub mod local_tests;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/c_bindings.rs | mcl/tests/c_bindings.rs | #[cfg(all(test, feature = "c_bindings"))]
mod tests {
use kzg_bench::tests::c_bindings::{
blob_to_kzg_commitment_invalid_blob_test,
compute_blob_kzg_proof_commitment_is_point_at_infinity_test,
compute_blob_kzg_proof_invalid_blob_test, free_trusted_setup_null_ptr_test,
free_trusted_setup_set_all_values_to_null_test,
load_trusted_setup_file_invalid_format_test, load_trusted_setup_file_valid_format_test,
load_trusted_setup_invalid_form_test, load_trusted_setup_invalid_g1_byte_length_test,
load_trusted_setup_invalid_g1_point_test, load_trusted_setup_invalid_g2_byte_length_test,
load_trusted_setup_invalid_g2_point_test,
};
use rust_kzg_mcl::eip_4844::{
blob_to_kzg_commitment, compute_blob_kzg_proof, free_trusted_setup, load_trusted_setup,
load_trusted_setup_file,
};
#[test]
fn blob_to_kzg_commitment_invalid_blob() {
blob_to_kzg_commitment_invalid_blob_test(blob_to_kzg_commitment, load_trusted_setup_file);
}
#[test]
fn load_trusted_setup_invalid_g1_byte_length() {
load_trusted_setup_invalid_g1_byte_length_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_invalid_g1_point() {
load_trusted_setup_invalid_g1_point_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_invalid_g2_byte_length() {
load_trusted_setup_invalid_g2_byte_length_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_invalid_g2_point() {
load_trusted_setup_invalid_g2_point_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_invalid_form() {
load_trusted_setup_invalid_form_test(load_trusted_setup);
}
#[test]
fn load_trusted_setup_file_invalid_format() {
load_trusted_setup_file_invalid_format_test(load_trusted_setup_file);
}
#[test]
fn load_trusted_setup_file_valid_format() {
load_trusted_setup_file_valid_format_test(load_trusted_setup_file);
}
#[test]
fn free_trusted_setup_null_ptr() {
free_trusted_setup_null_ptr_test(free_trusted_setup);
}
#[test]
fn free_trusted_setup_set_all_values_to_null() {
free_trusted_setup_set_all_values_to_null_test(free_trusted_setup, load_trusted_setup_file);
}
#[test]
fn compute_blob_kzg_proof_invalid_blob() {
compute_blob_kzg_proof_invalid_blob_test(compute_blob_kzg_proof, load_trusted_setup_file);
}
#[test]
fn compute_blob_kzg_proof_commitment_is_point_at_infinity() {
compute_blob_kzg_proof_commitment_is_point_at_infinity_test(
compute_blob_kzg_proof,
load_trusted_setup_file,
);
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/fft_g1.rs | mcl/tests/fft_g1.rs | #[cfg(test)]
mod tests {
use kzg::G1;
use kzg_bench::tests::fft_g1::{compare_ft_fft, roundtrip_fft, stride_fft};
use rust_kzg_mcl::consts::G1_GENERATOR;
use rust_kzg_mcl::fft_g1::{fft_g1_fast, fft_g1_slow};
use rust_kzg_mcl::types::fft_settings::MclFFTSettings;
use rust_kzg_mcl::types::fr::MclFr;
use rust_kzg_mcl::types::g1::MclG1;
fn make_data(n: usize) -> Vec<MclG1> {
if n == 0 {
return Vec::new();
}
let mut result: Vec<MclG1> = vec![MclG1::default(); n];
result[0] = G1_GENERATOR;
for i in 1..n {
result[i] = result[i - 1].add_or_dbl(&G1_GENERATOR)
}
result
}
#[test]
fn roundtrip_fft_() {
roundtrip_fft::<MclFr, MclG1, MclFFTSettings>(&make_data);
}
#[test]
fn stride_fft_() {
stride_fft::<MclFr, MclG1, MclFFTSettings>(&make_data);
}
#[test]
fn compare_sft_fft_() {
compare_ft_fft::<MclFr, MclG1, MclFFTSettings>(&fft_g1_slow, &fft_g1_fast, &make_data);
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/fft_fr.rs | mcl/tests/fft_fr.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::fft_fr::{compare_sft_fft, inverse_fft, roundtrip_fft, stride_fft};
use rust_kzg_mcl::fft_fr::{fft_fr_fast, fft_fr_slow};
use rust_kzg_mcl::types::fft_settings::MclFFTSettings;
use rust_kzg_mcl::types::fr::MclFr;
#[test]
fn compare_sft_fft_() {
compare_sft_fft::<MclFr, MclFFTSettings>(&fft_fr_slow, &fft_fr_fast);
}
#[test]
fn roundtrip_fft_() {
roundtrip_fft::<MclFr, MclFFTSettings>();
}
#[test]
fn inverse_fft_() {
inverse_fft::<MclFr, MclFFTSettings>();
}
#[test]
fn stride_fft_() {
stride_fft::<MclFr, MclFFTSettings>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/recovery.rs | mcl/tests/recovery.rs | // #[path = "./local_tests/local_recovery.rs"]
// pub mod local_recovery;
#[cfg(test)]
mod tests {
use kzg_bench::tests::recover::*;
// uncomment to use the local tests
//use crate::local_recovery::{recover_random, recover_simple};
use rust_kzg_mcl::types::fft_settings::MclFFTSettings;
use rust_kzg_mcl::types::fr::MclFr;
use rust_kzg_mcl::types::poly::MclPoly;
// Shared tests
#[test]
fn recover_simple_() {
recover_simple::<MclFr, MclFFTSettings, MclPoly, MclPoly>();
}
#[test]
fn recover_random_() {
recover_random::<MclFr, MclFFTSettings, MclPoly, MclPoly>();
}
#[test]
fn more_than_half_missing_() {
more_than_half_missing::<MclFr, MclFFTSettings, MclPoly, MclPoly>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/batch_adder.rs | mcl/tests/batch_adder.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::msm::batch_adder::{
test_batch_add, test_batch_add_indexed, test_batch_add_indexed_single_bucket,
test_batch_add_step_n, test_phase_one_p_add_p, test_phase_one_p_add_q,
test_phase_one_p_add_q_twice, test_phase_one_zero_or_neg, test_phase_two_p_add_neg,
test_phase_two_p_add_p, test_phase_two_p_add_q, test_phase_two_zero_add_p,
};
use rust_kzg_mcl::types::{
fp::MclFp,
g1::{MclG1, MclG1Affine},
};
// use rust_kzg_mcl::types::
#[test]
fn test_phase_one_zero_or_neg_() {
test_phase_one_zero_or_neg::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_phase_one_p_add_p_() {
test_phase_one_p_add_p::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_phase_one_p_add_q_() {
test_phase_one_p_add_q::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_phase_one_p_add_q_twice_() {
test_phase_one_p_add_q_twice::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_phase_two_zero_add_p_() {
test_phase_two_zero_add_p::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_phase_two_p_add_neg_() {
test_phase_two_p_add_neg::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_phase_two_p_add_q_() {
test_phase_two_p_add_q::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_phase_two_p_add_p_() {
test_phase_two_p_add_p::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_batch_add_() {
test_batch_add::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_batch_add_step_n_() {
test_batch_add_step_n::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_batch_add_indexed_() {
test_batch_add_indexed::<MclG1, MclFp, MclG1Affine>();
}
#[test]
fn test_batch_add_indexed_single_bucket_() {
test_batch_add_indexed_single_bucket::<MclG1, MclFp, MclG1Affine>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/local_tests/local_recovery.rs | mcl/tests/local_tests/local_recovery.rs | use kzg::{FFTFr, FFTSettings, Fr, Poly, PolyRecover};
use rand::rngs::StdRng;
use rand::{RngCore, SeedableRng};
use std::convert::TryInto;
fn shuffle(a: &mut [usize], n: usize) {
let mut i: u64 = n as u64;
let mut j: usize;
let mut tmp: usize;
let mut rng = StdRng::seed_from_u64(0);
while i > 0 {
j = (rng.next_u64() % i) as usize;
i -= 1;
tmp = a[j];
a[j] = a[i as usize];
a[i as usize] = tmp;
}
}
fn random_missing<TFr: Fr>(
with_missing: &mut [Option<TFr>],
data: &[TFr],
len_data: usize,
known: usize,
) {
let mut missing_idx = Vec::new();
for i in 0..len_data {
missing_idx.push(i);
with_missing[i] = Some(data[i].clone());
}
shuffle(&mut missing_idx, len_data);
for i in 0..(len_data - known) {
with_missing[missing_idx[i]] = None;
}
}
pub fn recover_simple<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>,
TPoly: Poly<TFr>,
TPolyRecover: PolyRecover<TFr, TPoly, TFFTSettings>,
>() {
let fs_query = TFFTSettings::new(2);
assert!(fs_query.is_ok());
let fs: TFFTSettings = fs_query.unwrap();
let max_width: usize = fs.get_max_width();
let poly_query = TPoly::new(max_width);
let mut poly = poly_query;
for i in 0..(max_width / 2) {
poly.set_coeff_at(i, &TFr::from_u64(i.try_into().unwrap()));
}
for i in (max_width / 2)..max_width {
poly.set_coeff_at(i, &TFr::zero());
}
let data_query = fs.fft_fr(poly.get_coeffs(), false);
assert!(data_query.is_ok());
let data = data_query.unwrap();
let sample: [Option<TFr>; 4] = [Some(data[0].clone()), None, None, Some(data[3].clone())];
let recovered_query = TPolyRecover::recover_poly_from_samples(&sample, &fs);
assert!(recovered_query.is_ok());
let recovered = recovered_query.unwrap();
for (i, item) in data.iter().enumerate().take(max_width) {
assert!(item.equals(&recovered.get_coeff_at(i)));
}
let mut recovered_vec: Vec<TFr> = Vec::new();
for i in 0..max_width {
recovered_vec.push(recovered.get_coeff_at(i));
}
let back_query = fs.fft_fr(&recovered_vec, true);
assert!(back_query.is_ok());
let back = back_query.unwrap();
for (i, back_x) in back[..(max_width / 2)].iter().enumerate() {
assert!(back_x.equals(&poly.get_coeff_at(i)));
}
for back_x in back[(max_width / 2)..max_width].iter() {
assert!(back_x.is_zero());
}
}
pub fn recover_random<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>,
TPoly: Poly<TFr>,
TPolyRecover: PolyRecover<TFr, TPoly, TFFTSettings>,
>() {
let fs_query = TFFTSettings::new(12);
assert!(fs_query.is_ok());
let fs: TFFTSettings = fs_query.unwrap();
let max_width: usize = fs.get_max_width();
// let mut poly = TPoly::default();
let poly_query = TPoly::new(max_width);
let mut poly = poly_query;
for i in 0..(max_width / 2) {
poly.set_coeff_at(i, &TFr::from_u64(i.try_into().unwrap()));
}
for i in (max_width / 2)..max_width {
poly.set_coeff_at(i, &TFr::zero());
}
let data_query = fs.fft_fr(poly.get_coeffs(), false);
assert!(data_query.is_ok());
let data = data_query.unwrap();
let mut samples = vec![Some(TFr::default()); max_width]; // std::vec![TFr; max_width];
for i in 0..10 {
let known_ratio = 0.5 + (i as f32) * 0.05;
let known: usize = ((max_width as f32) * known_ratio) as usize;
for _ in 0..4 {
random_missing(&mut samples, &data, max_width, known);
let recovered_query = TPolyRecover::recover_poly_from_samples(&samples, &fs);
assert!(recovered_query.is_ok());
let recovered = recovered_query.unwrap();
for (j, item) in data.iter().enumerate().take(max_width) {
assert!(item.equals(&recovered.get_coeff_at(j)));
}
let mut recovered_vec: Vec<TFr> = Vec::new();
for i in 0..max_width {
recovered_vec.push(recovered.get_coeff_at(i));
}
let back_query = fs.fft_fr(&recovered_vec, true);
assert!(back_query.is_ok());
let back = back_query.unwrap();
for (i, back_x) in back[..(max_width / 2)].iter().enumerate() {
assert!(back_x.equals(&poly.get_coeff_at(i)));
}
for back_x in back[(max_width / 2)..max_width].iter() {
assert!(back_x.is_zero());
}
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/local_tests/local_poly.rs | mcl/tests/local_tests/local_poly.rs | use kzg::{Fr, Poly};
use rand::rngs::StdRng;
use rand::{RngCore, SeedableRng};
use rust_kzg_mcl::types::fr::MclFr;
use rust_kzg_mcl::types::poly::MclPoly;
pub fn create_poly_of_length_ten() {
let poly = MclPoly::new(10);
assert_eq!(poly.len(), 10);
}
pub fn poly_pad_works_rand() {
let mut rng = StdRng::seed_from_u64(0);
for _k in 0..256 {
let poly_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let mut poly = MclPoly::new(poly_length);
for i in 0..poly.len() {
poly.set_coeff_at(i, &MclFr::rand());
}
let padded_poly = poly.pad(1000);
for i in 0..poly_length {
assert!(padded_poly.get_coeff_at(i).equals(&poly.get_coeff_at(i)));
}
for i in poly_length..1000 {
assert!(padded_poly.get_coeff_at(i).equals(&Fr::zero()));
}
}
}
pub fn poly_eval_check() {
let n: usize = 10;
let mut poly = MclPoly::new(n);
for i in 0..n {
let fr = MclFr::from_u64((i + 1) as u64);
poly.set_coeff_at(i, &fr);
}
let expected = MclFr::from_u64((n * (n + 1) / 2) as u64);
let actual = poly.eval(&MclFr::one());
assert!(expected.equals(&actual));
}
pub fn poly_eval_0_check() {
let n: usize = 7;
let a: usize = 597;
let mut poly = MclPoly::new(n);
for i in 0..n {
let fr = MclFr::from_u64((i + a) as u64);
poly.set_coeff_at(i, &fr);
}
let expected = MclFr::from_u64(a as u64);
let actual = poly.eval(&MclFr::zero());
assert!(expected.equals(&actual));
}
pub fn poly_eval_nil_check() {
let n: usize = 0;
let poly = MclPoly::new(n);
let actual = poly.eval(&MclFr::one());
assert!(actual.equals(&MclFr::zero()));
}
pub fn poly_inverse_simple_0() {
// 1 / (1 - x) = 1 + x + x^2 + ...
let d: usize = 16;
let mut p = MclPoly::new(2);
p.set_coeff_at(0, &MclFr::one());
p.set_coeff_at(1, &MclFr::one());
p.set_coeff_at(1, &MclFr::negate(&p.get_coeff_at(1)));
let result = p.inverse(d);
assert!(result.is_ok());
let q = result.unwrap();
for i in 0..d {
assert!(q.get_coeff_at(i).is_one());
}
}
pub fn poly_inverse_simple_1() {
// 1 / (1 + x) = 1 - x + x^2 - ...
let d: usize = 16;
let mut p = MclPoly::new(2);
p.set_coeff_at(0, &MclFr::one());
p.set_coeff_at(1, &MclFr::one());
let result = p.inverse(d);
assert!(result.is_ok());
let q = result.unwrap();
for i in 0..d {
let mut tmp = q.get_coeff_at(i);
if i & 1 != 0 {
tmp = MclFr::negate(&tmp);
}
assert!(tmp.is_one());
}
}
pub const NUM_TESTS: u64 = 10;
fn test_data(a: usize, b: usize) -> Vec<i64> {
// (x^2 - 1) / (x + 1) = x - 1
let test_0_0 = vec![-1, 0, 1];
let test_0_1 = vec![1, 1];
let test_0_2 = vec![-1, 1];
// (12x^3 - 11x^2 + 9x + 18) / (4x + 3) = 3x^2 - 5x + 6
let test_1_0 = vec![18, 9, -11, 12];
let test_1_1 = vec![3, 4];
let test_1_2 = vec![6, -5, 3];
// (x + 1) / (x^2 - 1) = nil
let test_2_0 = vec![1, 1];
let test_2_1 = vec![-1, 0, 2];
let test_2_2 = vec![];
// (10x^2 + 20x + 30) / 10 = x^2 + 2x + 3
let test_3_0 = vec![30, 20, 10];
let test_3_1 = vec![10];
let test_3_2 = vec![3, 2, 1];
// (x^2 + x) / (x + 1) = x
let test_4_0 = vec![0, 1, 1];
let test_4_1 = vec![1, 1];
let test_4_2 = vec![0, 1];
// (x^2 + x + 1) / 1 = x^2 + x + 1
let test_5_0 = vec![1, 1, 1];
let test_5_1 = vec![1];
let test_5_2 = vec![1, 1, 1];
// (x^2 + x + 1) / (0x + 1) = x^2 + x + 1
let test_6_0 = vec![1, 1, 1];
let test_6_1 = vec![1, 0]; // The highest coefficient is zero
let test_6_2 = vec![1, 1, 1];
// (x^3) / (x) = (x^2)
let test_7_0 = vec![0, 0, 0, 1];
let test_7_1 = vec![0, 1];
let test_7_2 = vec![0, 0, 1];
//
let test_8_0 = vec![
236,
945,
-297698,
2489425,
-18556462,
-301325440,
2473062655,
-20699887353,
];
let test_8_1 = vec![4, 11, -5000, 45541, -454533];
let test_8_2 = vec![59, 74, -878, 45541];
// (x^4 + 2x^3 + 3x^2 + 2x + 1) / (-x^2 -x -1) = (-x^2 -x -1)
let test_9_0 = vec![1, 2, 3, 2, 1];
let test_9_1 = vec![-1, -1, -1];
let test_9_2 = vec![-1, -1, -1];
let test_data = [
[test_0_0, test_0_1, test_0_2],
[test_1_0, test_1_1, test_1_2],
[test_2_0, test_2_1, test_2_2],
[test_3_0, test_3_1, test_3_2],
[test_4_0, test_4_1, test_4_2],
[test_5_0, test_5_1, test_5_2],
[test_6_0, test_6_1, test_6_2],
[test_7_0, test_7_1, test_7_2],
[test_8_0, test_8_1, test_8_2],
[test_9_0, test_9_1, test_9_2],
];
test_data[a][b].clone()
}
fn new_test_poly(coeffs: &[i64]) -> MclPoly {
let mut p = MclPoly::new(0);
for &coeff in coeffs.iter() {
if coeff >= 0 {
let c = MclFr::from_u64(coeff as u64);
p.coeffs.push(c);
} else {
let c = MclFr::from_u64((-coeff) as u64);
let negc = c.negate();
p.coeffs.push(negc);
}
}
p
}
pub fn poly_div_long_test() {
for i in 0..9 {
// Tests are designed to throw an exception when last member is 0
if i == 6 {
continue;
}
let divided_data = test_data(i, 0);
let divisor_data = test_data(i, 1);
let expected_data = test_data(i, 2);
let mut dividend: MclPoly = new_test_poly(÷d_data);
let divisor: MclPoly = new_test_poly(&divisor_data);
let expected: MclPoly = new_test_poly(&expected_data);
let actual = dividend.long_div(&divisor).unwrap();
assert_eq!(expected.len(), actual.len());
for i in 0..actual.len() {
assert!(expected.get_coeff_at(i).equals(&actual.get_coeff_at(i)))
}
}
}
pub fn poly_div_fast_test() {
for i in 0..9 {
// Tests are designed to throw an exception when last member is 0
if i == 6 {
continue;
}
let divided_data = test_data(i, 0);
let divisor_data = test_data(i, 1);
let expected_data = test_data(i, 2);
let mut dividend: MclPoly = new_test_poly(÷d_data);
let divisor: MclPoly = new_test_poly(&divisor_data);
let expected: MclPoly = new_test_poly(&expected_data);
let actual = dividend.fast_div(&divisor).unwrap();
assert_eq!(expected.len(), actual.len());
for i in 0..actual.len() {
assert!(expected.get_coeff_at(i).equals(&actual.get_coeff_at(i)))
}
}
}
pub fn test_poly_div_by_zero() {
let mut dividend = MclPoly::new(2);
dividend.set_coeff_at(0, &MclFr::from_u64(1));
dividend.set_coeff_at(1, &MclFr::from_u64(1));
let divisor = MclPoly::new(0);
let dummy = dividend.div(&divisor);
assert!(dummy.is_err());
}
pub fn poly_mul_direct_test() {
for i in 0..9 {
let coeffs1 = test_data(i, 2);
let coeffs2 = test_data(i, 1);
let coeffs3 = test_data(i, 0);
let mut multiplicand: MclPoly = new_test_poly(&coeffs1);
let mut multiplier: MclPoly = new_test_poly(&coeffs2);
let expected: MclPoly = new_test_poly(&coeffs3);
let result0 = multiplicand.mul_direct(&multiplier, coeffs3.len()).unwrap();
for j in 0..result0.len() {
assert!(expected.get_coeff_at(j).equals(&result0.get_coeff_at(j)))
}
// Check commutativity
let result1 = multiplier.mul_direct(&multiplicand, coeffs3.len()).unwrap();
for j in 0..result1.len() {
assert!(expected.get_coeff_at(j).equals(&result1.get_coeff_at(j)))
}
}
}
pub fn poly_mul_fft_test() {
for i in 0..9 {
// Ignore 0 multiplication case because its incorrect when multiplied backwards
if i == 2 {
continue;
}
let coeffs1 = test_data(i, 2);
let coeffs2 = test_data(i, 1);
let coeffs3 = test_data(i, 0);
let multiplicand: MclPoly = new_test_poly(&coeffs1);
let multiplier: MclPoly = new_test_poly(&coeffs2);
let expected: MclPoly = new_test_poly(&coeffs3);
let result0 = multiplicand.mul_fft(&multiplier, coeffs3.len()).unwrap();
for j in 0..result0.len() {
assert!(expected.get_coeff_at(j).equals(&result0.get_coeff_at(j)))
}
// Check commutativity
let result1 = multiplier.mul_fft(&multiplicand, coeffs3.len()).unwrap();
for j in 0..result1.len() {
assert!(expected.get_coeff_at(j).equals(&result1.get_coeff_at(j)))
}
}
}
pub fn poly_mul_random() {
let mut rng = StdRng::seed_from_u64(0);
for _k in 0..256 {
let multiplicand_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let mut multiplicand = MclPoly::new(multiplicand_length);
for i in 0..multiplicand.len() {
multiplicand.set_coeff_at(i, &MclFr::rand());
}
let multiplier_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let mut multiplier = MclPoly::new(multiplier_length);
for i in 0..multiplier.len() {
multiplier.set_coeff_at(i, &MclFr::rand());
}
if multiplicand.get_coeff_at(multiplicand.len() - 1).is_zero() {
multiplicand.set_coeff_at(multiplicand.len() - 1, &Fr::one());
}
if multiplier.get_coeff_at(multiplier.len() - 1).is_zero() {
multiplier.set_coeff_at(multiplier.len() - 1, &Fr::one());
}
let out_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let q0 = multiplicand.mul_direct(&multiplier, out_length).unwrap();
let q1 = multiplicand.mul_fft(&multiplier, out_length).unwrap();
assert_eq!(q0.len(), q1.len());
for i in 0..q0.len() {
assert!(q0.get_coeff_at(i).equals(&q1.get_coeff_at(i)));
}
}
}
pub fn poly_div_random() {
let mut rng = StdRng::seed_from_u64(0);
for _k in 0..256 {
let dividend_length: usize = (2 + (rng.next_u64() % 1000)) as usize;
let divisor_length: usize = 1 + ((rng.next_u64() as usize) % dividend_length);
let mut dividend = MclPoly::new(dividend_length);
let mut divisor = MclPoly::new(divisor_length);
for i in 0..dividend_length {
dividend.set_coeff_at(i, &MclFr::rand());
}
for i in 0..divisor_length {
divisor.set_coeff_at(i, &MclFr::rand());
}
//Ensure that the polynomials' orders corresponds to their lengths
if dividend.get_coeff_at(dividend.len() - 1).is_zero() {
dividend.set_coeff_at(dividend.len() - 1, &Fr::one());
}
if divisor.get_coeff_at(divisor.len() - 1).is_zero() {
divisor.set_coeff_at(divisor.len() - 1, &Fr::one());
}
let result0 = dividend.long_div(&divisor).unwrap();
let result1 = dividend.fast_div(&divisor).unwrap();
assert_eq!(result0.len(), result1.len());
for i in 0..result0.len() {
assert!(result0.get_coeff_at(i).equals(&result1.get_coeff_at(i)));
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/mcl/tests/local_tests/mod.rs | mcl/tests/local_tests/mod.rs | pub mod local_consts;
pub mod local_poly;
pub mod local_recovery;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.