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/mcl/tests/local_tests/local_consts.rs | mcl/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/mcl/benches/trusted_setup.rs | mcl/benches/trusted_setup.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg::eip_4844::load_trusted_setup_rust;
use kzg_bench::benches::trusted_setup::bench_load_trusted_setup;
use rust_kzg_mcl::{
eip_4844::load_trusted_setup_filename_rust,
types::{
fft_settings::MclFFTSettings,
fp::MclFp,
fr::MclFr,
g1::{MclG1, MclG1Affine, MclG1ProjAddAffine},
g2::MclG2,
kzg_settings::MclKZGSettings,
poly::MclPoly,
},
};
fn bench_load_trusted_setup_(c: &mut Criterion) {
bench_load_trusted_setup::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
c,
&load_trusted_setup_filename_rust,
&load_trusted_setup_rust,
);
}
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/mcl/benches/das.rs | mcl/benches/das.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::das::bench_das_extension;
use rust_kzg_mcl::types::fft_settings::MclFFTSettings;
use rust_kzg_mcl::types::fr::MclFr;
fn bench_das_extension_(c: &mut Criterion) {
bench_das_extension::<MclFr, MclFFTSettings>(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/mcl/benches/eip_4844.rs | mcl/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_mcl::{
eip_4844::load_trusted_setup_filename_rust,
types::{
fft_settings::MclFFTSettings,
fp::MclFp,
fr::MclFr,
g1::{MclG1, MclG1Affine, MclG1ProjAddAffine},
g2::MclG2,
kzg_settings::MclKZGSettings,
poly::MclPoly,
},
};
fn bench_eip_4844_(c: &mut Criterion) {
bench_eip_4844::<
MclFr,
MclG1,
MclG2,
MclPoly,
MclFFTSettings,
MclKZGSettings,
MclFp,
MclG1Affine,
MclG1ProjAddAffine,
>(
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/mcl/benches/eip_7594.rs | mcl/benches/eip_7594.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg::eip_4844::{blob_to_kzg_commitment_rust, bytes_to_blob};
use kzg_bench::benches::eip_7594::bench_eip_7594;
use rust_kzg_mcl::{eip_4844::load_trusted_setup_filename_rust, eip_7594::MclBackend};
fn bench_eip_7594_(c: &mut Criterion) {
bench_eip_7594::<MclBackend>(
c,
&load_trusted_setup_filename_rust,
&bytes_to_blob,
&blob_to_kzg_commitment_rust,
);
}
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/benches/poly.rs | mcl/benches/poly.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::poly::bench_new_poly_div;
use rust_kzg_mcl::types::fr::MclFr;
use rust_kzg_mcl::types::poly::MclPoly;
fn bench_new_poly_div_(c: &mut Criterion) {
bench_new_poly_div::<MclFr, MclPoly>(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/mcl/benches/zero_poly.rs | mcl/benches/zero_poly.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::zero_poly::bench_zero_poly;
use rust_kzg_mcl::types::{fft_settings::MclFFTSettings, fr::MclFr, poly::MclPoly};
fn bench_zero_poly_(c: &mut Criterion) {
bench_zero_poly::<MclFr, MclFFTSettings, MclPoly>(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/mcl/benches/kzg.rs | mcl/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_mcl::eip_7594::MclBackend;
use rust_kzg_mcl::utils::generate_trusted_setup;
fn bench_commit_to_poly_(c: &mut Criterion) {
bench_commit_to_poly::<MclBackend>(c, &generate_trusted_setup)
}
fn bench_compute_proof_single_(c: &mut Criterion) {
bench_compute_proof_single::<MclBackend>(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/mcl/benches/lincomb.rs | mcl/benches/lincomb.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::lincomb::bench_g1_lincomb;
use rust_kzg_mcl::kzg_proofs::g1_linear_combination;
use rust_kzg_mcl::types::fp::MclFp;
use rust_kzg_mcl::types::fr::MclFr;
use rust_kzg_mcl::types::g1::{MclG1, MclG1Affine, MclG1ProjAddAffine};
fn bench_g1_lincomb_(c: &mut Criterion) {
bench_g1_lincomb::<MclFr, MclG1, MclFp, MclG1Affine, MclG1ProjAddAffine>(
c,
&g1_linear_combination,
);
}
criterion_group! {
name = benches;
config = Criterion::default().sample_size(100);
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/mcl/benches/fk_20.rs | mcl/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_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;
fn bench_fk_single_da_(c: &mut Criterion) {
bench_fk_single_da::<MclBackend, MclFK20SingleSettings>(c, &generate_trusted_setup)
}
fn bench_fk_multi_da_(c: &mut Criterion) {
bench_fk_multi_da::<MclBackend, MclFK20MultiSettings>(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/mcl/benches/recover.rs | mcl/benches/recover.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::recover::bench_recover;
use rust_kzg_mcl::types::{fft_settings::MclFFTSettings, fr::MclFr, poly::MclPoly};
pub fn bench_recover_(c: &mut Criterion) {
bench_recover::<MclFr, MclFFTSettings, MclPoly, MclPoly>(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/mcl/benches/fft.rs | mcl/benches/fft.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::fft::{bench_fft_fr, bench_fft_g1};
use rust_kzg_mcl::types::fft_settings::MclFFTSettings;
use rust_kzg_mcl::types::fr::MclFr;
use rust_kzg_mcl::types::g1::MclG1;
fn bench_fft_fr_(c: &mut Criterion) {
bench_fft_fr::<MclFr, MclFFTSettings>(c);
}
fn bench_fft_g1_(c: &mut Criterion) {
bench_fft_g1::<MclFr, MclG1, MclFFTSettings>(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/kzg-bench/src/lib.rs | kzg-bench/src/lib.rs | use std::env::set_current_dir;
pub mod benches;
pub mod test_vectors;
pub mod tests;
pub fn set_trusted_setup_dir() {
set_current_dir(env!("CARGO_MANIFEST_DIR")).unwrap();
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/consts.rs | kzg-bench/src/tests/consts.rs | use kzg::{FFTSettings, Fr};
pub fn roots_of_unity_is_the_expected_size(roots: &[[u64; 4]; 32]) {
assert_eq!(roots.len(), 32);
}
pub fn roots_of_unity_out_of_bounds_fails<TFr: Fr, TFFTSettings: FFTSettings<TFr>>() {
let fft_settings = TFFTSettings::new(32);
assert!(fft_settings.is_err());
}
/// Raise each root to the power of 2 ^ i and see if it equals 1
pub fn roots_of_unity_are_plausible<TFr: Fr>(roots: &[[u64; 4]; 32]) {
for (i, root) in roots.iter().enumerate() {
let mut r = TFr::from_u64_arr(root);
for _j in 0..i {
r = r.sqr();
}
assert!(r.is_one());
}
}
/// Check if expanded root members follow symmetry and symmetrically multiply to produce a 1.
#[allow(clippy::type_complexity)]
pub fn expand_roots_is_plausible<TFr: Fr>(
roots: &[[u64; 4]; 32],
expand_root_of_unity: &dyn Fn(&TFr, usize) -> Result<Vec<TFr>, String>,
) {
let scale = 15;
let width: usize = 1 << scale;
let root = TFr::from_u64_arr(&roots[scale]);
let expanded = expand_root_of_unity(&root, width).unwrap();
assert!(expanded[0].is_one());
assert!(expanded[width].is_one());
// Multiply symmetrically and check if the result is 1
for i in 0..(width / 2 + 1) {
let prod = expanded[i].mul(&expanded[width - i]);
assert!(prod.is_one());
}
}
/// Check if generated reverse roots are reversed correctly and multiply with expanded roots to result in 1.
pub fn new_fft_settings_is_plausible<TFr: Fr, TFFTSettings: FFTSettings<TFr>>() {
let scale = 21;
let width: usize = 1 << scale;
let fft_settings = TFFTSettings::new(scale).unwrap();
assert_eq!(fft_settings.get_max_width(), width);
for i in 0..width {
let prod = fft_settings
.get_roots_of_unity_at(i)
.mul(&fft_settings.get_reverse_roots_of_unity_at(i));
assert!(prod.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/kzg-bench/src/tests/das.rs | kzg-bench/src/tests/das.rs | use kzg::{DASExtension, FFTFr, FFTSettings, Fr};
/// Check if DAS FFT creates odds that match precomputed values
pub fn das_extension_test_known<TFr: Fr, TFFTSettings: FFTSettings<TFr> + DASExtension<TFr>>() {
#[rustfmt::skip]
let expected_u: [[u64; 4]; 8] = [
[0xa0c43757db972d7d, 0x79d15a1e0677962c, 0xf678865c0c95fa6a, 0x4e85fd4814f96825, ],
[0xad9f844939f2705d, 0x319e440c9f3b0325, 0x4cbd29a60e160a28, 0x665961d85d90c4c0, ],
[0x5f3ac8a72468d28b, 0xede949e28383c5d2, 0xaf6f84dd8708d8c9, 0x2567aa0b14a41521, ],
[0x25abe312b96aadad, 0x4abf043f091ff417, 0x43824b53e09536db, 0x195dbe06a28ca227, ],
[0x5f3ac8a72468d28b, 0xede949e28383c5d2, 0xaf6f84dd8708d8c9, 0x2567aa0b14a41521, ],
[0xad9f844939f2705d, 0x319e440c9f3b0325, 0x4cbd29a60e160a28, 0x665961d85d90c4c0, ],
[0xa0c43757db972d7d, 0x79d15a1e0677962c, 0xf678865c0c95fa6a, 0x4e85fd4814f96825, ],
[0x7f171458d2b071a9, 0xd185bbb2a46cbd9b, 0xa41aab0d02886e80, 0x01cacceef58ccee9, ],
];
let fft_settings = TFFTSettings::new(4).unwrap();
let mut evens = Vec::new();
for i in 0..(fft_settings.get_max_width() / 2) {
let temp = TFr::from_u64(i as u64);
evens.push(temp);
}
let odds = fft_settings.das_fft_extension(&evens).unwrap();
for i in 0..expected_u.len() {
let expected = TFr::from_u64_arr(&expected_u[i]);
assert!(expected.equals(&odds[i]));
}
}
/// Check that DAS extension produces correct odds.
/// Verify this by checking that the second half of the inverse FFT coefficients of odd-even interpolated vector results in zeros.
pub fn das_extension_test_random<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + DASExtension<TFr> + FFTFr<TFr>,
>() {
let max_scale: usize = 15;
let fft_settings = TFFTSettings::new(max_scale).unwrap();
for scale in 1..(max_scale + 1) {
let width: usize = 1 << scale;
assert!(width <= fft_settings.get_max_width());
for _rep in 0..4 {
let mut evens = Vec::new();
for _i in 0..(width / 2) {
evens.push(TFr::rand());
}
let odds = fft_settings.das_fft_extension(&evens).unwrap();
let mut data = Vec::new();
for i in (0..width).step_by(2) {
data.push(evens[i / 2].clone());
data.push(odds[i / 2].clone());
}
let coeffs = fft_settings.fft_fr(&data, true).unwrap();
for coeff in coeffs.iter().take(width).skip(width / 2) {
assert!(coeff.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/kzg-bench/src/tests/finite.rs | kzg-bench/src/tests/finite.rs | use kzg::Fr;
pub fn sum_of_two_zeros_is_zero<TFr: Fr>() {
let zero = TFr::default();
assert!(zero.add(&zero).equals(&zero));
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/eip_4844.rs | kzg-bench/src/tests/eip_4844.rs | #![allow(unused)]
use crate::test_vectors::{
blob_to_kzg_commitment, compute_blob_kzg_proof, compute_cells, compute_challenge,
compute_kzg_proof, verify_blob_kzg_proof, verify_blob_kzg_proof_batch, verify_kzg_proof,
};
use crate::tests::utils::{get_manifest_dir, get_trusted_setup_path};
use kzg::eip_4844::{
BYTES_PER_BLOB, BYTES_PER_COMMITMENT, BYTES_PER_FIELD_ELEMENT, BYTES_PER_PROOF,
FIELD_ELEMENTS_PER_BLOB, TRUSTED_SETUP_PATH,
};
use kzg::{
FFTSettings, Fr, G1Affine, G1Fp, G1GetFp, G1Mul, G1ProjAddAffine, KZGSettings, Poly, G1, G2,
};
use pathdiff::diff_paths;
use rand::rngs::{OsRng, ThreadRng};
use rand::Rng;
use std::env::current_dir;
use std::fs;
use std::path::PathBuf;
fn u64_to_bytes(x: u64) -> [u8; 32] {
let mut bytes = [0u8; 32];
bytes[24..32].copy_from_slice(&x.to_be_bytes());
bytes
}
pub fn generate_random_blob_bytes(rng: &mut ThreadRng) -> [u8; BYTES_PER_BLOB] {
let mut arr = [0u8; BYTES_PER_BLOB];
rng.fill(&mut arr[..]);
// Ensure that the blob is canonical by ensuring that
// each field element contained in the blob is < BLS_MODULUS
for i in 0..FIELD_ELEMENTS_PER_BLOB {
arr[i * BYTES_PER_FIELD_ELEMENT] = 0;
}
arr
}
pub fn generate_random_field_element_bytes(rng: &mut ThreadRng) -> [u8; BYTES_PER_FIELD_ELEMENT] {
let mut arr = [0u8; BYTES_PER_FIELD_ELEMENT];
rng.fill(&mut arr[..]);
// Ensure that the field element is canonical, i.e. < BLS_MODULUS
arr[0] = 0;
arr
}
#[rustfmt::skip]
const EXPECTED_POWERS: [[u64; 4usize]; 11] = [
[1, 0, 0, 0],
[32930439, 0, 0, 0],
[1084413812732721, 0, 0, 0],
[15773128324309817559, 1935, 0, 0],
[17639716667354648417, 63748557064, 0, 0],
[14688837229838358055, 2099267969765560859, 0, 0],
[17806839894568993937, 15217493595388594120, 3747534, 0],
[17407663719861420663, 10645919139951883969, 123407966953127, 0],
[9882663619548185281, 9079722283539367550, 5594831647882181930, 220],
[4160126872399834567, 5941227867469556516, 11658769961926678707, 7254684264],
[4000187329613806065, 4317886535621327299, 17988956659770583631, 238899937640724696],
];
pub fn bytes_to_bls_field_test<TFr: Fr>() {
let x: u64 = 329;
let x_bytes = u64_to_bytes(x);
let x_fr = TFr::from_bytes(&x_bytes).unwrap();
assert_eq!(x_fr.to_bytes(), x_bytes);
assert_eq!(x, x_fr.to_u64_arr()[0]);
}
pub fn compute_powers_test<TFr: Fr>(compute_powers: &dyn Fn(&TFr, usize) -> Vec<TFr>) {
let x: u64 = 32930439;
let n = 11;
let x_bytes: [u8; 32] = u64_to_bytes(x);
let x_fr = TFr::from_bytes(&x_bytes).unwrap();
let powers = compute_powers(&x_fr, n);
for (p, expected_p) in powers.iter().zip(EXPECTED_POWERS.iter()) {
assert_eq!(expected_p, &p.to_u64_arr());
}
}
#[allow(clippy::type_complexity)]
pub fn blob_to_kzg_commitment_test<
TFr: Fr + Copy,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let field_element =
TFr::from_hex("0x14629a3a39f7b854e6aa49aa2edb450267eac2c14bb2d4f97a0b81a3f57055ad")
.unwrap();
// Initialize the blob with a single field element
let mut blob: [TFr; FIELD_ELEMENTS_PER_BLOB] = [TFr::zero(); FIELD_ELEMENTS_PER_BLOB];
blob[0] = field_element;
// Get a commitment to this particular blob
let commitment = blob_to_kzg_commitment(&blob, &ts).unwrap();
// We expect the commitment to match
// If it doesn't match, something important has changed
let expected_commitment = TG1::from_hex(
"0x91a5e1c143820d2e7bec38a5404c5145807cb88c0abbbecb\
cb4bccc83a4b417326e337574cff43303f8a6648ecbee7ac",
)
.unwrap();
assert!(commitment.equals(&expected_commitment));
}
#[allow(clippy::type_complexity)]
pub fn compute_kzg_proof_test<
TFr: Fr + Copy,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
compute_kzg_proof: &dyn Fn(&[TFr], &TFr, &TKZGSettings) -> Result<(TG1, TFr), String>,
blob_to_polynomial: &dyn Fn(&[TFr]) -> Result<TPoly, String>,
evaluate_polynomial_in_evaluation_form: &dyn Fn(
&TPoly,
&TFr,
&TKZGSettings,
) -> Result<TFr, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let field_element =
TFr::from_hex("0x69386e69dbae0357b399b8d645a57a3062dfbe00bd8e97170b9bdd6bc6168a13")
.unwrap();
let input_value =
TFr::from_hex("0x03ea4fb841b4f9e01aa917c5e40dbd67efb4b8d4d9052069595f0647feba320d")
.unwrap();
// Initialize the blob with a single field element
let mut blob: [TFr; FIELD_ELEMENTS_PER_BLOB] = [TFr::zero(); FIELD_ELEMENTS_PER_BLOB];
blob[0] = field_element;
// Compute the KZG proof for the given blob & z
let (proof, output_value) = compute_kzg_proof(&blob, &input_value, &ts).unwrap();
// Compare the computed proof to the expected proof
let expected_proof = TG1::from_hex(
"0xb21f8f9b85e52fd9c4a6d4fb4e9a27ebdc5a09c3f5ca17f6\
bcd85c26f04953b0e6925607aaebed1087e5cc2fe4b2b356",
)
.unwrap();
assert!(proof.equals(&expected_proof));
// Get the expected y by evaluating the polynomial at input_value
let poly = blob_to_polynomial(&blob).unwrap();
let expected_output_value =
evaluate_polynomial_in_evaluation_form(&poly, &input_value, &ts).unwrap();
assert!(output_value.equals(&expected_output_value));
}
#[allow(clippy::type_complexity)]
pub fn compute_and_verify_kzg_proof_round_trip_test<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
compute_kzg_proof: &dyn Fn(&[TFr], &TFr, &TKZGSettings) -> Result<(TG1, TFr), String>,
blob_to_polynomial: &dyn Fn(&[TFr]) -> Result<TPoly, String>,
evaluate_polynomial_in_evaluation_form: &dyn Fn(
&TPoly,
&TFr,
&TKZGSettings,
) -> Result<TFr, String>,
verify_kzg_proof: &dyn Fn(&TG1, &TFr, &TFr, &TG1, &TKZGSettings) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let mut rng = rand::thread_rng();
let z_fr = {
let z_bytes = generate_random_field_element_bytes(&mut rng);
TFr::from_bytes(&z_bytes).unwrap()
};
let blob = {
let blob_bytes = generate_random_blob_bytes(&mut rng);
bytes_to_blob(&blob_bytes).unwrap()
};
// Get a commitment to that particular blob
let commitment = blob_to_kzg_commitment(&blob, &ts).unwrap();
// Compute the proof
let (proof, computed_y) = compute_kzg_proof(&blob, &z_fr, &ts).unwrap();
// Now let's attempt to verify the proof
// First convert the blob to field elements
let poly = blob_to_polynomial(&blob).unwrap();
// Now evaluate the poly at `z` to learn `y`
let y_fr = evaluate_polynomial_in_evaluation_form(&poly, &z_fr, &ts).unwrap();
// Compare the recently evaluated y to the computed y
assert!(y_fr.equals(&computed_y));
// Finally verify the proof
let result = verify_kzg_proof(&commitment, &z_fr, &y_fr, &proof, &ts).unwrap();
assert!(result);
}
#[allow(clippy::type_complexity)]
pub fn compute_and_verify_kzg_proof_within_domain_test<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
compute_kzg_proof: &dyn Fn(&[TFr], &TFr, &TKZGSettings) -> Result<(TG1, TFr), String>,
blob_to_polynomial: &dyn Fn(&[TFr]) -> Result<TPoly, String>,
evaluate_polynomial_in_evaluation_form: &dyn Fn(
&TPoly,
&TFr,
&TKZGSettings,
) -> Result<TFr, String>,
verify_kzg_proof: &dyn Fn(&TG1, &TFr, &TFr, &TG1, &TKZGSettings) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let mut rng = rand::thread_rng();
for i in 0..25 {
let blob = {
let blob_bytes = generate_random_blob_bytes(&mut rng);
bytes_to_blob(&blob_bytes).unwrap()
};
// Get a commitment to that particular blob
let commitment = blob_to_kzg_commitment(&blob, &ts).unwrap();
// Get the polynomial version of the blob
let poly = blob_to_polynomial(&blob).unwrap();
// Compute the proof
let z_fr = ts.get_roots_of_unity_at(i);
let (proof, computed_y) = compute_kzg_proof(&blob, &z_fr, &ts).unwrap();
// Now evaluate the poly at `z` to learn `y`
let y_fr = evaluate_polynomial_in_evaluation_form(&poly, &z_fr, &ts).unwrap();
// Compare the recently evaluated y to the computed y
assert!(y_fr.equals(&computed_y));
// Finally verify the proof
let result = verify_kzg_proof(&commitment, &z_fr, &y_fr, &proof, &ts).unwrap();
assert!(result);
}
}
#[allow(clippy::type_complexity)]
pub fn compute_and_verify_kzg_proof_fails_with_incorrect_proof_test<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
compute_kzg_proof: &dyn Fn(&[TFr], &TFr, &TKZGSettings) -> Result<(TG1, TFr), String>,
blob_to_polynomial: &dyn Fn(&[TFr]) -> Result<TPoly, String>,
evaluate_polynomial_in_evaluation_form: &dyn Fn(
&TPoly,
&TFr,
&TKZGSettings,
) -> Result<TFr, String>,
verify_kzg_proof: &dyn Fn(&TG1, &TFr, &TFr, &TG1, &TKZGSettings) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let mut rng = rand::thread_rng();
let z_fr = {
let z_bytes = generate_random_field_element_bytes(&mut rng);
TFr::from_bytes(&z_bytes).unwrap()
};
let blob = {
let blob_bytes = generate_random_blob_bytes(&mut rng);
bytes_to_blob(&blob_bytes).unwrap()
};
// Get a commitment to that particular blob
let commitment = blob_to_kzg_commitment(&blob, &ts).unwrap();
// Compute the proof
let (mut proof, _) = compute_kzg_proof(&blob, &z_fr, &ts).unwrap();
// Now let's attempt to verify the proof
// First convert the blob to field elements
let poly = blob_to_polynomial(&blob).unwrap();
// Now evaluate the poly at `z` to learn `y`
let y_fr = evaluate_polynomial_in_evaluation_form(&poly, &z_fr, &ts).unwrap();
// Change the proof so it should not verify
proof = proof.add(&TG1::generator());
// Finally verify the proof
let result = verify_kzg_proof(&commitment, &z_fr, &y_fr, &proof, &ts).unwrap();
assert!(!result);
}
#[allow(clippy::type_complexity)]
pub fn compute_and_verify_blob_kzg_proof_test<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
compute_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TKZGSettings) -> Result<TG1, String>,
verify_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TG1, &TKZGSettings) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let mut rng = rand::thread_rng();
// Some preparation
let blob = {
let blob_bytes = generate_random_blob_bytes(&mut rng);
bytes_to_blob(&blob_bytes).unwrap()
};
// Compute the proof
let commitment = blob_to_kzg_commitment(&blob, &ts).unwrap();
let proof = compute_blob_kzg_proof(&blob, &commitment, &ts).unwrap();
// Finally verify the proof
let result = verify_blob_kzg_proof(&blob, &commitment, &proof, &ts).unwrap();
assert!(result);
}
#[allow(clippy::type_complexity)]
pub fn compute_and_verify_blob_kzg_proof_fails_with_incorrect_proof_test<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
compute_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TKZGSettings) -> Result<TG1, String>,
verify_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TG1, &TKZGSettings) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let mut rng = rand::thread_rng();
// Some preparation
let blob = {
let blob_bytes = generate_random_blob_bytes(&mut rng);
bytes_to_blob(&blob_bytes).unwrap()
};
// Compute the proof
let commitment = blob_to_kzg_commitment(&blob, &ts).unwrap();
let mut proof = compute_blob_kzg_proof(&blob, &commitment, &ts).unwrap();
// Change the proof so it should not verify
proof = proof.add(&TG1::generator());
// Finally verify the proof
let result = verify_blob_kzg_proof(&blob, &commitment, &proof, &ts).unwrap();
assert!(!result);
}
#[allow(clippy::type_complexity)]
pub fn verify_kzg_proof_batch_test<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
compute_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TKZGSettings) -> Result<TG1, String>,
verify_blob_kzg_proof_batch: &dyn Fn(
&[Vec<TFr>],
&[TG1],
&[TG1],
&TKZGSettings,
) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let mut rng = rand::thread_rng();
const N_SAMPLES: usize = 16;
let mut blobs: Vec<Vec<TFr>> = Vec::new();
let mut commitments: Vec<TG1> = Vec::new();
let mut proofs: Vec<TG1> = Vec::new();
// Some preparation
for _ in 0..N_SAMPLES {
let blob = {
let blob_bytes = generate_random_blob_bytes(&mut rng);
bytes_to_blob(&blob_bytes).unwrap()
};
let commitment = blob_to_kzg_commitment(&blob, &ts).unwrap();
let proof = compute_blob_kzg_proof(&blob, &commitment, &ts).unwrap();
blobs.push(blob);
commitments.push(commitment);
proofs.push(proof);
}
// Verify batched proofs for 0,1,2..16 blobs
// This should still work with zero blobs
for count in 0..(N_SAMPLES + 1) {
let result = verify_blob_kzg_proof_batch(
&blobs[0..count],
&commitments[0..count],
&proofs[0..count],
&ts,
)
.unwrap();
assert!(result);
}
}
#[allow(clippy::type_complexity)]
pub fn verify_kzg_proof_batch_fails_with_incorrect_proof_test<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
compute_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TKZGSettings) -> Result<TG1, String>,
verify_blob_kzg_proof_batch: &dyn Fn(
&[Vec<TFr>],
&[TG1],
&[TG1],
&TKZGSettings,
) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let mut rng = rand::thread_rng();
const N_SAMPLES: usize = 2;
let mut blobs: Vec<Vec<TFr>> = Vec::with_capacity(N_SAMPLES);
let mut commitments: Vec<TG1> = Vec::with_capacity(N_SAMPLES);
let mut proofs: Vec<TG1> = Vec::with_capacity(N_SAMPLES);
// Some preparation
for _ in 0..N_SAMPLES {
let blob = {
let blob_bytes = generate_random_blob_bytes(&mut rng);
bytes_to_blob(&blob_bytes).unwrap()
};
let commitment = blob_to_kzg_commitment(&blob, &ts).unwrap();
let proof = compute_blob_kzg_proof(&blob, &commitment, &ts).unwrap();
blobs.push(blob);
commitments.push(commitment);
proofs.push(proof);
}
// Overwrite second proof with an incorrect one
proofs[1] = proofs[0].clone();
let result = verify_blob_kzg_proof_batch(&blobs, &commitments, &proofs, &ts).unwrap();
assert!(!result);
}
const BLOB_TO_KZG_COMMITMENT_TESTS: &str = "src/test_vectors/blob_to_kzg_commitment/*/*/*";
const COMPUTE_KZG_PROOF_TESTS: &str = "src/test_vectors/compute_kzg_proof/*/*/*";
const COMPUTE_BLOB_KZG_PROOF_TESTS: &str = "src/test_vectors/compute_blob_kzg_proof/*/*/*";
const VERIFY_KZG_PROOF_TESTS: &str = "src/test_vectors/verify_kzg_proof/*/*/*";
const VERIFY_BLOB_KZG_PROOF_TESTS: &str = "src/test_vectors/verify_blob_kzg_proof/*/*/*";
const VERIFY_BLOB_KZG_PROOF_BATCH_TESTS: &str =
"src/test_vectors/verify_blob_kzg_proof_batch/*/*/*";
const COMPUTE_CHALLENGE_TEST_VECTORS: &str = "src/test_vectors/compute_challenge/*/*/*";
#[allow(clippy::type_complexity)]
pub fn test_vectors_blob_to_kzg_commitment<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
BLOB_TO_KZG_COMMITMENT_TESTS
))
.unwrap()
.map(Result::unwrap)
.collect();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file).unwrap();
let test: blob_to_kzg_commitment::Test = serde_yaml::from_str(&yaml_data).unwrap();
let blob = match bytes_to_blob(&test.input.get_blob_bytes()) {
Ok(blob) => blob,
Err(_) => {
assert!(test.get_output_bytes().is_none());
continue;
}
};
if (test.get_output_bytes().is_none()) {
continue;
}
let expected_commitment = {
let commitment_bytes = test.get_output_bytes().unwrap();
TG1::from_bytes(&commitment_bytes).unwrap()
};
let commitment = blob_to_kzg_commitment(&blob, &ts).unwrap();
assert!(commitment.equals(&expected_commitment));
}
}
#[allow(clippy::type_complexity)]
pub fn test_vectors_compute_kzg_proof<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
compute_kzg_proof: &dyn Fn(&[TFr], &TFr, &TKZGSettings) -> Result<(TG1, TFr), String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
COMPUTE_KZG_PROOF_TESTS
))
.unwrap()
.map(Result::unwrap)
.collect();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file).unwrap();
let test: compute_kzg_proof::Test = serde_yaml::from_str(&yaml_data).unwrap();
let input = (
match bytes_to_blob(&test.input.get_blob_bytes()) {
Ok(blob) => blob,
Err(_) => {
assert!(test.get_output_bytes().is_none());
continue;
}
},
match TFr::from_bytes(&test.input.get_z_bytes()) {
Ok(z) => z,
Err(_) => {
assert!(test.get_output_bytes().is_none());
continue;
}
},
);
let output = (
test.get_output_bytes()
.and_then(|bytes| TG1::from_bytes(&bytes.0).ok()), // proof
test.get_output_bytes()
.and_then(|bytes| TFr::from_bytes(&bytes.1).ok()), // y
);
// Compute the proof
let (proof, y) = compute_kzg_proof(&input.0, &input.1, &ts).unwrap();
// Compare the computed and expected proofs
assert!(proof.equals(&output.0.unwrap()));
// Compare the computed and expected ys
assert!(y.equals(&output.1.unwrap()));
}
}
#[allow(clippy::type_complexity)]
pub fn test_vectors_compute_blob_kzg_proof<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
compute_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TKZGSettings) -> Result<TG1, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
COMPUTE_BLOB_KZG_PROOF_TESTS
))
.unwrap()
.map(Result::unwrap)
.collect();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file).unwrap();
let test: compute_blob_kzg_proof::Test = serde_yaml::from_str(&yaml_data).unwrap();
let input = (
match bytes_to_blob(&test.input.get_blob_bytes()) {
Ok(blob) => blob,
Err(_) => {
assert!(test.get_output_bytes().is_none());
continue;
}
},
match TG1::from_bytes(&test.input.get_commitment_bytes()) {
Ok(commitment) => commitment,
Err(_) => {
assert!(test.get_output_bytes().is_none());
continue;
}
},
);
match compute_blob_kzg_proof(&input.0, &input.1, &ts) {
Ok(proof) => {
let expected_commitment = test
.get_output_bytes()
.and_then(|commitment_bytes| TG1::from_bytes(&commitment_bytes).ok());
assert!(
expected_commitment.is_some(),
"Expected that `compute_blob_kzg_proof` would throw an error, but it succeeded"
);
assert_eq!(proof, expected_commitment.unwrap());
}
Err(_) => {
assert!(test.get_output_bytes().is_none());
continue;
}
};
}
}
#[allow(clippy::type_complexity)]
pub fn test_vectors_verify_kzg_proof<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
verify_kzg_proof: &dyn Fn(&TG1, &TFr, &TFr, &TG1, &TKZGSettings) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
VERIFY_KZG_PROOF_TESTS
))
.unwrap()
.map(Result::unwrap)
.collect();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file).unwrap();
let test: verify_kzg_proof::Test = serde_yaml::from_str(&yaml_data).unwrap();
let input = (
match TG1::from_bytes(&test.input.get_commitment_bytes()) {
Ok(commitment) => commitment,
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
},
match TFr::from_bytes(&test.input.get_z_bytes()) {
Ok(z) => z,
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
},
match TFr::from_bytes(&test.input.get_y_bytes()) {
Ok(y) => y,
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
},
match TG1::from_bytes(&test.input.get_proof_bytes()) {
Ok(proof) => proof,
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
},
);
match verify_kzg_proof(&input.0, &input.1, &input.2, &input.3, &ts) {
Ok(result) => assert_eq!(result, test.get_output().unwrap()),
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
};
}
}
#[allow(clippy::type_complexity)]
pub fn test_vectors_verify_blob_kzg_proof<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
verify_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TG1, &TKZGSettings) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
VERIFY_BLOB_KZG_PROOF_TESTS
))
.unwrap()
.map(Result::unwrap)
.collect();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file).unwrap();
let test: verify_blob_kzg_proof::Test = serde_yaml::from_str(&yaml_data).unwrap();
let input = (
match bytes_to_blob(&test.input.get_blob_bytes()) {
Ok(blob) => blob,
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
},
match TG1::from_bytes(&test.input.get_commitment_bytes()) {
Ok(commitment) => commitment,
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
},
match TG1::from_bytes(&test.input.get_proof_bytes()) {
Ok(proof) => proof,
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
},
);
match verify_blob_kzg_proof(&input.0, &input.1, &input.2, &ts) {
Ok(result) => assert_eq!(result, test.get_output().unwrap()),
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
};
}
}
#[allow(clippy::type_complexity)]
pub fn test_vectors_verify_blob_kzg_proof_batch<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
verify_blob_kzg_proof_batch: &dyn Fn(
&[Vec<TFr>],
&[TG1],
&[TG1],
&TKZGSettings,
) -> Result<bool, String>,
) {
let ts = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
VERIFY_BLOB_KZG_PROOF_BATCH_TESTS
))
.unwrap()
.map(Result::unwrap)
.collect();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file).unwrap();
let test: verify_blob_kzg_proof_batch::Test = serde_yaml::from_str(&yaml_data).unwrap();
let mut skip_test = false;
let mut blobs = Vec::new();
let mut commitments = Vec::new();
let mut proofs = Vec::new();
for blob_bytes in test.input.get_blobs_bytes() {
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | true |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/kzg_proofs.rs | kzg-bench/src/tests/kzg_proofs.rs | use kzg::{
eth, EcBackend, FFTSettings, Fr, G1Affine, G1Fp, G1GetFp, G1LinComb, G1Mul, G1ProjAddAffine,
KZGSettings, Poly, G1, G2,
};
pub const SECRET: [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,
];
/// Check that generate_trusted_setup function returns trusted setup in correct form
#[allow(clippy::type_complexity)]
pub fn trusted_setup_in_correct_form<B: EcBackend>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) where
B::Fr: Copy,
{
let (s1, s2, s3) = generate_trusted_setup(8, SECRET);
let fs = B::FFTSettings::new(3).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 3).unwrap();
let poly = B::Poly::from_coeffs(
&[6, 28, 31, 85, 30, 71, 79, 58]
.into_iter()
.map(B::Fr::from_u64)
.collect::<Vec<_>>(),
);
let evaluations = fs
.get_roots_of_unity()
.iter()
.map(|v| poly.eval(v))
.collect::<Vec<_>>();
let left = B::G1::g1_lincomb(ks.get_g1_monomial(), poly.get_coeffs(), 8, None);
let right = B::G1::g1_lincomb(ks.get_g1_lagrange_brp(), &evaluations, 8, None);
assert_eq!(left, right);
}
/// Check that both FFT implementations produce the same results
#[allow(clippy::type_complexity)]
pub fn proof_single<B: EcBackend>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) where
B::Fr: Copy,
{
// Our polynomial: degree 14, 15 coefficients
let coeffs = [1, 2, 3, 4, 7, 7, 7, 7, 13, 13, 13, 13, 13, 13, 13];
let poly_len = coeffs.len();
let secrets_len = poly_len + 1;
// Create the polynomial
let mut p = B::Poly::new(poly_len);
for (x, &coeff) in coeffs.iter().enumerate() {
p.set_coeff_at(x, &B::Fr::from_u64(coeff));
}
// Initialise the secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = B::FFTSettings::new(4).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 4).unwrap();
// Compute the proof for x = 25
let x = B::Fr::from_u64(25);
let commitment = ks.commit_to_poly(&p).unwrap();
let proof = ks.compute_proof_single(&p, &x).unwrap();
let mut value = p.eval(&x);
// Verify the proof that the (unknown) polynomial has y = value at x = 25
assert!(ks
.check_proof_single(&commitment, &proof, &x, &value)
.unwrap());
// Change the value and check that the proof fails
value = value.add(&B::Fr::one());
assert!(!ks
.check_proof_single(&commitment, &proof, &x, &value)
.unwrap());
}
#[allow(clippy::type_complexity)]
pub fn commit_to_nil_poly<B: EcBackend>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
{
let secrets_len = 16;
// Initialise the (arbitrary) secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = B::FFTSettings::new(4).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 8).unwrap();
let a = B::Poly::new(0);
let result = ks.commit_to_poly(&a).unwrap();
assert!(result.equals(&B::G1::default()));
}
}
//Test is made to panic so put this under #[test]
//#[should_panic(expected = "Poly given is too long")]
#[allow(clippy::type_complexity)]
pub fn commit_to_too_long_poly<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<TG1>, Vec<TG1>, Vec<TG2>),
) {
{
let secrets_len = 16;
let poly_len = 32; // poly is longer than secrets!
// Initialise the (arbitrary) secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = TFFTSettings::new(4).unwrap();
let ks = TKZGSettings::new(&s1, &s2, &s3, &fs, eth::FIELD_ELEMENTS_PER_CELL).unwrap();
let a = TPoly::new(poly_len);
let _result = ks.commit_to_poly(&a);
}
}
// Instead of panicking, commit should return an err
#[allow(clippy::type_complexity)]
pub fn commit_to_too_long_poly_returns_err<B: EcBackend>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
let secrets_len = 16;
let poly_len = 32; // poly is longer than secrets!
// Initialise the (arbitrary) secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = B::FFTSettings::new(4).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 8).unwrap();
let a = B::Poly::new(poly_len);
let _result = ks.commit_to_poly(&a);
assert!(_result.is_err());
}
//It was not verified that this test works, use with caution
#[allow(clippy::type_complexity)]
pub fn proof_multi<B: EcBackend>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
// Our polynomial: degree 14, 15 coefficients
let coeffs = [1, 2, 3, 4, 7, 7, 7, 7, 13, 13, 13, 13, 13, 13, 13];
let poly_len = coeffs.len();
// Compute proof at 2^coset_scale points
let coset_scale = 3;
let coset_len = 1 << coset_scale;
let mut y: Vec<B::Fr> = Vec::new();
let secrets_len = if poly_len > coset_len {
poly_len + 1
} else {
coset_len + 1
};
// Create the polynomial
let mut p = B::Poly::new(poly_len);
for (x, &coeff) in coeffs.iter().enumerate() {
p.set_coeff_at(x, &B::Fr::from_u64(coeff));
}
// Initialise the secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs1 = B::FFTSettings::new(4).unwrap();
let ks1 = B::KZGSettings::new(&s1, &s2, &s3, &fs1, 7).unwrap();
// Commit to the polynomial
let commitment = ks1.commit_to_poly(&p).unwrap();
let fs2 = B::FFTSettings::new(coset_scale).unwrap();
let ks2 = B::KZGSettings::new(&s1, &s2, &s3, &fs2, 7).unwrap();
// Compute proof at the points [x * root_i] 0 <= i < coset_len
let x = B::Fr::from_u64(5431);
let proof = ks2.compute_proof_multi(&p, &x, coset_len).unwrap();
// y_i is the value of the polynomial at each x_i
for i in 0..coset_len {
let tmp = B::Fr::mul(&x, &ks2.get_roots_of_unity_at(i));
y.push(p.eval(&tmp));
}
// Verify the proof that the (unknown) polynomial has value y_i at x_i
let result = ks2
.check_proof_multi(&commitment, &proof, &x, &y, coset_len)
.unwrap();
assert!(result);
// Change a value and check that the proof fails
let temp = B::Fr::add(&y[4], &B::Fr::one());
let _temp = std::mem::replace(&mut y[4], temp);
let result = ks2
.check_proof_multi(&commitment, &proof, &x, &y, coset_len)
.unwrap();
assert!(!result);
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/eip_7594.rs | kzg-bench/src/tests/eip_7594.rs | use super::utils::{get_manifest_dir, get_trusted_setup_path};
use crate::test_vectors::{
compute_cells, compute_cells_and_kzg_proofs, compute_verify_cell_kzg_proof_batch_challenge,
recover_cells_and_kzg_proofs, verify_cell_kzg_proof_batch,
};
use kzg::{
eth::{self, FIELD_ELEMENTS_PER_CELL},
EcBackend, Fr, DAS, G1,
};
use std::{fs, path::PathBuf};
const COMPUTE_CELLS_AND_KZG_PROOFS_TEST_VECTORS: &str =
"src/test_vectors/compute_cells_and_kzg_proofs/*/*/*";
const COMPUTE_CELLS_TEST_VECTORS: &str = "src/test_vectors/compute_cells/*/*/*";
const RECOVER_CELLS_AND_KZG_PROOFS_TEST_VECTORS: &str =
"src/test_vectors/recover_cells_and_kzg_proofs/*/*/*";
const VERIFY_CELL_KZG_PROOF_BATCH_TEST_VECTORS: &str =
"src/test_vectors/verify_cell_kzg_proof_batch/*/*/*";
const COMPUTE_VERIFY_CELL_KZG_PROOF_BATCH_CHALLENGE: &str =
"src/test_vectors/compute_verify_cell_kzg_proof_batch_challenge/*/*/*";
#[allow(clippy::type_complexity)]
pub fn test_vectors_compute_cells_and_kzg_proofs<B: EcBackend>(
load_trusted_setup: &dyn Fn(&str) -> Result<B::KZGSettings, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<B::Fr>, String>,
) {
let settings = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
COMPUTE_CELLS_AND_KZG_PROOFS_TEST_VECTORS
))
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file.clone()).unwrap();
let test: compute_cells_and_kzg_proofs::Test = serde_yaml::from_str(&yaml_data).unwrap();
let blob = match bytes_to_blob(&test.input.get_blob_bytes().unwrap()) {
Ok(blob) => blob,
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
};
let mut recv_cells =
vec![B::Fr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
let mut recv_proofs = vec![B::G1::default(); eth::CELLS_PER_EXT_BLOB];
match <B::KZGSettings as DAS<B>>::compute_cells_and_kzg_proofs(
&settings,
Some(&mut recv_cells),
Some(&mut recv_proofs),
&blob,
) {
Err(_) => assert!(test.get_output().is_none()),
Ok(()) => {
let (exp_cells, exp_proofs) = test.get_output().unwrap();
let recv_cells = recv_cells
.chunks(FIELD_ELEMENTS_PER_CELL)
.map(|it| it.iter().flat_map(|it| it.to_bytes()).collect::<Vec<_>>())
.collect::<Vec<Vec<u8>>>();
let recv_proofs = recv_proofs
.into_iter()
.map(|it| it.to_bytes().to_vec())
.collect::<Vec<Vec<u8>>>();
assert!(
recv_cells == exp_cells,
"Cells do not match, for test vector {:?}",
test_file
);
assert!(
recv_proofs == exp_proofs,
"Proofs do not match, for test vector {:?}",
test_file
);
}
}
}
}
#[allow(clippy::type_complexity)]
pub fn test_vectors_compute_cells<B: EcBackend>(
load_trusted_setup: &dyn Fn(&str) -> Result<B::KZGSettings, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<B::Fr>, String>,
) {
let settings = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
COMPUTE_CELLS_TEST_VECTORS
))
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file.clone()).unwrap();
let test: compute_cells::Test = serde_yaml::from_str(&yaml_data).unwrap();
let blob = match bytes_to_blob(&test.input.get_blob_bytes().unwrap()) {
Ok(blob) => blob,
Err(_) => {
assert!(test.get_output().is_none());
continue;
}
};
let mut recv_cells =
vec![B::Fr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
match <B::KZGSettings as DAS<B>>::compute_cells_and_kzg_proofs(
&settings,
Some(&mut recv_cells),
None,
&blob,
) {
Err(_) => assert!(test.get_output().is_none()),
Ok(()) => {
let exp_cells = test.get_output().unwrap();
let recv_cells = recv_cells
.chunks(FIELD_ELEMENTS_PER_CELL)
.map(|it| it.iter().flat_map(|it| it.to_bytes()).collect::<Vec<_>>())
.collect::<Vec<Vec<u8>>>();
assert!(
recv_cells == exp_cells,
"Cells do not match, for test vector {:?}",
test_file
);
}
}
}
}
#[allow(clippy::type_complexity)]
pub fn test_vectors_recover_cells_and_kzg_proofs<B: EcBackend>(
load_trusted_setup: &dyn Fn(&str) -> Result<B::KZGSettings, String>,
) {
let settings = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
RECOVER_CELLS_AND_KZG_PROOFS_TEST_VECTORS
))
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file.clone()).unwrap();
let test: recover_cells_and_kzg_proofs::Test = serde_yaml::from_str(&yaml_data).unwrap();
let cells = match test
.input
.get_cell_bytes()
.unwrap()
.iter()
.flat_map(|bytes| {
bytes
.chunks(eth::BYTES_PER_FIELD_ELEMENT)
.map(B::Fr::from_bytes)
})
.collect::<Result<Vec<_>, _>>()
{
Ok(v) => v,
Err(err) => {
// c-kzg-4844 also includes tests with invalid byte count for cell
// in rust-kzg, these checks are performed outside of recovery function,
// while parsing data (in c bindings, for example). These tests will be
// additionally checked through rust-kzg c binding tests.
// We add here assertion, to avoid accidentally skipping valid test case
assert!(
test.get_output().is_none(),
"Parsing input failed with error {err:?}, for test vector {test_file:?}",
);
continue;
}
};
let mut recv_cells =
vec![B::Fr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
let mut recv_proofs = vec![B::G1::default(); eth::CELLS_PER_EXT_BLOB];
match <B::KZGSettings as DAS<B>>::recover_cells_and_kzg_proofs(
&settings,
&mut recv_cells,
Some(&mut recv_proofs),
&test.input.get_cell_indices().unwrap().iter().map(|it| (*it).into()).collect::<Vec<_>>(),
&cells,
) {
Err(err) => assert!(test.get_output().is_none(), "Should correctly recover cells, but failed with error {err:?}, for test vector {test_file:?}"),
Ok(()) => {
let test_output = test.get_output();
assert!(test_output.is_some(), "Should fail, but succeeded for test vector {test_file:?}");
let (exp_cells, exp_proofs) = test_output.unwrap();
let recv_cells = recv_cells
.chunks(eth::FIELD_ELEMENTS_PER_CELL)
.map(|it| it.iter().flat_map(|it| it.to_bytes()).collect::<Vec<_>>())
.collect::<Vec<Vec<u8>>>();
let recv_proofs = recv_proofs
.into_iter()
.map(|it| it.to_bytes().to_vec())
.collect::<Vec<Vec<u8>>>();
assert!(
recv_cells == exp_cells,
"Cells do not match, for test vector {test_file:?}",
);
assert!(
recv_proofs == exp_proofs,
"Proofs do not match, for test vector {:?}",
test_file
);
}
}
}
}
#[allow(clippy::type_complexity)]
pub fn test_vectors_verify_cell_kzg_proof_batch<B: EcBackend>(
load_trusted_setup: &dyn Fn(&str) -> Result<B::KZGSettings, String>,
) {
let settings = load_trusted_setup(get_trusted_setup_path().as_str()).unwrap();
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
VERIFY_CELL_KZG_PROOF_BATCH_TEST_VECTORS
))
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file.clone()).unwrap();
let test: verify_cell_kzg_proof_batch::Test = serde_yaml::from_str(&yaml_data).unwrap();
let cells = match test
.input
.get_cell_bytes()
.unwrap()
.iter()
.flat_map(|bytes| {
bytes
.chunks(eth::BYTES_PER_FIELD_ELEMENT)
.map(B::Fr::from_bytes)
})
.collect::<Result<Vec<_>, _>>()
{
Ok(v) => v,
Err(err) => {
// c-kzg-4844 also includes tests with invalid byte count for cell
// in rust-kzg, these checks are performed outside of recovery function,
// while parsing data (in c bindings, for example). These tests will be
// additionally checked through rust-kzg c binding tests.
// We add here assertion, to avoid accidentally skipping valid test case
assert!(
test.get_output().is_none(),
"Parsing input failed with error {err:?}, for test vector {test_file:?}",
);
continue;
}
};
let commitments = match test
.input
.get_commitment_bytes()
.unwrap()
.iter()
.map(|bytes| B::G1::from_bytes(bytes))
.collect::<Result<Vec<_>, _>>()
{
Ok(v) => v,
Err(err) => {
// c-kzg-4844 also includes tests with invalid byte count for cell
// in rust-kzg, these checks are performed outside of recovery function,
// while parsing data (in c bindings, for example). These tests will be
// additionally checked through rust-kzg c binding tests.
// We add here assertion, to avoid accidentally skipping valid test case
assert!(
test.get_output().is_none(),
"Parsing input failed with error {err:?}, for test vector {test_file:?}",
);
continue;
}
};
let proofs = match test
.input
.get_proof_bytes()
.unwrap()
.iter()
.map(|bytes| B::G1::from_bytes(bytes))
.collect::<Result<Vec<_>, _>>()
{
Ok(v) => v,
Err(err) => {
// c-kzg-4844 also includes tests with invalid byte count for cell
// in rust-kzg, these checks are performed outside of recovery function,
// while parsing data (in c bindings, for example). These tests will be
// additionally checked through rust-kzg c binding tests.
// We add here assertion, to avoid accidentally skipping valid test case
assert!(
test.get_output().is_none(),
"Parsing input failed with error {err:?}, for test vector {test_file:?}",
);
continue;
}
};
let cell_indices = test.input.get_cell_indices().unwrap();
match <B::KZGSettings as DAS<B>>::verify_cell_kzg_proof_batch(
&settings,
&commitments,
&cell_indices,
&cells,
&proofs,
) {
Err(err) => assert!(test.get_output().is_none(), "Should correctly verify cells, but failed with error {err:?}, for test vector {test_file:?}"),
Ok(value) => {
let test_output = test.get_output();
assert!(test_output.is_some(), "Should fail, but succeeded for test vector {test_file:?}");
assert_eq!(value, test_output.unwrap(), "Test vector failed {test_file:?}");
}
}
}
}
#[allow(clippy::type_complexity)]
pub fn test_vectors_compute_verify_cell_kzg_proof_batch_challenge<B: EcBackend>() {
let test_files: Vec<PathBuf> = glob::glob(&format!(
"{}/{}",
get_manifest_dir(),
COMPUTE_VERIFY_CELL_KZG_PROOF_BATCH_CHALLENGE
))
.unwrap()
.collect::<Result<Vec<_>, _>>()
.unwrap();
assert!(!test_files.is_empty());
for test_file in test_files {
let yaml_data = fs::read_to_string(test_file.clone()).unwrap();
let test: compute_verify_cell_kzg_proof_batch_challenge::Test =
serde_yaml::from_str(&yaml_data).unwrap();
let commitments = match test
.input
.get_commitment_bytes()
.unwrap()
.iter()
.map(|bytes| B::G1::from_bytes(bytes))
.collect::<Result<Vec<_>, _>>()
{
Ok(v) => v,
Err(err) => {
// c-kzg-4844 also includes tests with invalid byte count for cell
// in rust-kzg, these checks are performed outside of recovery function,
// while parsing data (in c bindings, for example). These tests will be
// additionally checked through rust-kzg c binding tests.
// We add here assertion, to avoid accidentally skipping valid test case
assert!(
test.get_output_bytes().is_none(),
"Parsing input failed with error {err:?}, for test vector {test_file:?}",
);
continue;
}
};
let commitment_indices = test.input.get_commitment_indices().unwrap();
let cell_indices = test.input.get_cell_indices().unwrap();
let cells = match test
.input
.get_coset_eval_bytes()
.unwrap()
.iter()
.flat_map(|elements| elements.iter().map(|b| B::Fr::from_bytes(b.as_slice())))
.collect::<Result<Vec<_>, _>>()
{
Ok(v) => v,
Err(err) => {
// c-kzg-4844 also includes tests with invalid byte count for cell
// in rust-kzg, these checks are performed outside of recovery function,
// while parsing data (in c bindings, for example). These tests will be
// additionally checked through rust-kzg c binding tests.
// We add here assertion, to avoid accidentally skipping valid test case
assert!(
test.get_output_bytes().is_none(),
"Parsing input failed with error {err:?}, for test vector {test_file:?}",
);
continue;
}
};
let proofs = match test
.input
.get_proof_bytes()
.unwrap()
.iter()
.map(|bytes| B::G1::from_bytes(bytes))
.collect::<Result<Vec<_>, _>>()
{
Ok(v) => v,
Err(err) => {
// c-kzg-4844 also includes tests with invalid byte count for cell
// in rust-kzg, these checks are performed outside of recovery function,
// while parsing data (in c bindings, for example). These tests will be
// additionally checked through rust-kzg c binding tests.
// We add here assertion, to avoid accidentally skipping valid test case
assert!(
test.get_output_bytes().is_none(),
"Parsing input failed with error {err:?}, for test vector {test_file:?}",
);
continue;
}
};
match <B::KZGSettings as DAS<B>>::compute_verify_cell_kzg_proof_batch_challenge(
kzg::eth::FIELD_ELEMENTS_PER_CELL,
&commitments,
&commitment_indices,
&cell_indices,
&cells,
&proofs,
kzg::eth::FIELD_ELEMENTS_PER_BLOB,
) {
Err(err) => assert!(test.get_output_bytes().is_none(), "Should correctly verify cells, but failed with error {err:?}, for test vector {test_file:?}"),
Ok(value) => {
let test_output = test.get_output_bytes();
let res_output = value.to_bytes();
assert!(test_output.is_some(), "Should fail, but succeeded for test vector {test_file:?}");
assert_eq!(res_output.as_slice(), test_output.unwrap().as_slice(), "Test vector failed {test_file:?}");
}
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/poly.rs | kzg-bench/src/tests/poly.rs | use kzg::{FFTSettings, FFTSettingsPoly, Fr, Poly};
use rand::rngs::StdRng;
use rand::{RngCore, SeedableRng};
pub fn create_poly_of_length_ten<TFr: Fr, TPoly: Poly<TFr>>() {
let poly = TPoly::new(10);
assert_eq!(poly.len(), 10);
}
pub fn poly_eval_check<TFr: Fr, TPoly: Poly<TFr>>() {
let n: usize = 10;
let mut poly = TPoly::new(n);
for i in 0..n {
let fr = TFr::from_u64((i + 1) as u64);
poly.set_coeff_at(i, &fr);
}
let expected = TFr::from_u64((n * (n + 1) / 2) as u64);
let actual = poly.eval(&TFr::one());
assert!(expected.equals(&actual));
}
pub fn poly_eval_0_check<TFr: Fr, TPoly: Poly<TFr>>() {
let n: usize = 7;
let a: usize = 597;
let mut poly = TPoly::new(n);
for i in 0..n {
let fr = TFr::from_u64((i + a) as u64);
poly.set_coeff_at(i, &fr);
}
let expected = TFr::from_u64(a as u64);
let actual = poly.eval(&TFr::zero());
assert!(expected.equals(&actual));
}
pub fn poly_eval_nil_check<TFr: Fr, TPoly: Poly<TFr>>() {
let n: usize = 0;
let poly = TPoly::new(n);
let actual = poly.eval(&TFr::one());
assert!(actual.equals(&TFr::zero()));
}
pub fn poly_inverse_simple_0<TFr: Fr, TPoly: Poly<TFr>>() {
// 1 / (1 - x) = 1 + x + x^2 + ...
let d: usize = 16;
let mut p = TPoly::new(2);
p.set_coeff_at(0, &TFr::one());
p.set_coeff_at(1, &TFr::one());
p.set_coeff_at(1, &TFr::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<TFr: Fr, TPoly: Poly<TFr>>() {
// 1 / (1 + x) = 1 - x + x^2 - ...
let d: usize = 16;
let mut p = TPoly::new(2);
p.set_coeff_at(0, &TFr::one());
p.set_coeff_at(1, &TFr::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 = TFr::negate(&tmp);
}
assert!(tmp.is_one());
}
}
fn test_data(a: usize, b: usize) -> Vec<i32> {
// (x^2 - 1) / (x + 1) = x - 1
let test_0_0: Vec<i32> = vec![-1, 0, 1];
let test_0_1: Vec<i32> = vec![1, 1];
let test_0_2: Vec<i32> = vec![-1, 1];
// (12x^3 - 11x^2 + 9x + 18) / (4x + 3) = 3x^2 - 5x + 6
let test_1_0: Vec<i32> = vec![18, 9, -11, 12];
let test_1_1: Vec<i32> = vec![3, 4];
let test_1_2: Vec<i32> = vec![6, -5, 3];
// (x + 1) / (x^2 - 1) = nil
let test_2_0: Vec<i32> = vec![1, 1];
let test_2_1: Vec<i32> = vec![-1, 0, 2];
let test_2_2: Vec<i32> = vec![];
// (10x^2 + 20x + 30) / 10 = x^2 + 2x + 3
let test_3_0: Vec<i32> = vec![30, 20, 10];
let test_3_1: Vec<i32> = vec![10];
let test_3_2: Vec<i32> = vec![3, 2, 1];
// (x^2 + x) / (x + 1) = x
let test_4_0: Vec<i32> = vec![0, 1, 1];
let test_4_1: Vec<i32> = vec![1, 1];
let test_4_2: Vec<i32> = vec![0, 1];
// (x^2 + x + 1) / 1 = x^2 + x + 1
let test_5_0: Vec<i32> = vec![1, 1, 1];
let test_5_1: Vec<i32> = vec![1];
let test_5_2: Vec<i32> = vec![1, 1, 1];
// (x^2 + x + 1) / (0x + 1) = x^2 + x + 1
let test_6_0: Vec<i32> = vec![1, 1, 1];
let test_6_1: Vec<i32> = vec![1, 0]; // The highest coefficient is zero
let test_6_2: Vec<i32> = vec![1, 1, 1];
let test_data: [[Vec<i32>; 3]; 7] = [
[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_data[a][b].clone()
}
fn new_test_poly<TFr: Fr, TPoly: Poly<TFr>>(coeffs: &[i32]) -> TPoly {
let mut p = TPoly::new(coeffs.len());
for (i, &coeff) in coeffs.iter().enumerate() {
if coeff >= 0 {
let c = TFr::from_u64(coeff as u64);
p.set_coeff_at(i, &c);
} else {
let c = TFr::from_u64((-coeff) as u64);
let negc = c.negate();
p.set_coeff_at(i, &negc);
}
}
p
}
pub fn poly_test_div<TFr: Fr, TPoly: Poly<TFr>>() {
for i in 0..6 {
let divided_data = test_data(i, 0);
let divisor_data = test_data(i, 1);
let expected_data = test_data(i, 2);
let mut dividend: TPoly = new_test_poly(÷d_data);
let divisor: TPoly = new_test_poly(&divisor_data);
let expected: TPoly = new_test_poly(&expected_data);
let result = dividend.div(&divisor);
assert!(result.is_ok());
let actual = result.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_by_zero<TFr: Fr, TPoly: Poly<TFr>>() {
//Arrange
let coeffs: Vec<i32> = vec![1, 1];
let mut dividend: TPoly = new_test_poly(&coeffs);
let divisor = TPoly::new(0);
//Act
let result = dividend.div(&divisor);
//Assert
assert!(result.is_err());
}
pub fn poly_mul_direct_test<TFr: Fr, TPoly: Poly<TFr>>() {
let coeffs0: Vec<i32> = vec![3, 4];
let mut multiplicand: TPoly = new_test_poly(&coeffs0);
let coeffs1: Vec<i32> = vec![6, -5, 3];
let mut multiplier: TPoly = new_test_poly(&coeffs1);
let coeffs2: Vec<i32> = vec![18, 9, -11, 12];
let expected: TPoly = new_test_poly(&coeffs2);
let result0 = multiplicand.mul_direct(&multiplier, 4);
assert!(result0.is_ok());
let actual0 = result0.unwrap();
for i in 0..actual0.len() {
assert!(expected.get_coeff_at(i).equals(&actual0.get_coeff_at(i)))
}
//Check commutativity
let result1 = multiplier.mul_direct(&multiplicand, 4);
assert!(result1.is_ok());
let actual1 = result1.unwrap();
for i in 0..actual1.len() {
assert!(expected.get_coeff_at(i).equals(&actual1.get_coeff_at(i)))
}
}
pub fn poly_mul_fft_test<
TFr: Fr,
TPoly: Poly<TFr>,
TFTTSettings: FFTSettings<TFr> + FFTSettingsPoly<TFr, TPoly, TFTTSettings>,
>() {
let coeffs: Vec<i32> = vec![3, 4];
let multiplicand: TPoly = new_test_poly(&coeffs);
let coeffs: Vec<i32> = vec![6, -5, 3];
let multiplier: TPoly = new_test_poly(&coeffs);
let coeffs: Vec<i32> = vec![18, 9, -11, 12];
let expected: TPoly = new_test_poly(&coeffs);
let result0 = TFTTSettings::poly_mul_fft(&multiplicand, &multiplier, 4, None);
assert!(result0.is_ok());
let actual0 = result0.unwrap();
for i in 0..actual0.len() {
assert!(expected.get_coeff_at(i).equals(&actual0.get_coeff_at(i)))
}
//Check commutativity
let result1 = TFTTSettings::poly_mul_fft(&multiplier, &multiplicand, 4, None);
assert!(result1.is_ok());
let actual1 = result1.unwrap();
for i in 0..actual1.len() {
assert!(expected.get_coeff_at(i).equals(&actual1.get_coeff_at(i)))
}
}
pub fn poly_mul_random<
TFr: Fr,
TPoly: Poly<TFr>,
TFTTSettings: FFTSettings<TFr> + FFTSettingsPoly<TFr, TPoly, TFTTSettings>,
>() {
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 multiplier_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let out_length: usize = (1 + (rng.next_u64() % 1000)) as usize;
let mut multiplicand = TPoly::new(multiplicand_length);
let mut multiplier = TPoly::new(multiplier_length);
for i in 0..multiplicand_length {
let coef = TFr::rand();
multiplicand.set_coeff_at(i, &coef);
}
for i in 0..multiplier_length {
let coef = TFr::rand();
multiplier.set_coeff_at(i, &coef);
}
//Ensure that the polynomials' orders corresponds to their lengths
if multiplicand.get_coeff_at(multiplicand.len() - 1).is_zero() {
let fr_one = Fr::one();
multiplicand.set_coeff_at(multiplicand.len() - 1, &fr_one);
}
if multiplier.get_coeff_at(multiplier.len() - 1).is_zero() {
let fr_one = Fr::one();
multiplier.set_coeff_at(multiplier.len() - 1, &fr_one);
}
let result0 = multiplicand.mul_direct(&multiplier, out_length);
assert!(result0.is_ok());
let result1 = TFTTSettings::poly_mul_fft(&multiplicand, &multiplier, out_length, None);
assert!(result1.is_ok());
let actual0 = result0.unwrap();
let actual1 = result1.unwrap();
assert_eq!(actual0.len(), actual1.len());
for i in 0..actual0.len() {
assert!(actual0.get_coeff_at(i).equals(&actual1.get_coeff_at(i)));
}
}
}
pub fn poly_div_random<TFr: Fr, TPoly: Poly<TFr>>() {
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 = TPoly::new(dividend_length);
let mut divisor = TPoly::new(divisor_length);
for i in 0..dividend_length {
let coef = TFr::rand();
dividend.set_coeff_at(i, &coef);
}
for i in 0..divisor_length {
let coef = TFr::rand();
divisor.set_coeff_at(i, &coef);
}
//Ensure that the polynomials' orders corresponds to their lengths
if dividend.get_coeff_at(dividend.len() - 1).is_zero() {
let fr_one = Fr::one();
dividend.set_coeff_at(dividend.len() - 1, &fr_one);
}
if divisor.get_coeff_at(divisor.len() - 1).is_zero() {
let fr_one = Fr::one();
divisor.set_coeff_at(divisor.len() - 1, &fr_one);
}
let result0 = dividend.long_div(&divisor);
assert!(result0.is_ok());
let result1 = dividend.fast_div(&divisor);
assert!(result1.is_ok());
let actual0 = result0.unwrap();
let actual1 = result1.unwrap();
assert_eq!(actual0.len(), actual1.len());
for i in 0..actual0.len() {
assert!(actual0.get_coeff_at(i).equals(&actual1.get_coeff_at(i)));
}
}
}
pub fn poly_div_long_test<TFr: Fr, TPoly: Poly<TFr>>() {
for i in 0..7 {
// 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: TPoly = new_test_poly(÷d_data);
let divisor: TPoly = new_test_poly(&divisor_data);
let expected: TPoly = 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<TFr: Fr, TPoly: Poly<TFr>>() {
for i in 0..7 {
// 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: TPoly = new_test_poly(÷d_data);
let divisor: TPoly = new_test_poly(&divisor_data);
let expected: TPoly = 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)))
}
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/zero_poly.rs | kzg-bench/src/tests/zero_poly.rs | use kzg::{FFTFr, FFTSettings, Fr, Poly, ZeroPoly};
use rand::rngs::StdRng;
use rand::seq::SliceRandom;
use rand::{thread_rng, RngCore, SeedableRng};
#[rustfmt::skip]
const EXISTS: [bool; 16] = [
true, false, false, true,
false, true, true, false,
false, false, true, true,
false, true, false, true,
];
#[rustfmt::skip]
const EXPECTED_EVAL_U64: [[u64; 4]; 16] = [
[0xfd5a5130b97ce0c3, 0xb4748a4cb0f90e6d, 0x12a1ab34b25b18c1, 0x5a5ac0c81c9f7ea8],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0xaa385cbce3dd1657, 0x2fdab57a38bdb514, 0x20e022e205dafa53, 0x14077dd3f5d996b1],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x194018614b6f7276, 0xdf2b18f870532376, 0x1ff427cd5b583fe6, 0x014d6444ff03dd09],
[0xcc84c2de684c0dde, 0xf1e7ab32aa830d02, 0x967bf35a2a691f20, 0x046109731cdf0d3c],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x96cddd2924212afb, 0xeaa4c1f51421d8d8, 0x3ae969cfa34d0ed1, 0x6b6c5e876bc3916d],
[0x449310802f74ad49, 0x47c940979163037a, 0x10d311564afb9b2a, 0x269b8531c369bafb],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0xd9af75fe35c16cf1, 0x068bb140cea92f75, 0xe769811965e10a47, 0x48ed97e6745612f2],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x7ef1f59bb1677685, 0x33a637296680e8ce, 0xaaf62b3f6e016709, 0x454a299178a4dba9]];
#[rustfmt::skip]
const EXPECTED_POLY_U64: [[u64; 4]; 16] = [
[0xac159e2688bd4333, 0x3bfef0f00df2ec88, 0x561dcd0fd4d314d9, 0x533bd8c1e977024e],
[0x18bc6eedc010ef8d, 0xc731a3eb4ea2ab70, 0x5c2589357ae121a8, 0x04f9108d308f7016],
[0x232759f49556ac08, 0x9776fe2e9f4c613c, 0x74d5bed4eb2de960, 0x1f6cf6719bfa0e68],
[0xf2f3461e8ab1ae34, 0xeb220fcc11ef1c80, 0x7a4637d3a637739b, 0x19901a58cd177c53],
[0x9340f62465a1f4fe, 0xd9cb3ea6de494a11, 0xee92ebc763cdff5d, 0x5443e89811b5b9f5],
[0x269a255e2e4e48a4, 0xfadae7a89d9b2f2b, 0xb5515799b41e1a88, 0x2e990979a0ffcee5],
[0x1c2f3a5759088c29, 0x2a958d654cf1795f, 0x9ca121fa43d152d1, 0x1425239535953093],
[0x4c634e2d63ad89fd, 0xd6ea7bc7da4ebe1a, 0x9730a8fb88c7c895, 0x1a01ffae0477c2a8],
[0x0000000000000001, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000],
[0x0000000000000000, 0x0000000000000000, 0x0000000000000000, 0x0000000000000000]];
/// First, create polynomials that evaluate to zero at given roots.
/// Check that multiplying them together (via reduce_partials) equals
/// constructing a polynomial that evaluates to zero at all given roots.
pub fn test_reduce_partials<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + ZeroPoly<TFr, TPoly>,
TPoly: Poly<TFr>,
>() {
let fft_settings = TFFTSettings::new(4).unwrap();
let partial_idxs: [[usize; 2]; 4] = [[1, 3], [7, 8], [9, 10], [12, 13]];
let mut poly_partials = Vec::new();
for partial_idxs in partial_idxs.iter() {
let temp = fft_settings
.do_zero_poly_mul_partial(partial_idxs, 1)
.unwrap();
poly_partials.push(temp);
}
let from_tree_reduction = fft_settings.reduce_partials(16, &poly_partials).unwrap();
let idxs = [1, 3, 7, 8, 9, 10, 12, 13];
let from_direct = fft_settings.do_zero_poly_mul_partial(&idxs, 1).unwrap();
for i in 0..9 {
from_tree_reduction
.get_coeff_at(i)
.equals(&from_direct.get_coeff_at(i));
}
}
/// Create random partial polynomials that equal 0 at given roots.
/// Check that multiplying them together (via reduce_partials) equals
/// constructing a polynomial that evaluates to zero at all given roots.
pub fn reduce_partials_random<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + ZeroPoly<TFr, TPoly>,
TPoly: Poly<TFr>,
>() {
for scale in 5..13 {
for ii in 1..8 {
let missing_ratio = 0.1 * ii as f32;
let fft_settings = TFFTSettings::new(scale).unwrap();
let point_count = fft_settings.get_max_width();
let missing_count = (point_count as f32 * missing_ratio) as usize;
let mut missing = (0..point_count).collect::<Vec<_>>();
missing.shuffle(&mut thread_rng());
let missing_per_partial = 63;
let partial_count = missing_count.div_ceil(missing_per_partial);
let mut idxs = vec![0usize; missing_per_partial];
let mut partials = Vec::new();
for i in 0..partial_count {
let start = i * missing_per_partial;
let end = if start + missing_per_partial > missing_count {
missing_count
} else {
start + missing_per_partial
};
let partial_size = end - start;
for j in 0..partial_size {
idxs[j] = missing[i * missing_per_partial + j];
}
let partial = fft_settings
.do_zero_poly_mul_partial(&idxs[..partial_size], 1)
.unwrap();
partials.push(partial);
}
let from_tree_reduction = fft_settings
.reduce_partials(point_count, &partials)
.unwrap();
let from_direct = fft_settings
.do_zero_poly_mul_partial(
&missing[..missing_count],
fft_settings.get_max_width() / point_count,
)
.unwrap();
for i in 0..(missing_count + 1) {
from_tree_reduction
.get_coeff_at(i)
.equals(&from_direct.get_coeff_at(i));
}
}
}
}
/// Check that polynomial evaluation works against precomputed values
pub fn check_test_data<TFr: Fr, TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>, TPoly: Poly<TFr>>() {
let mut expected_eval = TPoly::new(16);
let mut expected_poly = TPoly::new(16);
let fft_settings = TFFTSettings::new(4).unwrap();
for i in 0..16 {
expected_eval.set_coeff_at(i, &TFr::from_u64_arr(&EXPECTED_EVAL_U64[i]));
expected_poly.set_coeff_at(i, &TFr::from_u64_arr(&EXPECTED_POLY_U64[i]));
}
for (i, &exists) in EXISTS.iter().enumerate() {
if !exists {
let tmp = expected_poly.eval(&fft_settings.get_roots_of_unity_at(i));
assert!(tmp.is_zero());
}
}
for i in 1..8 {
let tmp = expected_eval.eval(&fft_settings.get_roots_of_unity_at(i));
assert!(tmp.is_zero());
}
let tmp_poly = fft_settings
.fft_fr(expected_eval.get_coeffs(), true)
.unwrap();
assert_eq!(tmp_poly.len(), 16);
for (i, tmp_poly) in tmp_poly.iter().enumerate() {
assert!(tmp_poly.equals(&expected_poly.get_coeff_at(i)));
}
}
/// Check if zero polynomial is calculated and evaluated as expected against precomputed values
pub fn zero_poly_known<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + ZeroPoly<TFr, TPoly>,
TPoly: Poly<TFr>,
>() {
let fft_settings = TFFTSettings::new(4).unwrap();
let mut missing_idxs = Vec::new();
let mut expected_eval = TPoly::new(16);
let mut expected_poly = TPoly::new(16);
for (i, &exists) in EXISTS.iter().enumerate() {
expected_eval.set_coeff_at(i, &TFr::from_u64_arr(&EXPECTED_EVAL_U64[i]));
expected_poly.set_coeff_at(i, &TFr::from_u64_arr(&EXPECTED_POLY_U64[i]));
if !exists {
missing_idxs.push(i);
}
}
let (zero_eval, zero_poly) = fft_settings
.zero_poly_via_multiplication(16, &missing_idxs)
.unwrap();
assert_eq!(zero_eval.len(), 16);
for (i, zero_eval) in zero_eval.iter().enumerate() {
assert!(expected_eval.get_coeff_at(i).equals(zero_eval));
assert!(expected_poly
.get_coeff_at(i)
.equals(&zero_poly.get_coeff_at(i)));
}
}
/// Generate random series of missing indices and check if they are multiplied correctly
pub fn zero_poly_random<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + ZeroPoly<TFr, TPoly> + FFTFr<TFr>,
TPoly: Poly<TFr>,
>() {
for its in 0..8 {
let mut rng = StdRng::seed_from_u64(its);
for scale in 3..13 {
let fft_settings = TFFTSettings::new(scale).unwrap();
let mut missing_idxs = Vec::new();
for i in 0..fft_settings.get_max_width() {
if rng.next_u64() % 2 == 1 {
missing_idxs.push(i);
}
}
if missing_idxs.len() == fft_settings.get_max_width() {
continue;
}
let (zero_eval, zero_poly) = fft_settings
.zero_poly_via_multiplication(fft_settings.get_max_width(), &missing_idxs)
.unwrap();
for missing_idx in missing_idxs {
let out = zero_poly.eval(&fft_settings.get_roots_of_unity_at(missing_idx));
assert!(out.is_zero());
}
let zero_eval_fft = fft_settings.fft_fr(&zero_eval, true).unwrap();
#[allow(clippy::needless_range_loop)]
for i in 0..zero_poly.len() {
assert!(zero_poly.get_coeff_at(i).equals(&zero_eval_fft[i]));
}
#[allow(clippy::needless_range_loop)]
for i in zero_poly.len()..fft_settings.get_max_width() {
assert!(zero_eval_fft[i].is_zero());
}
}
}
}
/// Check that roots of unity loop correctly and the first value equals the last one
/// by evaluating a polynomial created to equal zero for the last value
pub fn zero_poly_all_but_one<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + ZeroPoly<TFr, TPoly> + FFTFr<TFr>,
TPoly: Poly<TFr>,
>() {
let fft_settings = TFFTSettings::new(8).unwrap();
let mut missing_idxs = Vec::new();
for i in 0..(fft_settings.get_max_width() - 1) {
missing_idxs.push(i + 1);
}
let (zero_eval, zero_poly) = fft_settings
.zero_poly_via_multiplication(fft_settings.get_max_width(), &missing_idxs)
.unwrap();
for missing_idx in missing_idxs {
let ret = zero_poly.eval(&fft_settings.get_roots_of_unity_at(missing_idx));
assert!(ret.is_zero());
}
let zero_eval_fft = fft_settings.fft_fr(&zero_eval, true).unwrap();
#[allow(clippy::needless_range_loop)]
for i in 0..zero_poly.len() {
assert!(zero_poly.get_coeff_at(i).equals(&zero_eval_fft[i]));
}
#[allow(clippy::needless_range_loop)]
for i in zero_poly.len()..fft_settings.get_max_width() {
assert!(zero_eval_fft[i].is_zero());
}
}
/// Check an edge case where 252 is missing with width 8
pub fn zero_poly_252<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + ZeroPoly<TFr, TPoly> + FFTFr<TFr>,
TPoly: Poly<TFr>,
>() {
let fft_settings = TFFTSettings::new(8).unwrap();
let missing_idxs = (0..252).collect::<Vec<_>>();
let (zero_eval, zero_poly) = fft_settings
.zero_poly_via_multiplication(fft_settings.get_max_width(), &missing_idxs)
.unwrap();
for missing_idx in missing_idxs {
let ret = zero_poly.eval(&fft_settings.get_roots_of_unity_at(missing_idx));
assert!(ret.is_zero());
}
let zero_eval_fft = fft_settings.fft_fr(&zero_eval, true).unwrap();
#[allow(clippy::needless_range_loop)]
for i in 0..zero_poly.len() {
assert!(zero_poly.get_coeff_at(i).equals(&zero_eval_fft[i]));
}
#[allow(clippy::needless_range_loop)]
for i in zero_poly.len()..fft_settings.get_max_width() {
assert!(zero_eval_fft[i].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/kzg-bench/src/tests/bls12_381.rs | kzg-bench/src/tests/bls12_381.rs | use kzg::{
msm::precompute::{precompute, PrecomputationTable},
Fr, G1Affine, G1Fp, G1GetFp, G1Mul, G1ProjAddAffine, G2Mul, G1, G2,
};
use std::convert::TryInto;
pub fn log_2_byte_works(log_2_byte: &dyn Fn(u8) -> usize) {
assert_eq!(0, log_2_byte(0x01));
assert_eq!(7, log_2_byte(0x80));
assert_eq!(7, log_2_byte(0xff));
assert_eq!(4, log_2_byte(0x10));
}
pub fn fr_is_null_works<TFr: Fr>() {
let one = TFr::from_u64(1);
let zero = TFr::zero();
let null = TFr::null();
assert!(!zero.is_null());
assert!(!one.is_null());
assert!(null.is_null());
}
pub fn fr_is_zero_works<TFr: Fr>() {
let zero = TFr::from_u64(0);
assert!(zero.is_zero());
}
pub fn fr_is_one_works<TFr: Fr>() {
let one = TFr::from_u64(1);
assert!(one.is_one());
}
pub fn fr_from_uint64_works<TFr: Fr>() {
let a = TFr::from_u64(1);
assert!(a.is_one());
}
pub fn fr_equal_works<TFr: Fr>() {
// // A couple of arbitrary roots of unity
let aa: [u64; 4] = [
0x0001000000000000,
0xec03000276030000,
0x8d51ccce760304d0,
0x0000000000000000,
];
let bb: [u64; 4] = [
0x8dd702cb688bc087,
0xa032824078eaa4fe,
0xa733b23a98ca5b22,
0x3f96405d25a31660,
];
let a: TFr = TFr::from_u64_arr(&aa);
let b: TFr = TFr::from_u64_arr(&bb);
assert!(a.equals(&a));
assert!(!a.equals(&b));
}
pub fn fr_negate_works<TFr: Fr + std::fmt::Debug>() {
let m1: [u64; 4] = [
0xffffffff00000000,
0x53bda402fffe5bfe,
0x3339d80809a1d805,
0x73eda753299d7d48,
];
let minus1 = TFr::from_u64_arr(&m1);
let res = minus1.negate();
assert!(res.is_one());
}
pub fn fr_pow_works<TFr: Fr>() {
// // a^pow
let pow: u64 = 123456;
let a = TFr::from_u64(197);
// // Do it the slow way
let mut expected = TFr::one();
for _ in 0..pow {
expected = expected.mul(&a);
}
// // Do it the quick way
let actual = a.pow(pow as usize);
assert!(expected.equals(&actual));
}
pub fn fr_div_works<TFr: Fr>() {
let a = TFr::from_u64(197);
let b = TFr::from_u64(123456);
let tmp = a.div(&b).unwrap();
let actual = tmp.mul(&b);
assert!(a.equals(&actual));
}
// // This is strictly undefined, but conventionally 0 is returned
pub fn fr_div_by_zero<TFr: Fr>() {
let a = TFr::from_u64(197);
let b = TFr::from_u64(0);
let tmp = a.div(&b).unwrap();
assert!(tmp.is_zero());
}
pub fn fr_uint64s_roundtrip<TFr: Fr>() {
let expected: [u64; 4] = [1, 2, 3, 4];
let fr = TFr::from_u64_arr(&expected);
let actual = fr.to_u64_arr();
assert_eq!(expected[0], actual[0]);
assert_eq!(expected[1], actual[1]);
assert_eq!(expected[2], actual[2]);
assert_eq!(expected[3], actual[3]);
}
pub fn p1_mul_works<TFr: Fr, TG1: G1 + G1Mul<TFr>>() {
let m1: [u64; 4] = [
0xffffffff00000000,
0x53bda402fffe5bfe,
0x3339d80809a1d805,
0x73eda753299d7d48,
];
let minus1 = TFr::from_u64_arr(&m1);
let res = TG1::generator().mul(&minus1);
assert!(res.equals(&TG1::negative_generator()));
}
pub fn p1_sub_works<TG1: G1>() {
let tmp = TG1::generator().dbl();
let res = TG1::generator().sub(&TG1::negative_generator());
assert!(tmp.equals(&res));
}
pub fn p1_add_or_dbl_works<TG1: G1>() {
let p = TG1::rand();
let expected = p.dbl();
let actual = p.add_or_dbl(&p);
assert!(expected.equals(&actual));
let mut actual = TG1::zero();
actual.add_or_dbl_assign(&p);
assert!(p.equals(&actual));
}
pub fn p1_add_zero_works<TG1: G1>() {
let p = TG1::rand();
let expected = p.clone();
let actual = p.add(&TG1::zero());
assert!(expected.equals(&actual));
let actual = TG1::zero().add(&p);
assert!(expected.equals(&actual));
let mut actual = TG1::zero();
actual.add_assign(&p);
assert!(expected.equals(&actual));
}
pub fn p2_add_or_dbl_works<TG2: G2>() {
let expected = TG2::generator().dbl();
let actual = TG2::generator().add_or_dbl(&TG2::generator());
assert!(expected.equals(&actual));
}
pub fn p2_mul_works<TFr: Fr, TG2: G2 + G2Mul<TFr>>() {
let m1: [u64; 4] = [
0xffffffff00000000,
0x53bda402fffe5bfe,
0x3339d80809a1d805,
0x73eda753299d7d48,
];
let minus1 = TFr::from_u64_arr(&m1);
let res = TG2::generator().mul(&minus1);
assert!(res.equals(&TG2::negative_generator()));
}
pub fn p2_sub_works<TG2: G2>() {
let tmp = TG2::generator().dbl();
let res = TG2::generator().sub(&TG2::negative_generator());
assert!(tmp.equals(&res));
}
pub fn g1_identity_is_infinity<TG1: G1>() {
assert!(TG1::is_inf(&TG1::identity()));
}
pub fn g1_identity_is_identity<TG1: G1>() {
let actual = TG1::generator().add_or_dbl(&TG1::identity());
assert!(actual.equals(&TG1::generator()));
}
#[allow(clippy::type_complexity)]
pub fn g1_make_linear_combination<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp> + Copy,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
g1_linear_combination: &dyn Fn(
&mut TG1,
&[TG1],
&[TFr],
usize,
Option<&PrecomputationTable<TFr, TG1, TG1Fp, TG1Affine, TG1ProjAddAffine>>,
),
) {
let len: usize = 255;
let mut coeffs = vec![TFr::default(); len];
let mut p = vec![TG1::default(); len];
for i in 0..len {
coeffs[i] = TFr::from_u64((i + 1).try_into().unwrap());
p[i] = TG1::generator();
}
let tmp = TFr::from_u64((len * (len + 1) / 2).try_into().unwrap());
let exp = TG1::generator().mul(&tmp);
let mut res = TG1::default();
g1_linear_combination(&mut res, &p, &coeffs, len, None);
assert!(exp.equals(&res));
let precomputation = precompute(&p, &[]).unwrap();
g1_linear_combination(&mut res, &p, &coeffs, len, precomputation.as_ref());
assert_eq!(exp, res);
}
#[allow(clippy::type_complexity)]
pub fn g1_random_linear_combination<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp> + Copy,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
g1_linear_combination: &dyn Fn(
&mut TG1,
&[TG1],
&[TFr],
usize,
Option<&PrecomputationTable<TFr, TG1, TG1Fp, TG1Affine, TG1ProjAddAffine>>,
),
) {
let len: usize = 8192;
let mut coeffs = vec![TFr::default(); len];
let mut p = vec![TG1::default(); len];
let mut p1tmp = TG1::generator();
for i in 0..len {
coeffs[i] = TFr::rand();
p[i] = p1tmp;
p1tmp = p1tmp.dbl();
}
let mut exp = TG1::identity();
for i in 0..len {
p1tmp = p[i].mul(&coeffs[i]);
exp = exp.add_or_dbl(&p1tmp);
}
let mut res = TG1::default();
g1_linear_combination(&mut res, &p, &coeffs, len, None);
assert!(exp.equals(&res));
let precomputation = precompute(&p, &[]).unwrap();
g1_linear_combination(&mut res, &p, &coeffs, len, precomputation.as_ref());
assert!(exp.equals(&res));
}
#[allow(clippy::type_complexity)]
pub fn g1_linear_combination_infinity_points<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp> + Copy,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
g1_linear_combination: &dyn Fn(
&mut TG1,
&[TG1],
&[TFr],
usize,
Option<&PrecomputationTable<TFr, TG1, TG1Fp, TG1Affine, TG1ProjAddAffine>>,
),
) {
let len: usize = 4096;
let mut coeffs = vec![TFr::default(); len];
let mut p = vec![TG1::default(); len];
for i in 0..len {
if rand::random::<f32>() < 0.1 {
coeffs[i] = TFr::zero();
} else {
coeffs[i] = TFr::rand();
}
if rand::random::<f32>() < 0.1 {
p[i] = TG1::zero();
} else {
p[i] = TG1::rand();
}
}
let mut exp = TG1::identity();
for i in 0..len {
exp = exp.add_or_dbl(&p[i].mul(&coeffs[i]));
}
let mut res = TG1::default();
g1_linear_combination(&mut res, &p, &coeffs, len, None);
assert!(exp.equals(&res));
let precomputation = precompute(&p, &[]).unwrap();
g1_linear_combination(&mut res, &p, &coeffs, len, precomputation.as_ref());
assert_eq!(exp, res);
}
#[allow(clippy::type_complexity)]
pub fn g1_small_linear_combination<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp> + Copy,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
g1_linear_combination: &dyn Fn(
&mut TG1,
&[TG1],
&[TFr],
usize,
Option<&PrecomputationTable<TFr, TG1, TG1Fp, TG1Affine, TG1ProjAddAffine>>,
),
) {
let len: usize = 128;
let points = (0..len).map(|_| TG1::rand()).collect::<Vec<_>>();
let scalars = (0..len).map(|_| TFr::rand()).collect::<Vec<_>>();
let mut results = Vec::with_capacity(len + 1);
let mut current = TG1::zero();
results.push(current);
for i in 0..len {
current = current.add(&points[i].mul(&scalars[i]));
results.push(current);
}
let results = &results[..];
for i in 0..=len {
let mut res = TG1::rand(); // g1_linear_combination must ignore value saved in output, so just to make sure, we initialize with random value
g1_linear_combination(&mut res, &points[0..i], &scalars[0..i], i, None);
assert_eq!(
res, results[i],
"should correctly compute msm with size {i}"
);
}
// // Precompute once, use to calculate all other results
{
let precomputation = precompute(&points, &[]).unwrap();
if precomputation.is_some() {
for i in 0..=len {
let mut res = TG1::rand(); // g1_linear_combination must ignore value saved in output, so just to make sure, we initialize with random value
g1_linear_combination(
&mut res,
&points[0..i],
&scalars[0..i],
i,
precomputation.as_ref(),
);
assert_eq!(res, results[i], "should correctly compute msm, using precomputations for {len} points, with size {i}");
}
}
}
// Precompute for each set of points
{
for i in 0..=len {
let precomputation = precompute(&points[0..i], &[]).unwrap();
if precomputation.is_some() {
let mut res = TG1::rand();
g1_linear_combination(
&mut res,
&points[0..i],
&scalars[0..i],
i,
precomputation.as_ref(),
);
assert_eq!(res, results[i], "should correctly compute msm, using precomputations for {i} points, with size {i}");
}
}
}
}
pub fn pairings_work<TFr: Fr, TG1: G1 + G1Mul<TFr>, TG2: G2 + G2Mul<TFr>>(
pairings_verify: &dyn Fn(&TG1, &TG2, &TG1, &TG2) -> bool,
) {
// // Verify that e([3]g1, [5]g2) = e([5]g1, [3]g2)
let three = TFr::from_u64(3);
let five = TFr::from_u64(5);
let g1_3 = TG1::generator().mul(&three);
let g1_5 = TG1::generator().mul(&five);
let g2_3 = TG2::generator().mul(&three);
let g2_5 = TG2::generator().mul(&five);
assert!(pairings_verify(&g1_3, &g2_5, &g1_5, &g2_3));
assert!(!pairings_verify(&g1_3, &g2_3, &g1_5, &g2_5));
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/fk20_proofs.rs | kzg-bench/src/tests/fk20_proofs.rs | use kzg::{
common_utils::{is_power_of_two, log2_pow2, reverse_bit_order, reverse_bits_limited},
EcBackend, FFTFr, FFTSettings, FK20MultiSettings, FK20SingleSettings, Fr, KZGSettings, Poly,
};
pub const SECRET: [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,
];
#[allow(clippy::type_complexity)]
pub fn fk_single<
B: EcBackend,
TFK20SingleSettings: FK20SingleSettings<
B::Fr,
B::G1,
B::G2,
B::FFTSettings,
B::Poly,
B::KZGSettings,
B::G1Fp,
B::G1Affine,
B::G1ProjAddAffine,
>,
>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
let coeffs = [1, 2, 3, 4, 7, 7, 7, 7, 13, 13, 13, 13, 13, 13, 13, 13];
let poly_len: usize = coeffs.len();
let n: usize = 5;
let n_len: usize = 1 << n;
let secrets_len = n_len;
assert!(n_len >= 2 * poly_len);
let mut p = B::Poly::new(poly_len);
for (i, &coeff) in coeffs.iter().enumerate() {
p.set_coeff_at(i, &B::Fr::from_u64(coeff));
}
// Initialise the secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = B::FFTSettings::new(n).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 4).unwrap();
let fk = TFK20SingleSettings::new(&ks, 2 * poly_len).unwrap();
// Commit to the polynomial
let commitment = ks.commit_to_poly(&p).unwrap();
// 1. First with `da_using_fk20_single`
// Generate the proofs
let all_proofs = fk.data_availability(&p).unwrap();
// Verify the proof at each root of unity
for i in 0..(2 * poly_len) {
let x = fs.get_roots_of_unity_at(i);
let y = p.eval(&x);
let proof = &all_proofs[reverse_bits_limited(2 * poly_len, i)];
assert!(ks.check_proof_single(&commitment, proof, &x, &y).unwrap());
}
// 2. Exactly the same thing again with `fk20_single_da_opt`
// Generate the proofs
let all_proofs = fk.data_availability_optimized(&p).unwrap();
// Verify the proof at each root of unity
for (i, proof) in all_proofs.iter().enumerate().take(2 * poly_len) {
let x = fs.get_roots_of_unity_at(i);
let y = p.eval(&x);
assert!(ks.check_proof_single(&commitment, proof, &x, &y).unwrap());
}
}
#[allow(clippy::type_complexity)]
pub fn fk_single_strided<
B: EcBackend,
TFK20SingleSettings: FK20SingleSettings<
B::Fr,
B::G1,
B::G2,
B::FFTSettings,
B::Poly,
B::KZGSettings,
B::G1Fp,
B::G1Affine,
B::G1ProjAddAffine,
>,
>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
let coeffs = [1, 2, 3, 4, 7, 7, 7, 7, 13, 13, 13, 13, 13, 13, 13, 13];
let poly_len: usize = coeffs.len();
let n: usize = 8;
let n_len: usize = 1 << n;
let stride: usize = n_len / (2 * poly_len);
let secrets_len = n_len;
assert!(n_len >= 2 * poly_len);
let mut p = B::Poly::new(poly_len);
for (i, &coeff) in coeffs.iter().enumerate() {
p.set_coeff_at(i, &B::Fr::from_u64(coeff));
}
// Initialise the secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = B::FFTSettings::new(n).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 16).unwrap();
let fk = TFK20SingleSettings::new(&ks, 2 * poly_len).unwrap();
// Commit to the polynomial
let commitment = ks.commit_to_poly(&p).unwrap();
// Generate the proofs
let all_proofs = fk.data_availability(&p).unwrap();
// Verify the proof at each root of unity
for i in 0..(2 * poly_len) {
let x = fs.get_roots_of_unity_at(i * stride);
let y = p.eval(&x);
let proof = &all_proofs[reverse_bits_limited(2 * poly_len, i)];
assert!(ks.check_proof_single(&commitment, proof, &x, &y).unwrap());
}
}
#[allow(clippy::type_complexity)]
pub fn fk_multi_settings<
B: EcBackend,
TFK20MultiSettings: FK20MultiSettings<
B::Fr,
B::G1,
B::G2,
B::FFTSettings,
B::Poly,
B::KZGSettings,
B::G1Fp,
B::G1Affine,
B::G1ProjAddAffine,
>,
>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
let n: usize = 5;
let secrets_len: usize = 32;
// Initialise the secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = B::FFTSettings::new(n).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 4).unwrap();
let _fk = TFK20MultiSettings::new(&ks, 32, 4).unwrap();
}
#[allow(clippy::type_complexity)]
fn fk_multi_case<
B: EcBackend,
TFK20MultiSettings: FK20MultiSettings<
B::Fr,
B::G1,
B::G2,
B::FFTSettings,
B::Poly,
B::KZGSettings,
B::G1Fp,
B::G1Affine,
B::G1ProjAddAffine,
>,
>(
chunk_len: usize,
n: usize,
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) where
B::FFTSettings: FFTFr<B::Fr>,
{
let vv: Vec<u64> = vec![1, 2, 3, 4, 7, 8, 9, 10, 13, 14, 1, 15, 1, 1000, 134, 33];
assert!(is_power_of_two(n));
assert!(is_power_of_two(chunk_len));
assert_eq!(n % 16, 0);
assert!(n >= chunk_len);
let chunk_count: usize = n / chunk_len;
let secrets_len: usize = 2 * n;
let width: usize = log2_pow2(secrets_len);
// Initialise the secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = B::FFTSettings::new(width).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, chunk_len).unwrap();
let fk = TFK20MultiSettings::new(&ks, n * 2, chunk_len).unwrap();
// Create a test polynomial of size n that's independent of chunk_len
let mut p = B::Poly::new(n);
for i in 0..chunk_count {
for j in 0..chunk_len {
let p_index = i * chunk_len + j;
let v_index = p_index % 16;
let mut v = vv[v_index];
let tmp: u64 = (i * chunk_len / 16) as u64;
if v_index == 3 {
v += tmp;
}
if v_index == 5 {
v += tmp * tmp;
}
p.set_coeff_at(p_index, &B::Fr::from_u64(v));
if v_index == 12 {
p.set_coeff_at(p_index, &p.get_coeff_at(p_index).negate());
}
if v_index == 14 {
p.set_coeff_at(p_index, &p.get_coeff_at(p_index).negate());
}
}
}
// Commit to the polynomial
let commitment = ks.commit_to_poly(&p).unwrap();
// Compute the multi proofs, assuming that the polynomial will be extended with zeros
let all_proofs = fk.data_availability(&p).unwrap();
// Now actually extend the polynomial with zeros
let mut extended_coeffs = vec![B::Fr::zero(); 2 * n];
for (i, extended_coeff) in extended_coeffs.iter_mut().enumerate().take(n) {
*extended_coeff = p.get_coeff_at(i);
}
let mut extended_coeffs_fft = fs.fft_fr(&extended_coeffs, false).unwrap();
reverse_bit_order(&mut extended_coeffs_fft).unwrap();
// Verify the proofs
let mut ys = vec![B::Fr::default(); chunk_len];
let mut ys2 = vec![B::Fr::default(); chunk_len];
let domain_stride = fs.get_max_width() / (2 * n);
for pos in 0..(2 * chunk_count) {
let domain_pos = reverse_bits_limited(2 * chunk_count, pos);
let x = fs.get_roots_of_unity_at(domain_pos * domain_stride);
// The ys from the extended coeffients
for i in 0..chunk_len {
ys[i] = extended_coeffs_fft[chunk_len * pos + i].clone();
}
reverse_bit_order(&mut ys).unwrap();
// Now recreate the ys by evaluating the polynomial in the sub-domain range
let stride = fs.get_max_width() / chunk_len;
for (i, ys2) in ys2.iter_mut().enumerate() {
let z = x.mul(&fs.get_roots_of_unity_at(i * stride));
*ys2 = p.eval(&z);
}
// ys and ys2 should be equal
for (ys, ys2) in ys.iter().zip(&ys2) {
assert!(ys.equals(ys2));
}
// Verify this proof
let result = ks
.check_proof_multi(&commitment, &all_proofs[pos], &x, &ys, chunk_len)
.unwrap();
assert!(result);
}
}
#[allow(clippy::type_complexity)]
pub fn fk_multi_chunk_len_1_512<
B: EcBackend,
TFK20MultiSettings: FK20MultiSettings<
B::Fr,
B::G1,
B::G2,
B::FFTSettings,
B::Poly,
B::KZGSettings,
B::G1Fp,
B::G1Affine,
B::G1ProjAddAffine,
>,
>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
fk_multi_case::<B, TFK20MultiSettings>(1, 512, &generate_trusted_setup);
}
#[allow(clippy::type_complexity)]
pub fn fk_multi_chunk_len_16_512<
B: EcBackend,
TFK20MultiSettings: FK20MultiSettings<
B::Fr,
B::G1,
B::G2,
B::FFTSettings,
B::Poly,
B::KZGSettings,
B::G1Fp,
B::G1Affine,
B::G1ProjAddAffine,
>,
>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
fk_multi_case::<B, TFK20MultiSettings>(16, 512, &generate_trusted_setup);
}
#[allow(clippy::type_complexity)]
pub fn fk_multi_chunk_len_16_16<
B: EcBackend,
TFK20MultiSettings: FK20MultiSettings<
B::Fr,
B::G1,
B::G2,
B::FFTSettings,
B::Poly,
B::KZGSettings,
B::G1Fp,
B::G1Affine,
B::G1ProjAddAffine,
>,
>(
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
fk_multi_case::<B, TFK20MultiSettings>(16, 16, &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/kzg-bench/src/tests/utils.rs | kzg-bench/src/tests/utils.rs | use std::{env::current_dir, path::PathBuf};
use kzg::eip_4844::TRUSTED_SETUP_PATH;
use pathdiff::diff_paths;
pub fn get_manifest_dir() -> String {
let current = current_dir().unwrap();
let manifest = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
let relative = diff_paths(manifest, current).unwrap();
relative.into_os_string().into_string().unwrap()
}
pub fn get_trusted_setup_path() -> String {
PathBuf::from(get_manifest_dir())
.join(TRUSTED_SETUP_PATH)
.into_os_string()
.into_string()
.unwrap()
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/mod.rs | kzg-bench/src/tests/mod.rs | pub mod bls12_381;
pub mod c_bindings;
pub mod consts;
pub mod das;
pub mod eip_4844;
pub mod eip_7594;
pub mod fft_fr;
pub mod fft_g1;
pub mod finite;
pub mod fk20_proofs;
pub mod kzg_proofs;
pub mod msm;
pub mod poly;
pub mod recover;
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/kzg-bench/src/tests/c_bindings.rs | kzg-bench/src/tests/c_bindings.rs | use std::{ffi::CString, fs::File, io::Read, path::PathBuf, ptr::null_mut};
use kzg::eth::c_bindings::{Blob, Bytes48, CKZGSettings, KZGCommitment, KZGProof};
use kzg::{
eip_4844::{
load_trusted_setup_string, BYTES_PER_COMMITMENT, BYTES_PER_FIELD_ELEMENT, BYTES_PER_G1,
BYTES_PER_G2, BYTES_PER_PROOF,
},
eth::c_bindings::CKzgRet,
};
use libc::FILE;
use crate::tests::{
eip_4844::generate_random_blob_bytes,
utils::{get_manifest_dir, get_trusted_setup_path},
};
fn get_trusted_setup_fixture_path(fixture: &str) -> String {
let filename = "trusted_setup_fixture.txt";
PathBuf::from(get_manifest_dir())
.join("src/tests/fixtures")
.join(fixture)
.join(filename)
.as_os_str()
.to_str()
.unwrap()
.to_string()
}
fn get_ckzg_settings(
load_trusted_setup_file: unsafe extern "C" fn(
out: *mut CKZGSettings,
in_: *mut FILE,
) -> CKzgRet,
) -> CKZGSettings {
let mut c_settings = CKZGSettings {
g1_values_lagrange_brp: null_mut(),
brp_roots_of_unity: null_mut(),
g1_values_monomial: null_mut(),
g2_values_monomial: null_mut(),
reverse_roots_of_unity: null_mut(),
scratch_size: 0,
tables: null_mut(),
wbits: 0,
x_ext_fft_columns: null_mut(),
roots_of_unity: null_mut(),
};
let trusted_setup_path = CString::new(get_trusted_setup_path()).unwrap();
let file = unsafe { libc::fopen(trusted_setup_path.as_ptr(), c"r".as_ptr()) };
assert!(!file.is_null());
let out = unsafe { load_trusted_setup_file(&mut c_settings, file) };
unsafe {
libc::fclose(file);
}
assert_ne!(out, CKzgRet::BadArgs);
c_settings
}
pub fn blob_to_kzg_commitment_invalid_blob_test(
blob_to_kzg_commitment: unsafe extern "C" fn(
out: *mut KZGCommitment,
blob: *const Blob,
s: &CKZGSettings,
) -> CKzgRet,
load_trusted_setup_file: unsafe extern "C" fn(
out: *mut CKZGSettings,
in_: *mut FILE,
) -> CKzgRet,
) {
let settings = get_ckzg_settings(load_trusted_setup_file);
let mut rng = rand::thread_rng();
let mut blob_bytes = generate_random_blob_bytes(&mut rng);
let bls_modulus: [u8; BYTES_PER_FIELD_ELEMENT] = [
0x73, 0xED, 0xA7, 0x53, 0x29, 0x9D, 0x7D, 0x48, 0x33, 0x39, 0xD8, 0x08, 0x09, 0xA1, 0xD8,
0x05, 0x53, 0xBD, 0xA4, 0x02, 0xFF, 0xFE, 0x5B, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x01,
];
// Make first field element equal to BLS_MODULUS
blob_bytes[0..BYTES_PER_FIELD_ELEMENT].copy_from_slice(&bls_modulus);
let blob = Blob { bytes: blob_bytes };
let mut commitment = KZGCommitment {
bytes: [0; BYTES_PER_COMMITMENT],
};
let output = unsafe { blob_to_kzg_commitment(&mut commitment, &blob, &settings) };
assert_eq!(output, CKzgRet::BadArgs)
}
pub fn load_trusted_setup_invalid_g1_byte_length_test(
load_trusted_setup: unsafe extern "C" fn(
*mut CKZGSettings,
*const u8,
u64,
*const u8,
u64,
*const u8,
u64,
u64,
) -> CKzgRet,
) {
let mut file = File::open(get_trusted_setup_path()).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let (mut g1_bytes_monomial, g1_bytes_lagrange, g2_bytes_monomial) =
load_trusted_setup_string(&contents).unwrap();
// Add one more point
let additional = [0; BYTES_PER_G1];
g1_bytes_monomial.extend_from_slice(&additional);
let mut loaded_settings = CKZGSettings {
g1_values_lagrange_brp: null_mut(),
brp_roots_of_unity: null_mut(),
g1_values_monomial: null_mut(),
g2_values_monomial: null_mut(),
reverse_roots_of_unity: null_mut(),
scratch_size: 0,
tables: null_mut(),
wbits: 0,
x_ext_fft_columns: null_mut(),
roots_of_unity: null_mut(),
};
let status = unsafe {
load_trusted_setup(
&mut loaded_settings,
g1_bytes_monomial.as_ptr(),
g1_bytes_monomial.len() as u64,
g1_bytes_lagrange.as_ptr(),
g1_bytes_lagrange.len() as u64,
g2_bytes_monomial.as_ptr(),
g2_bytes_monomial.len() as u64,
0,
)
};
assert_eq!(status, CKzgRet::BadArgs)
}
pub fn load_trusted_setup_invalid_g1_point_test(
load_trusted_setup: unsafe extern "C" fn(
*mut CKZGSettings,
*const u8,
u64,
*const u8,
u64,
*const u8,
u64,
u64,
) -> CKzgRet,
) {
let mut file = File::open(get_trusted_setup_path()).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let (mut g1_bytes_monomial, g1_bytes_lagrange, g2_bytes_monomial) =
load_trusted_setup_string(&contents).unwrap();
// Break first G1 point
g1_bytes_monomial[0] = 0;
let mut loaded_settings = CKZGSettings {
g1_values_lagrange_brp: null_mut(),
brp_roots_of_unity: null_mut(),
g1_values_monomial: null_mut(),
g2_values_monomial: null_mut(),
reverse_roots_of_unity: null_mut(),
scratch_size: 0,
tables: null_mut(),
wbits: 0,
x_ext_fft_columns: null_mut(),
roots_of_unity: null_mut(),
};
let status = unsafe {
load_trusted_setup(
&mut loaded_settings,
g1_bytes_monomial.as_ptr(),
g1_bytes_monomial.len() as u64,
g1_bytes_lagrange.as_ptr(),
g1_bytes_lagrange.len() as u64,
g2_bytes_monomial.as_ptr(),
g2_bytes_monomial.len() as u64,
0,
)
};
assert_eq!(status, CKzgRet::BadArgs)
}
pub fn load_trusted_setup_invalid_g2_byte_length_test(
load_trusted_setup: unsafe extern "C" fn(
*mut CKZGSettings,
*const u8,
u64,
*const u8,
u64,
*const u8,
u64,
u64,
) -> CKzgRet,
) {
let mut file = File::open(get_trusted_setup_path()).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let (g1_bytes_monomial, g1_bytes_lagrange, mut g2_bytes_monomial) =
load_trusted_setup_string(&contents).unwrap();
// Add one more point
let additional = [0; BYTES_PER_G2];
g2_bytes_monomial.extend_from_slice(&additional);
let mut loaded_settings = CKZGSettings {
g1_values_lagrange_brp: null_mut(),
brp_roots_of_unity: null_mut(),
g1_values_monomial: null_mut(),
g2_values_monomial: null_mut(),
reverse_roots_of_unity: null_mut(),
scratch_size: 0,
tables: null_mut(),
wbits: 0,
x_ext_fft_columns: null_mut(),
roots_of_unity: null_mut(),
};
let status = unsafe {
load_trusted_setup(
&mut loaded_settings,
g1_bytes_monomial.as_ptr(),
g1_bytes_monomial.len() as u64,
g1_bytes_lagrange.as_ptr(),
g1_bytes_lagrange.len() as u64,
g2_bytes_monomial.as_ptr(),
g2_bytes_monomial.len() as u64,
0,
)
};
assert_eq!(status, CKzgRet::BadArgs)
}
pub fn load_trusted_setup_invalid_g2_point_test(
load_trusted_setup: unsafe extern "C" fn(
*mut CKZGSettings,
*const u8,
u64,
*const u8,
u64,
*const u8,
u64,
u64,
) -> CKzgRet,
) {
let mut file = File::open(get_trusted_setup_path()).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let (g1_bytes_monomial, g1_bytes_lagrange, mut g2_bytes_monomial) =
load_trusted_setup_string(&contents).unwrap();
// Break first G2 point
g2_bytes_monomial[0] = 0;
let mut loaded_settings = CKZGSettings {
g1_values_lagrange_brp: null_mut(),
brp_roots_of_unity: null_mut(),
g1_values_monomial: null_mut(),
g2_values_monomial: null_mut(),
reverse_roots_of_unity: null_mut(),
scratch_size: 0,
tables: null_mut(),
wbits: 0,
x_ext_fft_columns: null_mut(),
roots_of_unity: null_mut(),
};
let status = unsafe {
load_trusted_setup(
&mut loaded_settings,
g1_bytes_monomial.as_ptr(),
g1_bytes_monomial.len() as u64,
g1_bytes_lagrange.as_ptr(),
g1_bytes_lagrange.len() as u64,
g2_bytes_monomial.as_ptr(),
g2_bytes_monomial.len() as u64,
0,
)
};
assert_eq!(status, CKzgRet::BadArgs)
}
pub fn load_trusted_setup_invalid_form_test(
load_trusted_setup: unsafe extern "C" fn(
*mut CKZGSettings,
*const u8,
u64,
*const u8,
u64,
*const u8,
u64,
u64,
) -> CKzgRet,
) {
let mut file = File::open(get_trusted_setup_fixture_path("old")).unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents).unwrap();
let (g1_bytes_monomial, g1_bytes_lagrange, g2_bytes_monomial) =
load_trusted_setup_string(&contents).unwrap();
let mut loaded_settings = CKZGSettings {
g1_values_lagrange_brp: null_mut(),
brp_roots_of_unity: null_mut(),
g1_values_monomial: null_mut(),
g2_values_monomial: null_mut(),
reverse_roots_of_unity: null_mut(),
scratch_size: 0,
tables: null_mut(),
wbits: 0,
x_ext_fft_columns: null_mut(),
roots_of_unity: null_mut(),
};
let status = unsafe {
load_trusted_setup(
&mut loaded_settings,
g1_bytes_monomial.as_ptr(),
g1_bytes_monomial.len() as u64,
g1_bytes_lagrange.as_ptr(),
g1_bytes_lagrange.len() as u64,
g2_bytes_monomial.as_ptr(),
g2_bytes_monomial.len() as u64,
0,
)
};
assert_eq!(status, CKzgRet::BadArgs)
}
pub fn load_trusted_setup_file_invalid_format_test(
load_trusted_setup_file: unsafe extern "C" fn(
out: *mut CKZGSettings,
in_: *mut FILE,
) -> CKzgRet,
) {
struct Fixture {
name: String,
message: String,
}
let fixtures = [
Fixture {
name: "old".to_string(),
message: "Invalid format because trusted setup is old, i.e. is not in Lagrange form".to_string(),
},
Fixture {
name: "invalid_g1_point_count".to_string(),
message: "Invalid format because G1 point count in trusted setup file does not match expected".to_string(),
},
Fixture {
name: "invalid_g2_point_count".to_string(),
message: "Invalid format because G2 point count in trusted setup file does not match expected".to_string(),
},
Fixture {
name: "missing_g1_point_count".to_string(),
message: "Invalid format because G1 point count is was not found in trusted setup file".to_string(),
},
Fixture {
name: "missing_g2_point_count".to_string(),
message: "Invalid format because G2 point count is was not found in trusted setup file".to_string(),
},
Fixture {
name: "insufficient_g1_points".to_string(),
message: "Invalid format because failed to read specified amount of G1 points"
.to_string(),
},
Fixture {
name: "insufficient_g2_points".to_string(),
message: "Invalid format because failed to read specified amount of G2 points"
.to_string(),
},
Fixture {
name: "invalid_chars".to_string(),
message: "Invalid format because incorrect characters encountered".to_string(),
},
Fixture {
name: "not_a_number".to_string(),
message: "Invalid format because file starts with not a number".to_string(),
},
];
for fixture in fixtures {
let file_path = get_trusted_setup_fixture_path(&fixture.name);
let file = unsafe {
let c_file_path = CString::new(file_path.clone()).unwrap();
libc::fopen(c_file_path.as_ptr(), c"r".as_ptr())
};
assert!(!file.is_null());
let mut loaded_settings = CKZGSettings {
g1_values_lagrange_brp: null_mut(),
brp_roots_of_unity: null_mut(),
g1_values_monomial: null_mut(),
g2_values_monomial: null_mut(),
reverse_roots_of_unity: null_mut(),
scratch_size: 0,
tables: null_mut(),
wbits: 0,
x_ext_fft_columns: null_mut(),
roots_of_unity: null_mut(),
};
let output = unsafe { load_trusted_setup_file(&mut loaded_settings, file) };
unsafe {
libc::fclose(file);
}
assert!(
output == CKzgRet::BadArgs,
"{}, fixture: {file_path}",
fixture.message
);
}
}
pub fn load_trusted_setup_file_valid_format_test(
load_trusted_setup_file: unsafe extern "C" fn(
out: *mut CKZGSettings,
in_: *mut FILE,
) -> CKzgRet,
) {
struct Fixture {
name: String,
message: String,
}
let fixtures = [
Fixture {
name: "valid_whitespace_characters".to_string(),
message: "Valid format, because whitespace characters must be ignored".to_string(),
},
Fixture {
name: "valid_short_hex".to_string(),
message: "Valid format, because first character of hex can be omitted, if it is zero (e.g. 07 -> 7)".to_string()
}
];
for fixture in fixtures {
let file_path = get_trusted_setup_fixture_path(&fixture.name);
let file = unsafe {
let c_file_path = CString::new(file_path.clone()).unwrap();
libc::fopen(c_file_path.as_ptr(), c"r".as_ptr())
};
assert!(!file.is_null());
let mut loaded_settings = CKZGSettings {
g1_values_lagrange_brp: null_mut(),
brp_roots_of_unity: null_mut(),
g1_values_monomial: null_mut(),
g2_values_monomial: null_mut(),
reverse_roots_of_unity: null_mut(),
scratch_size: 0,
tables: null_mut(),
wbits: 0,
x_ext_fft_columns: null_mut(),
roots_of_unity: null_mut(),
};
let output = unsafe { load_trusted_setup_file(&mut loaded_settings, file) };
unsafe {
libc::fclose(file);
}
assert!(
output == CKzgRet::Ok,
"{}, fixture: {file_path}",
fixture.message
);
}
}
pub fn free_trusted_setup_null_ptr_test(
free_trusted_setup: unsafe extern "C" fn(s: *mut CKZGSettings) -> (),
) {
// just should not crash with SIGSEGV
unsafe {
free_trusted_setup(null_mut());
}
let mut settings = CKZGSettings {
g1_values_lagrange_brp: null_mut(),
brp_roots_of_unity: null_mut(),
g1_values_monomial: null_mut(),
g2_values_monomial: null_mut(),
reverse_roots_of_unity: null_mut(),
scratch_size: 0,
tables: null_mut(),
wbits: 0,
x_ext_fft_columns: null_mut(),
roots_of_unity: null_mut(),
};
// same here, no asserts, just should not crash
unsafe {
free_trusted_setup(&mut settings);
}
}
pub fn free_trusted_setup_set_all_values_to_null_test(
free_trusted_setup: unsafe extern "C" fn(s: *mut CKZGSettings) -> (),
load_trusted_setup_file: unsafe extern "C" fn(
out: *mut CKZGSettings,
in_: *mut FILE,
) -> CKzgRet,
) {
let mut settings = get_ckzg_settings(load_trusted_setup_file);
assert!(!settings.g1_values_monomial.is_null());
assert!(!settings.g1_values_lagrange_brp.is_null());
assert!(!settings.g2_values_monomial.is_null());
assert!(!settings.reverse_roots_of_unity.is_null());
assert!(!settings.roots_of_unity.is_null());
assert!(!settings.brp_roots_of_unity.is_null());
unsafe {
free_trusted_setup(&mut settings);
};
assert!(settings.g1_values_monomial.is_null());
assert!(settings.g1_values_lagrange_brp.is_null());
assert!(settings.g2_values_monomial.is_null());
assert!(settings.reverse_roots_of_unity.is_null());
assert!(settings.roots_of_unity.is_null());
assert!(settings.brp_roots_of_unity.is_null());
}
pub fn compute_blob_kzg_proof_invalid_blob_test(
compute_blob_kzg_proof: unsafe extern "C" fn(
out: *mut KZGProof,
blob: *const Blob,
commitment_bytes: *const Bytes48,
s: &CKZGSettings,
) -> CKzgRet,
load_trusted_setup_file: unsafe extern "C" fn(
out: *mut CKZGSettings,
in_: *mut FILE,
) -> CKzgRet,
) {
let settings = get_ckzg_settings(load_trusted_setup_file);
let mut rng = rand::thread_rng();
let mut blob_bytes = generate_random_blob_bytes(&mut rng);
let bls_modulus: [u8; BYTES_PER_FIELD_ELEMENT] = [
0x73, 0xED, 0xA7, 0x53, 0x29, 0x9D, 0x7D, 0x48, 0x33, 0x39, 0xD8, 0x08, 0x09, 0xA1, 0xD8,
0x05, 0x53, 0xBD, 0xA4, 0x02, 0xFF, 0xFE, 0x5B, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00,
0x00, 0x01,
];
// Make first field element equal to BLS_MODULUS
blob_bytes[0..BYTES_PER_FIELD_ELEMENT].copy_from_slice(&bls_modulus);
let blob = Blob { bytes: blob_bytes };
let mut out = KZGProof {
bytes: [0; BYTES_PER_PROOF],
};
let commitment = Bytes48 {
bytes: [0u8; BYTES_PER_COMMITMENT],
};
let out = unsafe { compute_blob_kzg_proof(&mut out, &blob, &commitment, &settings) };
assert_eq!(out, CKzgRet::BadArgs);
}
pub fn compute_blob_kzg_proof_commitment_is_point_at_infinity_test(
compute_blob_kzg_proof: unsafe extern "C" fn(
out: *mut KZGProof,
blob: *const Blob,
commitment_bytes: *const Bytes48,
s: &CKZGSettings,
) -> CKzgRet,
load_trusted_setup_file: unsafe extern "C" fn(
out: *mut CKZGSettings,
in_: *mut FILE,
) -> CKzgRet,
) {
let settings = get_ckzg_settings(load_trusted_setup_file);
let mut rng = rand::thread_rng();
let blob_bytes = generate_random_blob_bytes(&mut rng);
let blob = Blob { bytes: blob_bytes };
let mut out = KZGProof {
bytes: [0; BYTES_PER_PROOF],
};
/* set commitment to point at infinity */
let mut commitment = Bytes48 {
bytes: [0; BYTES_PER_COMMITMENT],
};
commitment.bytes[0] = 0xc0;
let out = unsafe { compute_blob_kzg_proof(&mut out, &blob, &commitment, &settings) };
assert_eq!(out, CKzgRet::Ok);
}
pub fn compute_blob_kzg_proof_zero_input_test(
compute_blob_kzg_proof: unsafe extern "C" fn(
out: *mut KZGProof,
blob: *const Blob,
commitment_bytes: *const Bytes48,
s: &CKZGSettings,
) -> CKzgRet,
load_trusted_setup_file: unsafe extern "C" fn(
out: *mut CKZGSettings,
in_: *mut FILE,
) -> CKzgRet,
) {
let settings = get_ckzg_settings(load_trusted_setup_file);
let mut rng = rand::thread_rng();
let blob_bytes = generate_random_blob_bytes(&mut rng);
let blob = Blob { bytes: blob_bytes };
let mut out = KZGProof {
bytes: [0; BYTES_PER_PROOF],
};
/* set commitment to zero */
let commitment = Bytes48 {
bytes: [0; BYTES_PER_COMMITMENT],
};
let out = unsafe { compute_blob_kzg_proof(&mut out, &blob, &commitment, &settings) };
assert_eq!(out, 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/kzg-bench/src/tests/fft_g1.rs | kzg-bench/src/tests/fft_g1.rs | use kzg::{FFTFr, FFTSettings, Fr, FFTG1, G1};
#[allow(clippy::type_complexity)]
pub fn compare_ft_fft<TFr: Fr, TG1: G1, TFFTSettings: FFTSettings<TFr> + FFTG1<TG1>>(
fft_g1_slow: &dyn Fn(&mut [TG1], &[TG1], usize, &[TFr], usize),
fft_g1_fast: &dyn Fn(&mut [TG1], &[TG1], usize, &[TFr], usize),
make_data: &dyn Fn(usize) -> Vec<TG1>,
) {
let size: usize = 6;
let fs = TFFTSettings::new(size).unwrap();
assert_eq!(fs.get_max_width(), 2 << (size - 1));
let data = make_data(fs.get_max_width());
let stride = fs.get_max_width() / data.len();
let mut fast = vec![TG1::default(); data.len()];
let mut slow = vec![TG1::default(); data.len()];
fft_g1_fast(&mut fast, &data, 1, fs.get_roots_of_unity(), stride);
fft_g1_slow(&mut slow, &data, 1, fs.get_roots_of_unity(), stride);
for i in 0..fs.get_max_width() {
assert!(fast[i].equals(&slow[i]));
}
}
pub fn roundtrip_fft<TFr: Fr, TG1: G1, TFFTSettings: FFTSettings<TFr> + FFTG1<TG1>>(
make_data: &dyn Fn(usize) -> Vec<TG1>,
) {
let size: usize = 10;
let fs = TFFTSettings::new(size).unwrap();
assert_eq!(fs.get_max_width(), 2 << (size - 1));
// Make data
let expected = make_data(fs.get_max_width());
let mut data = make_data(fs.get_max_width());
// Forward and reverse FFT
let coeffs = fs.fft_g1(&data, false).unwrap();
assert_eq!(coeffs.len(), 2 << (size - 1));
data = fs.fft_g1(&coeffs, true).unwrap();
assert_eq!(data.len(), 2 << (size - 1));
// Verify that the result is still ascending values of i
for i in 0..fs.get_max_width() {
assert!(expected[i].equals(&data[i]));
}
}
pub fn stride_fft<TFr: Fr, TG1: G1, TFFTSettings: FFTSettings<TFr> + FFTG1<TG1>>(
make_data: &dyn Fn(usize) -> Vec<TG1>,
) {
let size1: usize = 9;
let size2: usize = 12;
let width: u64 = if size1 < size2 {
1 << size1
} else {
1 << size2
};
let fs1 = TFFTSettings::new(size1).unwrap();
assert_eq!(fs1.get_max_width(), 2 << (size1 - 1));
let fs2 = TFFTSettings::new(size2).unwrap();
assert_eq!(fs2.get_max_width(), 2 << (size2 - 1));
let data = make_data(width as usize);
let coeffs1 = fs1.fft_g1(&data, false).unwrap();
assert_eq!(coeffs1.len(), width as usize);
let coeffs2 = fs2.fft_g1(&data, false).unwrap();
assert_eq!(coeffs2.len(), width as usize);
for i in 0..width {
assert!(coeffs1[i as usize].equals(&coeffs2[i as usize]));
}
}
#[allow(clippy::type_complexity)]
pub fn compare_sft_fft<TFr: Fr, TG1: G1, TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>>(
fft_g1_slow: &dyn Fn(&mut [TG1], &[TG1], usize, &[TFr], usize),
fft_g1_fast: &dyn Fn(&mut [TG1], &[TG1], usize, &[TFr], usize),
make_data: &dyn Fn(usize) -> Vec<TG1>,
) {
let size: usize = 6;
let fft_settings = TFFTSettings::new(size).unwrap();
let mut slow = vec![TG1::default(); fft_settings.get_max_width()];
let mut fast = vec![TG1::default(); fft_settings.get_max_width()];
let data = make_data(fft_settings.get_max_width());
fft_g1_slow(&mut slow, &data, 1, fft_settings.get_roots_of_unity(), 1);
fft_g1_fast(&mut fast, &data, 1, fft_settings.get_roots_of_unity(), 1);
for i in 0..fft_settings.get_max_width() {
assert!(slow[i].equals(&fast[i]));
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/fft_fr.rs | kzg-bench/src/tests/fft_fr.rs | use kzg::{FFTFr, FFTSettings, Fr};
/// Check that both FFT implementations produce the same results
#[allow(clippy::type_complexity)]
pub fn compare_sft_fft<TFr: Fr, TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>>(
fft_fr_slow: &dyn Fn(&mut [TFr], &[TFr], usize, &[TFr], usize),
fft_fr_fast: &dyn Fn(&mut [TFr], &[TFr], usize, &[TFr], usize),
) {
let size: usize = 12;
let fft_settings = TFFTSettings::new(size).unwrap();
let data = (0..fft_settings.get_max_width())
.map(|i| TFr::from_u64_arr(&[i as u64, 0, 0, 0]))
.collect::<Vec<_>>();
let mut out0 = vec![TFr::default(); fft_settings.get_max_width()];
let mut out1 = vec![TFr::default(); fft_settings.get_max_width()];
// Compare fast and slow FFT approach
fft_fr_slow(&mut out0, &data, 1, fft_settings.get_roots_of_unity(), 1);
fft_fr_fast(&mut out1, &data, 1, fft_settings.get_roots_of_unity(), 1);
for i in 0..fft_settings.get_max_width() {
assert!(out0[i].equals(&out1[i]));
}
}
/// Check that computing FFT and inverse FFT results in the starting data
pub fn roundtrip_fft<TFr: Fr, TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>>() {
let size: usize = 12;
let fft_settings = TFFTSettings::new(size).unwrap();
let starting_data = (0..fft_settings.get_max_width())
.map(|i| TFr::from_u64(i as u64))
.collect::<Vec<_>>();
// Forward and inverse FFT
let forward_result = fft_settings.fft_fr(&starting_data, false).unwrap();
let inverse_result = fft_settings.fft_fr(&forward_result, true).unwrap();
for (i, data) in starting_data.iter().enumerate() {
assert!(data.equals(&inverse_result[i]));
}
}
/// Check the inverse FFT operation on precomputed values
pub fn inverse_fft<TFr: Fr, TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>>() {
#[rustfmt::skip]
let inv_fft_expected: [[u64; 4]; 16] =
[
[0x7fffffff80000008, 0xa9ded2017fff2dff, 0x199cec0404d0ec02, 0x39f6d3a994cebea4],
[0xef296e7ffb8ca216, 0xd5b902cbcef9c1b6, 0xf06dfe5c7fca260d, 0x13993b7d05187205],
[0xe930fdda2306c7d4, 0x40e02aff48e2b16b, 0x83a712d1dd818c8f, 0x5dbc603bc53c7a3a],
[0xf9925986d0d25e90, 0xcdf85d0a339d7782, 0xee7a9a5f0410e423, 0x2e0d216170831056],
[0x80007fff80000000, 0x1fe05202bb00adff, 0x6045d26b3fd26e6b, 0x39f6d3a994cebea4],
[0x27325dd08ac4cee9, 0xcbb94f168ddacca9, 0x6843be68485784b1, 0x5a6faf9039451673],
[0xe92ffdda2306c7d4, 0x54dd2afcd2dfb16b, 0xf6554603677e87be, 0x5dbc603bc53c7a39],
[0x1cc772c9b57f126f, 0xfb73f4d33d3116dd, 0x4f9388c8d80abcf9, 0x3ffbc9abcdda7821],
[0x7fffffff80000000, 0xa9ded2017fff2dff, 0x199cec0404d0ec02, 0x39f6d3a994cebea4],
[0xe3388d354a80ed91, 0x5849af2fc2cd4521, 0xe3a64f3f31971b0b, 0x33f1dda75bc30526],
[0x16d00224dcf9382c, 0xfee079062d1eaa93, 0x3ce49204a2235046, 0x163147176461030e],
[0xd8cda22e753b3117, 0x880454ec72238f55, 0xcaf6199fc14a5353, 0x197df7c2f05866d4],
[0x7fff7fff80000000, 0x33dd520044fdadff, 0xd2f4059cc9cf699a, 0x39f6d3a994cebea3],
[0x066da6782f2da170, 0x85c546f8cc60e47c, 0x44bf3da90590f3e1, 0x45e085f1b91a6cf1],
[0x16cf0224dcf9382c, 0x12dd7903b71baa93, 0xaf92c5362c204b76, 0x163147176461030d],
[0x10d6917f04735dea, 0x7e04a13731049a48, 0x42cbd9ab89d7b1f7, 0x60546bd624850b42]
];
let fft_settings = TFFTSettings::new(4).unwrap();
let data = (0..fft_settings.get_max_width())
.map(|i| TFr::from_u64(i as u64))
.collect::<Vec<_>>();
let forward_result = fft_settings.fft_fr(&data, true).unwrap();
assert_eq!(inv_fft_expected.len(), fft_settings.get_max_width());
for i in 0..inv_fft_expected.len() {
let expected = TFr::from_u64_arr(&inv_fft_expected[i]);
assert!(expected.equals(&forward_result[i]));
}
}
/// Check that stride is normalized when roots of different precision are used
pub fn stride_fft<TFr: Fr, TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>>() {
let size1: usize = 9;
let size2: usize = 12;
let width: usize = 1 << size1;
let fft_settings1 = TFFTSettings::new(size1).unwrap();
let fft_settings2 = TFFTSettings::new(size2).unwrap();
let data = (0..width)
.map(|i| TFr::from_u64(i as u64))
.collect::<Vec<_>>();
let result1 = fft_settings1.fft_fr(&data, false).unwrap();
let result2 = fft_settings2.fft_fr(&data, false).unwrap();
for (i, r1) in result1.iter().enumerate() {
assert!(r1.equals(&result2[i]));
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/recover.rs | kzg-bench/src/tests/recover.rs | use kzg::FFTFr;
use kzg::FFTSettings;
use kzg::Fr;
use kzg::Poly;
use kzg::PolyRecover;
use rand::seq::SliceRandom;
use rand::thread_rng;
use std::convert::TryInto;
pub fn recover_simple<
TFr: Fr,
TFTTSettings: FFTSettings<TFr> + FFTFr<TFr>,
TPoly: Poly<TFr>,
TPolyRecover: PolyRecover<TFr, TPoly, TFTTSettings>,
>() {
let fs = TFTTSettings::new(2).unwrap();
let max_width: usize = fs.get_max_width();
let mut poly = vec![TFr::zero(); max_width];
for (i, p) in poly.iter_mut().enumerate().take(max_width / 2) {
*p = TFr::from_u64(i.try_into().unwrap());
}
//I think it is not needed, since vec! is set as Fr::zero(), but leaving just in case
// for i in (max_width / 2)..max_width {
// poly[i] = TFr::zero();
// }
let data = fs.fft_fr(&poly, false).unwrap();
let samples: [Option<TFr>; 4] = [Some(data[0].clone()), None, None, Some(data[3].clone())];
let recovered = TPolyRecover::recover_poly_from_samples(&samples, &fs).unwrap();
//Check recovered data
assert_eq!(data.len(), max_width);
for (i, d) in data.iter().enumerate() {
assert!(d.equals(&recovered.get_coeff_at(i)));
}
let mut recovered_vec: Vec<TFr> = vec![];
for i in 0..max_width {
recovered_vec.push(recovered.get_coeff_at(i));
}
//Also check against original coefficients
let back = fs.fft_fr(&recovered_vec, true).unwrap();
for (i, p) in poly.iter().enumerate().take(max_width / 2) {
assert!(p.equals(&back[i]));
}
for p in poly.iter().take(max_width).skip(max_width / 2) {
assert!(p.is_zero());
}
}
pub fn recover_random<
TFr: Fr,
TFTTSettings: FFTSettings<TFr> + FFTFr<TFr>,
TPoly: Poly<TFr>,
TPolyRecover: PolyRecover<TFr, TPoly, TFTTSettings>,
>() {
let fs = TFTTSettings::new(12).unwrap();
let max_width: usize = fs.get_max_width();
let mut poly = vec![TFr::zero(); max_width];
for (i, p) in poly.iter_mut().enumerate().take(max_width / 2) {
*p = TFr::from_u64(i.try_into().unwrap());
}
let data = fs.fft_fr(&poly, false).unwrap();
//Having half of the data is the minimum
let mut known_ratio: f64 = 0.5;
while known_ratio < 1.0 {
let known: u64 = (max_width as f64 * known_ratio) as u64;
for _ in 0..4 {
let samples = random_missing(data.clone(), max_width, known);
let recovered = TPolyRecover::recover_poly_from_samples(&samples, &fs).unwrap();
//Assert
assert_eq!(data.len(), max_width);
for (i, d) in data.iter().enumerate() {
assert!(d.equals(&recovered.get_coeff_at(i)));
}
let recovered_vec = (0..max_width)
.map(|i| recovered.get_coeff_at(i))
.collect::<Vec<_>>();
//Also check against original coefficients
let back = fs.fft_fr(&recovered_vec, true).unwrap();
for i in 0..(max_width / 2) {
assert!(poly[i].equals(&back[i]));
}
for p in poly.iter().take(max_width).skip(max_width / 2) {
assert!(p.is_zero());
}
}
//loop increment
known_ratio += 0.05;
}
}
pub fn more_than_half_missing<
TFr: Fr,
TFTTSettings: FFTSettings<TFr> + FFTFr<TFr>,
TPoly: Poly<TFr>,
TPolyRecover: PolyRecover<TFr, TPoly, TFTTSettings>,
>() {
let fs = TFTTSettings::new(2).unwrap();
let max_width: usize = fs.get_max_width();
let mut poly = vec![TFr::zero(); max_width];
for (i, p) in poly.iter_mut().enumerate().take(max_width / 2) {
*p = TFr::from_u64(i.try_into().unwrap());
}
let data = fs.fft_fr(&poly, false).unwrap();
let samples: [Option<TFr>; 4] = [Some(data[0].clone()), None, None, None];
assert!(TPolyRecover::recover_poly_from_samples(&samples, &fs).is_err());
assert!(TPolyRecover::recover_poly_from_samples(&[None], &fs).is_err());
}
fn random_missing<TFr: Fr>(data: Vec<TFr>, len_data: usize, known: u64) -> Vec<Option<TFr>> {
let mut missing_idx: Vec<usize> = vec![];
let mut with_missing = data.into_iter().map(Some).collect::<Vec<_>>();
for i in 0..len_data {
missing_idx.push(i);
}
missing_idx.shuffle(&mut thread_rng());
for missing_idx in missing_idx.into_iter().take(len_data - (known as usize)) {
with_missing[missing_idx] = None;
}
with_missing
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/msm/mod.rs | kzg-bench/src/tests/msm/mod.rs | pub mod batch_adder;
pub mod bucket_msm;
pub mod msm_slice;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/msm/msm_slice.rs | kzg-bench/src/tests/msm/msm_slice.rs | use kzg::{msm::arkmsm::arkmsm_msm::VariableBaseMSM, Scalar256};
pub fn test_msm_slice_window_size_1() {
let scalar = Scalar256::from_u64_s(0b101);
let mut slices: Vec<u32> = vec![0; 3];
VariableBaseMSM::msm_slice(scalar, &mut slices, 1);
assert!(slices.iter().eq([1, 0, 1].iter()));
}
pub fn test_msm_slice_window_size_2() {
let scalar = Scalar256::from_u64_s(0b000110);
let mut slices: Vec<u32> = vec![0; 3];
VariableBaseMSM::msm_slice(scalar, &mut slices, 2);
assert!(slices.iter().eq([2, 1, 0].iter()));
}
pub fn test_msm_slice_window_size_3() {
let scalar = Scalar256::from_u64_s(0b010111000);
let mut slices: Vec<u32> = vec![0; 3];
VariableBaseMSM::msm_slice(scalar, &mut slices, 3);
assert!(slices.iter().eq([0, 0x80000001, 3].iter()));
}
pub fn test_msm_slice_window_size_16() {
let scalar = Scalar256::from_u64_s(0x123400007FFF);
let mut slices: Vec<u32> = vec![0; 3];
VariableBaseMSM::msm_slice(scalar, &mut slices, 16);
assert!(slices.iter().eq([0x7FFF, 0, 0x1234].iter()));
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/msm/bucket_msm.rs | kzg-bench/src/tests/msm/bucket_msm.rs | use kzg::msm::arkmsm::bucket_msm::BucketMSM;
use kzg::msm::arkmsm::glv::endomorphism;
use kzg::{G1Affine, G1Fp, G1ProjAddAffine, G1};
pub fn test_process_point_and_slices_deal_two_points<
TG1: G1,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>() {
let window_bits = 15u32;
let mut bucket_msm = BucketMSM::<TG1, TG1Fp, TG1Affine, TProjAddAffine>::new(
30u32,
window_bits,
128u32,
4096u32,
);
let p = TG1Affine::into_affine(&G1::rand());
let q = TG1Affine::into_affine(&G1::rand());
bucket_msm.process_point_and_slices(&p, &[1u32, 3u32]);
bucket_msm.process_point_and_slices(&q, &[2u32, 3u32]);
bucket_msm.process_complete();
assert_eq!(bucket_msm.buckets[0], p);
assert_eq!(bucket_msm.buckets[1], q);
// FIXME: Maybe remove that to proj
assert_eq!(
bucket_msm.buckets[2 + (1 << bucket_msm.bucket_bits)].to_proj(),
p.to_proj().add(&q.to_proj())
);
}
pub fn test_process_point_and_slices_deal_three_points<
TG1: G1,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>() {
let window_bits = 15u32;
let mut bucket_msm = BucketMSM::<TG1, TG1Fp, TG1Affine, TProjAddAffine>::new(
45u32,
window_bits,
128u32,
4096u32,
);
let p = TG1Affine::into_affine(&G1::rand());
let q = TG1Affine::into_affine(&G1::rand());
let r = TG1Affine::into_affine(&G1::rand());
bucket_msm.process_point_and_slices(&p, &[1u32, 3u32, 4u32]);
bucket_msm.process_point_and_slices(&q, &[2u32, 3u32, 4u32]);
bucket_msm.process_point_and_slices(&r, &[2u32, 3u32, 5u32]);
bucket_msm.process_complete();
assert_eq!(bucket_msm.buckets[0], p);
assert_eq!(
bucket_msm.buckets[1].to_proj(),
q.to_proj().add(&r.to_proj())
);
assert_eq!(
bucket_msm.buckets[2 + (1 << bucket_msm.bucket_bits)].to_proj(),
p.to_proj().add(&q.to_proj()).add(&r.to_proj())
);
assert_eq!(
bucket_msm.buckets[3 + (2 << bucket_msm.bucket_bits)].to_proj(),
p.to_proj().add(&q.to_proj())
);
assert_eq!(bucket_msm.buckets[4 + (2 << bucket_msm.bucket_bits)], r);
}
pub fn test_process_point_and_slices_glv_deal_two_points<
TG1: G1,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>() {
let window_bits = 15u32;
let mut bucket_msm = BucketMSM::<TG1, TG1Fp, TG1Affine, TProjAddAffine>::new(
30u32,
window_bits,
128u32,
4096u32,
);
let mut p = TG1Affine::into_affine(&G1::rand());
let mut q = TG1Affine::into_affine(&G1::rand());
bucket_msm.process_point_and_slices_glv(&p, &[1u32, 3u32], &[4u32, 6u32], false, false);
bucket_msm.process_point_and_slices_glv(&q, &[2u32, 3u32], &[5u32, 6u32], false, false);
bucket_msm.process_complete();
assert_eq!(bucket_msm.buckets[0], p);
assert_eq!(bucket_msm.buckets[1], q);
assert_eq!(
bucket_msm.buckets[2 + (1 << bucket_msm.bucket_bits)].to_proj(),
p.to_proj().add(&q.to_proj())
);
endomorphism(&mut p);
endomorphism(&mut q);
assert_eq!(bucket_msm.buckets[3], p);
assert_eq!(bucket_msm.buckets[4], q);
assert_eq!(
bucket_msm.buckets[5 + (1 << bucket_msm.bucket_bits)].to_proj(),
p.to_proj().add(&q.to_proj())
);
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/tests/msm/batch_adder.rs | kzg-bench/src/tests/msm/batch_adder.rs | use kzg::{msm::arkmsm::batch_adder::BatchAdder, G1Affine, G1Fp, G1};
pub fn test_phase_one_zero_or_neg<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(4);
batch_adder.batch_add_phase_one(&TG1Affine::zero(), &TG1Affine::zero(), 0);
let p_rand = TG1::rand();
let p_affine = TG1Affine::into_affine(&p_rand);
let mut neg_p_affine = p_affine;
neg_p_affine.y_mut().neg_assign();
batch_adder.batch_add_phase_one(&p_affine, &neg_p_affine, 0);
}
pub fn test_phase_one_p_add_p<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(4);
let p = TG1Affine::into_affine(&TG1::rand());
let acc = p;
batch_adder.batch_add_phase_one(&acc, &p, 0);
assert!(batch_adder.inverses[0].is_one());
assert_eq!(batch_adder.inverse_state, p.y().add_fp(p.y()));
}
pub fn test_phase_one_p_add_q<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(4);
let p = TG1Affine::into_affine(&TG1::rand());
let q = TG1Affine::into_affine(&TG1::rand());
batch_adder.batch_add_phase_one(&p, &q, 0);
assert!(batch_adder.inverses[0].is_one());
assert_eq!(batch_adder.inverse_state, q.x().sub_fp(p.x()));
}
pub fn test_phase_one_p_add_q_twice<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(4);
let p = TG1Affine::into_affine(&TG1::rand());
let q = TG1Affine::into_affine(&TG1::rand());
batch_adder.batch_add_phase_one(&p, &q, 0);
batch_adder.batch_add_phase_one(&p, &q, 0);
assert_eq!(batch_adder.inverses[0], q.x().sub_fp(p.x()));
assert_eq!(
batch_adder.inverse_state,
(q.x().sub_fp(p.x())).mul_fp(&q.x().sub_fp(p.x()))
);
}
pub fn test_phase_two_zero_add_p<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(4);
let p = TG1Affine::into_affine(&TG1::rand());
let mut acc = G1Affine::zero();
batch_adder.batch_add_phase_two(&mut acc, &p, 0);
assert_eq!(acc, p);
}
pub fn test_phase_two_p_add_neg<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(4);
let mut p = TG1Affine::into_affine(&TG1::rand());
let mut acc = p;
p.y_mut().neg_assign();
batch_adder.batch_add_phase_two(&mut acc, &p, 0);
assert_eq!(acc, G1Affine::zero());
}
pub fn test_phase_two_p_add_q<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(4);
let acc_proj = TG1::rand();
let mut p = TG1Affine::into_affine(&acc_proj);
let mut acc = p;
*p.x_mut() = p.x().add_fp(p.x());
batch_adder.inverses[0] = (p.x().sub_fp(acc.x())).inverse().unwrap();
batch_adder.batch_add_phase_two(&mut acc, &p, 0);
assert_eq!(acc, TG1Affine::into_affine(&acc_proj.add(&p.to_proj())));
}
pub fn test_phase_two_p_add_p<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(4);
let acc_proj = TG1::rand();
// let acc_proj = TG1::from_bytes(&[180, 100, 110, 26, 178, 124, 0, 160, 32, 73, 34, 58, 143, 58, 42, 253, 109, 115, 30, 187, 250, 105, 87, 92, 20, 52, 138, 74, 220, 53, 87, 230, 205, 140, 221, 30, 177, 65, 96, 179, 92, 116, 71, 234, 74, 149, 140, 221]).unwrap();
// eprintln!("{:?}", acc_proj.to_bytes());
let p = TG1Affine::into_affine(&acc_proj);
let mut acc = p;
let p_sqr = p.y().add_fp(p.y());
let p_sqr_inv = p_sqr.inverse().unwrap();
batch_adder.inverses[0] = p_sqr_inv;
batch_adder.batch_add_phase_two(&mut acc, &p, 0);
assert_eq!(acc.to_proj(), acc_proj.add_or_dbl(&p.to_proj()));
}
pub fn test_batch_add<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(10);
let mut buckets: Vec<TG1Affine> = (0..10)
.map(|_| TG1Affine::into_affine(&TG1::rand()))
.collect();
let points: Vec<TG1Affine> = (0..10)
.map(|_| TG1Affine::into_affine(&TG1::rand()))
.collect();
let tmp = buckets.clone();
batch_adder.batch_add(&mut buckets, &points);
for i in 0..10 {
assert_eq!(
buckets[i],
TG1Affine::into_affine(&tmp[i].to_proj().add(&points[i].to_proj()))
);
}
}
pub fn test_batch_add_step_n<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(10);
let mut buckets: Vec<TG1Affine> = (0..10)
.map(|_| TG1Affine::into_affine(&TG1::rand()))
.collect();
let points: Vec<TG1Affine> = (0..10)
.map(|_| TG1Affine::into_affine(&TG1::rand()))
.collect();
let tmp = buckets.clone();
batch_adder.batch_add_step_n(&mut buckets, 1, &points, 2, 3);
for i in 0..3 {
assert_eq!(
buckets[i],
TG1Affine::into_affine(&tmp[i].to_proj().add(&points[i * 2].to_proj()))
);
}
}
pub fn test_batch_add_indexed<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(10);
let mut buckets: Vec<TG1Affine> = (0..10)
.map(|_| TG1Affine::into_affine(&TG1::rand()))
.collect();
let points: Vec<TG1Affine> = (0..10)
.map(|_| TG1Affine::into_affine(&TG1::rand()))
.collect();
let tmp = buckets.clone();
batch_adder.batch_add_indexed(&mut buckets, &[0, 2, 4], &points, &[0, 2, 4]);
for i in (0..5).step_by(2) {
assert_eq!(
buckets[i],
TG1Affine::into_affine(&tmp[i].to_proj().add(&points[i].to_proj()))
);
}
}
pub fn test_batch_add_indexed_single_bucket<TG1: G1, TGFp: G1Fp, TG1Affine: G1Affine<TG1, TGFp>>() {
let mut batch_adder = BatchAdder::<TG1, TGFp, TG1Affine>::new(1);
let mut buckets: Vec<TG1Affine> = (0..1)
.map(|_| TG1Affine::into_affine(&TG1::rand()))
.collect();
let points: Vec<TG1Affine> = (0..1)
.map(|_| TG1Affine::into_affine(&TG1::rand()))
.collect();
let tmp = buckets.clone();
batch_adder.batch_add_indexed(&mut buckets, &[0], &points, &[0]);
assert_eq!(
buckets[0],
TG1Affine::into_affine(&tmp[0].to_proj().add(&points[0].to_proj()))
);
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/trusted_setup.rs | kzg-bench/src/benches/trusted_setup.rs | use criterion::Criterion;
use kzg::{
eip_4844::TRUSTED_SETUP_PATH, FFTSettings, Fr, G1Affine, G1Fp, G1GetFp, G1Mul, G1ProjAddAffine,
KZGSettings, Poly, G1, G2,
};
use std::{fs::File, io::Read, path::PathBuf};
#[allow(clippy::type_complexity)]
pub fn bench_load_trusted_setup<
TFr: Fr + std::fmt::Debug,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
c: &mut Criterion,
load_trusted_setup_file: &dyn Fn(&str) -> Result<TKZGSettings, String>,
load_trusted_setup: &dyn Fn(&[u8], &[u8], &[u8]) -> Result<TKZGSettings, String>,
) {
let path = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join(TRUSTED_SETUP_PATH)
.to_string_lossy()
.to_string();
c.bench_function("load_trusted_setup_file", |b| {
b.iter(|| {
let _ = load_trusted_setup_file(path.as_str()).unwrap();
});
});
c.bench_function("load_trusted_setup", |b| {
let mut file = File::open(path.clone()).unwrap();
let mut source = String::new();
file.read_to_string(&mut source).unwrap();
let bytes = kzg::eip_4844::load_trusted_setup_string(source.as_str()).unwrap();
b.iter(|| {
let _ = load_trusted_setup(&bytes.0, &bytes.1, &bytes.2).unwrap();
});
});
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/das.rs | kzg-bench/src/benches/das.rs | use criterion::Criterion;
use kzg::{DASExtension, FFTSettings, Fr};
const BENCH_SCALE: usize = 15;
pub fn bench_das_extension<TFr: Fr, TFFTSettings: FFTSettings<TFr> + DASExtension<TFr>>(
c: &mut Criterion,
) {
let fft_settings = TFFTSettings::new(BENCH_SCALE).unwrap();
let data: Vec<TFr> = vec![TFr::rand(); fft_settings.get_max_width() / 2];
let id = format!("bench_DAS_extension scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| b.iter(|| fft_settings.das_fft_extension(&data)));
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/eip_4844.rs | kzg-bench/src/benches/eip_4844.rs | use std::env::set_current_dir;
use crate::tests::eip_4844::{generate_random_blob_bytes, generate_random_field_element_bytes};
use criterion::{BatchSize, BenchmarkId, Criterion, Throughput};
use kzg::eip_4844::TRUSTED_SETUP_PATH;
use kzg::{
FFTSettings, Fr, G1Affine, G1Fp, G1GetFp, G1Mul, G1ProjAddAffine, KZGSettings, Poly, G1, G2,
};
#[allow(clippy::type_complexity)]
#[allow(clippy::too_many_arguments)]
pub fn bench_eip_4844<
TFr: Fr,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp>,
TG2: G2,
TPoly: Poly<TFr>,
TFFTSettings: FFTSettings<TFr>,
TKZGSettings: KZGSettings<TFr, TG1, TG2, TFFTSettings, TPoly, TG1Fp, TG1Affine, TG1ProjAddAffine>,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
c: &mut Criterion,
load_trusted_setup: &dyn Fn(&str) -> Result<TKZGSettings, String>,
blob_to_kzg_commitment: &dyn Fn(&[TFr], &TKZGSettings) -> Result<TG1, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<TFr>, String>,
compute_kzg_proof: &dyn Fn(&[TFr], &TFr, &TKZGSettings) -> Result<(TG1, TFr), String>,
verify_kzg_proof: &dyn Fn(&TG1, &TFr, &TFr, &TG1, &TKZGSettings) -> Result<bool, String>,
compute_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TKZGSettings) -> Result<TG1, String>,
verify_blob_kzg_proof: &dyn Fn(&[TFr], &TG1, &TG1, &TKZGSettings) -> Result<bool, String>,
verify_blob_kzg_proof_batch: &dyn Fn(
&[Vec<TFr>],
&[TG1],
&[TG1],
&TKZGSettings,
) -> Result<bool, String>,
) {
set_current_dir(env!("CARGO_MANIFEST_DIR")).unwrap();
let ts = load_trusted_setup(TRUSTED_SETUP_PATH).unwrap();
let mut rng = rand::thread_rng();
const MAX_COUNT: usize = 64;
let blobs: Vec<Vec<TFr>> = (0..MAX_COUNT)
.map(|_| {
let blob_bytes = generate_random_blob_bytes(&mut rng);
bytes_to_blob(&blob_bytes).unwrap()
})
.collect();
let commitments: Vec<TG1> = blobs
.iter()
.map(|blob| blob_to_kzg_commitment(blob, &ts).unwrap())
.collect();
let proofs: Vec<TG1> = blobs
.iter()
.zip(commitments.iter())
.map(|(blob, commitment)| compute_blob_kzg_proof(blob, commitment, &ts).unwrap())
.collect();
let fields: Vec<TFr> = (0..MAX_COUNT)
.map(|_| {
let fr_bytes = generate_random_field_element_bytes(&mut rng);
TFr::from_bytes(&fr_bytes).unwrap()
})
.collect();
c.bench_function("blob_to_kzg_commitment", |b| {
b.iter(|| blob_to_kzg_commitment(blobs.first().unwrap(), &ts))
});
c.bench_function("compute_kzg_proof", |b| {
b.iter(|| compute_kzg_proof(blobs.first().unwrap(), fields.first().unwrap(), &ts))
});
c.bench_function("verify_kzg_proof", |b| {
b.iter(|| {
verify_kzg_proof(
commitments.first().unwrap(),
fields.first().unwrap(),
fields.first().unwrap(),
proofs.first().unwrap(),
&ts,
)
.unwrap()
})
});
c.bench_function("compute_blob_kzg_proof", |b| {
b.iter(|| compute_blob_kzg_proof(blobs.first().unwrap(), commitments.first().unwrap(), &ts))
});
c.bench_function("verify_blob_kzg_proof", |b| {
b.iter(|| {
verify_blob_kzg_proof(
blobs.first().unwrap(),
commitments.first().unwrap(),
proofs.first().unwrap(),
&ts,
)
.unwrap()
})
});
let mut group = c.benchmark_group("verify_blob_kzg_proof_batch");
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<Vec<TFr>>>();
let commitments_subset = commitments
.clone()
.into_iter()
.take(count)
.collect::<Vec<TG1>>();
let proofs_subset =
proofs.clone().into_iter().take(count).collect::<Vec<TG1>>();
(blobs_subset, commitments_subset, proofs_subset)
},
|(blobs_subset, commitments_subset, proofs_subset)| {
verify_blob_kzg_proof_batch(
blobs_subset,
commitments_subset,
proofs_subset,
&ts,
)
.unwrap()
},
BatchSize::LargeInput,
);
});
}
group.finish();
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/fk20.rs | kzg-bench/src/benches/fk20.rs | use criterion::Criterion;
use kzg::{
common_utils::{is_power_of_two, log2_pow2},
EcBackend, FFTSettings, FK20MultiSettings, FK20SingleSettings, Fr, KZGSettings, Poly,
};
use rand::{thread_rng, RngCore};
pub const SECRET: [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,
];
const BENCH_SCALE: usize = 14;
#[allow(clippy::type_complexity)]
pub fn bench_fk_single_da<
B: EcBackend,
TFK20SingleSettings: FK20SingleSettings<
B::Fr,
B::G1,
B::G2,
B::FFTSettings,
B::Poly,
B::KZGSettings,
B::G1Fp,
B::G1Affine,
B::G1ProjAddAffine,
>,
>(
c: &mut Criterion,
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
let mut rng = thread_rng();
let coeffs: Vec<u64> = vec![rng.next_u64(); 1 << (BENCH_SCALE - 1)];
let poly_len: usize = coeffs.len();
let n_len: usize = 1 << BENCH_SCALE;
let secrets_len = n_len;
assert!(n_len >= 2 * poly_len);
let mut p = B::Poly::new(poly_len);
for (i, &coeff) in coeffs.iter().enumerate() {
p.set_coeff_at(i, &B::Fr::from_u64(coeff));
}
// Initialise the secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = B::FFTSettings::new(BENCH_SCALE).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 16).unwrap();
let fk = TFK20SingleSettings::new(&ks, 2 * poly_len).unwrap();
// Commit to the polynomial
ks.commit_to_poly(&p).unwrap();
// Generate the proofs
let id = format!("bench_fk_single_da scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| b.iter(|| fk.data_availability(&p).unwrap()));
}
#[allow(clippy::type_complexity)]
pub fn bench_fk_multi_da<
B: EcBackend,
TFK20MultiSettings: FK20MultiSettings<
B::Fr,
B::G1,
B::G2,
B::FFTSettings,
B::Poly,
B::KZGSettings,
B::G1Fp,
B::G1Affine,
B::G1ProjAddAffine,
>,
>(
c: &mut Criterion,
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
let n = 1 << BENCH_SCALE;
let chunk_len = 16;
let vv: Vec<u64> = vec![1, 2, 3, 4, 7, 8, 9, 10, 13, 14, 1, 15, 1, 1000, 134, 33];
assert!(is_power_of_two(n));
assert!(is_power_of_two(chunk_len));
assert_eq!(n % 16, 0);
assert!(n >= chunk_len);
let chunk_count: usize = n / chunk_len;
let secrets_len: usize = 2 * n;
let width: usize = log2_pow2(secrets_len);
// Initialise the secrets and data structures
let (s1, s2, s3) = generate_trusted_setup(secrets_len, SECRET);
let fs = B::FFTSettings::new(width).unwrap();
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 16).unwrap();
let fk = TFK20MultiSettings::new(&ks, secrets_len, chunk_len).unwrap();
// Create a test polynomial of size n that's independent of chunk_len
let mut p = B::Poly::new(n);
for i in 0..chunk_count {
for j in 0..chunk_len {
let p_index = i * chunk_len + j;
let v_index = p_index % 16;
let mut v = vv[v_index];
let tmp: u64 = (i * chunk_len / 16) as u64;
if v_index == 3 {
v += tmp;
}
if v_index == 5 {
v += tmp * tmp;
}
p.set_coeff_at(p_index, &B::Fr::from_u64(v));
if v_index == 12 {
p.set_coeff_at(p_index, &p.get_coeff_at(p_index).negate());
}
if v_index == 14 {
p.set_coeff_at(p_index, &p.get_coeff_at(p_index).negate());
}
}
}
// Commit to the polynomial
ks.commit_to_poly(&p).unwrap();
let id = format!("bench_fk_multi_da scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| b.iter(|| fk.data_availability(&p).unwrap()));
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/eip_7594.rs | kzg-bench/src/benches/eip_7594.rs | use std::path::PathBuf;
use crate::tests::eip_4844::generate_random_blob_bytes;
use criterion::{BenchmarkId, Criterion};
use kzg::{eip_4844::TRUSTED_SETUP_PATH, eth, EcBackend, DAS};
pub fn get_partial_cells<T: Clone>(
cells: &[T],
chunk_size: usize,
m: usize,
) -> (Vec<usize>, Vec<T>) {
let mut cell_indices = Vec::new();
let mut partial_cells = Vec::new();
for (i, cell) in cells.chunks(chunk_size).enumerate() {
if i % m != 0 {
cell_indices.push(i);
partial_cells.extend_from_slice(cell);
}
}
(cell_indices, partial_cells)
}
#[allow(clippy::type_complexity)]
#[allow(clippy::too_many_arguments)]
pub fn bench_eip_7594<B: EcBackend>(
c: &mut Criterion,
load_trusted_setup: &dyn Fn(&str) -> Result<B::KZGSettings, String>,
bytes_to_blob: &dyn Fn(&[u8]) -> Result<Vec<B::Fr>, String>,
blob_to_kzg_commitment: &dyn Fn(&[B::Fr], &B::KZGSettings) -> Result<B::G1, String>,
) where
B::KZGSettings: Sync,
{
let ts = load_trusted_setup(
PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join(TRUSTED_SETUP_PATH)
.to_str()
.unwrap(),
)
.unwrap();
let mut rng = rand::thread_rng();
const MAX_COUNT: usize = 64;
let blobs: Vec<[u8; eth::BYTES_PER_BLOB]> = (0..MAX_COUNT)
.map(|_| generate_random_blob_bytes(&mut rng))
.collect();
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 mut cells =
vec![B::Fr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
let mut proofs = vec![B::G1::default(); eth::CELLS_PER_EXT_BLOB];
let blob = bytes_to_blob(blob).unwrap();
<B::KZGSettings as DAS<B>>::compute_cells_and_kzg_proofs(
&ts,
Some(&mut cells),
Some(&mut proofs),
&blob,
)
.unwrap();
blob_cells.push(cells);
blob_cell_proofs.push(proofs);
blob_commitments.push(blob_to_kzg_commitment(&blob, &ts).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(|| {
let blob_bytes = blobs.first().unwrap();
let blob = bytes_to_blob(blob_bytes).unwrap();
let mut recv_cells =
vec![B::Fr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
let mut recv_proofs = vec![B::G1::default(); eth::CELLS_PER_EXT_BLOB];
<B::KZGSettings as DAS<B>>::compute_cells_and_kzg_proofs(
&ts,
Some(&mut recv_cells),
Some(&mut recv_proofs),
&blob,
)
.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], eth::FIELD_ELEMENTS_PER_CELL, i);
group.bench_function(BenchmarkId::from_parameter(percent_missing), |b| {
b.iter(|| {
let mut recv_cells =
vec![B::Fr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
let mut recv_proofs = vec![B::G1::default(); eth::CELLS_PER_EXT_BLOB];
<B::KZGSettings as DAS<B>>::recover_cells_and_kzg_proofs(
&ts,
&mut recv_cells,
Some(&mut recv_proofs),
&cell_indices,
&partial_cells,
)
.unwrap();
});
});
}
group.finish();
let mut group =
c.benchmark_group("recover_cells_and_kzg_proofs_batch - whole matrix (% missing)");
group.sample_size(10);
for i in [2, 4, 8] {
let percent_missing = 100.0 / (i as f64);
let (cell_indices, partial_cells) = blob_cells
.iter()
.map(|cells| get_partial_cells(cells, eth::FIELD_ELEMENTS_PER_CELL, i))
.collect::<(Vec<_>, Vec<_>)>();
group.bench_function(BenchmarkId::from_parameter(percent_missing), |b| {
b.iter(|| {
<B::KZGSettings as DAS<B>>::recover_cells_and_kzg_proofs_batch(
&ts,
&cell_indices,
&partial_cells,
)
.unwrap();
})
});
}
group.finish();
let mut group = c.benchmark_group("recover_cells_and_kzg_proofs (missing)");
for i in 1..=5 {
let modulo = eth::CELLS_PER_EXT_BLOB.div_ceil(i);
let (cell_indices, partial_cells) =
get_partial_cells(&blob_cells[0], eth::FIELD_ELEMENTS_PER_CELL, modulo);
group.bench_function(BenchmarkId::from_parameter(i), |b| {
b.iter(|| {
let mut recv_cells =
vec![B::Fr::default(); eth::CELLS_PER_EXT_BLOB * eth::FIELD_ELEMENTS_PER_CELL];
let mut recv_proofs = vec![B::G1::default(); eth::CELLS_PER_EXT_BLOB];
<B::KZGSettings as DAS<B>>::recover_cells_and_kzg_proofs(
&ts,
&mut recv_cells,
Some(&mut recv_proofs),
&cell_indices,
&partial_cells,
)
.unwrap();
});
});
}
group.finish();
c.bench_function("verify_cell_kzg_proof_batch", |b| {
let mut cell_commitments = Vec::with_capacity(MAX_COUNT * eth::CELLS_PER_EXT_BLOB);
let mut cell_indices = Vec::with_capacity(MAX_COUNT * eth::CELLS_PER_EXT_BLOB);
let mut cells = Vec::with_capacity(MAX_COUNT * eth::CELLS_PER_EXT_BLOB);
let mut cell_proofs = Vec::with_capacity(MAX_COUNT * eth::CELLS_PER_EXT_BLOB);
for (row_index, blob_cell) in blob_cells.iter().enumerate() {
for (cell_index, cell) in blob_cell.chunks(eth::FIELD_ELEMENTS_PER_CELL).enumerate() {
cell_commitments.push(blob_commitments[row_index].clone());
cell_indices.push(cell_index);
cells.extend_from_slice(cell);
cell_proofs.push(blob_cell_proofs[row_index][cell_index].clone());
}
}
b.iter(|| {
let result = <B::KZGSettings as DAS<B>>::verify_cell_kzg_proof_batch(
&ts,
&cell_commitments,
&cell_indices,
&cells,
&cell_proofs,
)
.unwrap();
assert!(result);
});
});
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 * eth::CELLS_PER_EXT_BLOB);
let mut cell_indices = Vec::with_capacity(i * eth::CELLS_PER_EXT_BLOB);
let mut cells = Vec::with_capacity(i * eth::CELLS_PER_EXT_BLOB);
let mut cell_proofs = Vec::with_capacity(i * eth::CELLS_PER_EXT_BLOB);
for (row_index, blob_cell) in blob_cells.iter().take(i).enumerate() {
for (cell_index, cell) in blob_cell.chunks(eth::FIELD_ELEMENTS_PER_CELL).enumerate()
{
cell_commitments.push(blob_commitments[row_index].clone());
cell_indices.push(cell_index);
cells.extend_from_slice(cell);
cell_proofs.push(blob_cell_proofs[row_index][cell_index].clone());
}
}
b.iter(|| {
let result = <B::KZGSettings as DAS<B>>::verify_cell_kzg_proof_batch(
&ts,
&cell_commitments,
&cell_indices,
&cells,
&cell_proofs,
)
.unwrap();
assert!(result);
});
});
}
group.finish();
let mut group = c.benchmark_group("verify_cell_kzg_proof_batch (columns)");
for i in (0..=eth::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
.chunks(eth::FIELD_ELEMENTS_PER_CELL)
.take(i)
.enumerate()
{
cell_commitments.push(blob_commitments[row_index].clone());
cell_indices.push(cell_index);
cells.extend_from_slice(cell);
cell_proofs.push(blob_cell_proofs[row_index][cell_index].clone());
}
}
b.iter(|| {
let result = <B::KZGSettings as DAS<B>>::verify_cell_kzg_proof_batch(
&ts,
&cell_commitments,
&cell_indices,
&cells,
&cell_proofs,
)
.unwrap();
assert!(result);
});
});
}
group.finish();
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/poly.rs | kzg-bench/src/benches/poly.rs | use criterion::Criterion;
use kzg::{Fr, Poly};
const BENCH_SCALE: usize = 15;
pub fn bench_new_poly_div<TFr: Fr, TPoly: Poly<TFr>>(c: &mut Criterion) {
let dividend_length = 1 << BENCH_SCALE;
let divisor_length = dividend_length / 2;
let mut dividend = TPoly::new(dividend_length);
let mut divisor = TPoly::new(divisor_length);
// Randomize the polynomials' coefficients
for i in 0..dividend.len() {
dividend.set_coeff_at(i, &TFr::rand());
}
for i in 0..divisor.len() {
divisor.set_coeff_at(i, &TFr::rand());
}
// Ensure that the polynomials' orders correspond to their lengths
if dividend.get_coeff_at(dividend.len() - 1).is_zero() {
dividend.set_coeff_at(dividend.len() - 1, &TFr::one());
}
if divisor.get_coeff_at(divisor.len() - 1).is_zero() {
divisor.set_coeff_at(divisor.len() - 1, &TFr::one());
}
let id = format!("bench_new_poly_div scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| {
b.iter(|| {
dividend.div(&divisor).unwrap();
})
});
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/zero_poly.rs | kzg-bench/src/benches/zero_poly.rs | use criterion::Criterion;
use kzg::{FFTSettings, Fr, Poly, ZeroPoly};
use rand::seq::SliceRandom;
use rand::thread_rng;
const BENCH_SCALE: usize = 15;
pub fn bench_zero_poly<
TFr: Fr,
TFFTSettings: FFTSettings<TFr> + ZeroPoly<TFr, TPoly>,
TPoly: Poly<TFr>,
>(
c: &mut Criterion,
) {
let fs = TFFTSettings::new(BENCH_SCALE).unwrap();
let size = fs.get_max_width();
let mut missing = (0..size).collect::<Vec<_>>();
let mut rng = thread_rng();
missing.shuffle(&mut rng);
let id = format!("bench_zero_poly scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| {
b.iter(|| {
// Half missing leaves enough FFT computation space
fs.zero_poly_via_multiplication(size, &missing[0..(size / 2)])
.unwrap();
})
});
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/kzg.rs | kzg-bench/src/benches/kzg.rs | use criterion::Criterion;
use kzg::{EcBackend, FFTSettings, Fr, KZGSettings, Poly};
pub const SECRET: [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,
];
const BENCH_SCALE: usize = 15;
#[allow(clippy::type_complexity)]
pub fn bench_commit_to_poly<B: EcBackend>(
c: &mut Criterion,
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
let fs = B::FFTSettings::new(BENCH_SCALE).unwrap();
let (s1, s2, s3) = generate_trusted_setup(fs.get_max_width(), SECRET);
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 64).unwrap();
let mut poly = B::Poly::new(fs.get_max_width());
for i in 0..fs.get_max_width() {
poly.set_coeff_at(i, &B::Fr::rand());
}
let id = format!("bench_commit_to_poly scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| b.iter(|| ks.commit_to_poly(&poly).unwrap()));
}
#[allow(clippy::type_complexity)]
pub fn bench_compute_proof_single<B: EcBackend>(
c: &mut Criterion,
generate_trusted_setup: &dyn Fn(usize, [u8; 32usize]) -> (Vec<B::G1>, Vec<B::G1>, Vec<B::G2>),
) {
let fs = B::FFTSettings::new(BENCH_SCALE).unwrap();
let (s1, s2, s3) = generate_trusted_setup(fs.get_max_width(), SECRET);
let ks = B::KZGSettings::new(&s1, &s2, &s3, &fs, 64).unwrap();
let mut poly = B::Poly::new(fs.get_max_width());
for i in 0..fs.get_max_width() {
poly.set_coeff_at(i, &B::Fr::rand());
}
let id = format!("bench_compute_proof_single scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| {
b.iter(|| ks.compute_proof_single(&poly, &B::Fr::rand()).unwrap())
});
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/mod.rs | kzg-bench/src/benches/mod.rs | pub mod das;
pub mod eip_4844;
pub mod eip_7594;
pub mod fft;
pub mod fk20;
pub mod kzg;
pub mod lincomb;
pub mod poly;
pub mod recover;
pub mod trusted_setup;
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/kzg-bench/src/benches/lincomb.rs | kzg-bench/src/benches/lincomb.rs | use criterion::Criterion;
use kzg::{
msm::precompute::{precompute, PrecomputationTable},
Fr, G1Affine, G1Fp, G1GetFp, G1Mul, G1ProjAddAffine, G1,
};
#[allow(clippy::type_complexity)]
pub fn bench_g1_lincomb<
TFr: Fr + Copy,
TG1: G1 + G1Mul<TFr> + G1GetFp<TG1Fp> + Copy,
TG1Fp: G1Fp,
TG1Affine: G1Affine<TG1, TG1Fp>,
TG1ProjAddAffine: G1ProjAddAffine<TG1, TG1Fp, TG1Affine>,
>(
c: &mut Criterion,
g1_linear_combination: &dyn Fn(
&mut TG1,
&[TG1],
&[TFr],
usize,
Option<&PrecomputationTable<TFr, TG1, TG1Fp, TG1Affine, TG1ProjAddAffine>>,
),
) {
let npoints_npow = &std::env::var("BENCH_NPOW")
.unwrap_or("12".to_string())
.parse::<i32>()
.unwrap();
let num_points = 1usize << npoints_npow;
let points = (0..num_points).map(|_| TG1::rand()).collect::<Vec<_>>();
let scalars = (0..num_points).map(|_| TFr::rand()).collect::<Vec<_>>();
let id = format!("bench_g1_lincomb points: '{}'", num_points);
c.bench_function(&id, |b| {
b.iter(|| {
let mut out = TG1::default();
g1_linear_combination(
&mut out,
points.as_slice(),
scalars.as_slice(),
num_points,
None,
)
})
});
let precomputation =
precompute::<TFr, TG1, TG1Fp, TG1Affine, TG1ProjAddAffine>(&points, &[]).unwrap();
if precomputation.is_some() {
let id = format!(
"bench_g1_lincomb with precomputation points: '{}'",
num_points
);
c.bench_function(&id, |b| {
b.iter(|| {
let mut out = TG1::default();
g1_linear_combination(
&mut out,
points.as_slice(),
scalars.as_slice(),
num_points,
precomputation.as_ref(),
)
})
});
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/recover.rs | kzg-bench/src/benches/recover.rs | use criterion::{black_box, Criterion};
use kzg::{FFTFr, FFTSettings, Fr, Poly, PolyRecover};
use rand::Rng;
use std::convert::TryInto;
const BENCH_SCALE: usize = 15;
pub fn bench_recover<
TFr: Fr,
TFTTSettings: FFTSettings<TFr> + FFTFr<TFr>,
TPoly: Poly<TFr>,
TPolyRecover: PolyRecover<TFr, TPoly, TFTTSettings>,
>(
c: &mut Criterion,
) {
let mut rng = rand::thread_rng();
let fs = TFTTSettings::new(BENCH_SCALE).unwrap();
let max_width: usize = fs.get_max_width();
let mut poly = vec![TFr::zero(); max_width];
for (i, p) in poly.iter_mut().enumerate().take(max_width / 2) {
*p = TFr::from_u64(i.try_into().unwrap());
}
let mut samples = fs
.fft_fr(&poly, false)
.unwrap()
.into_iter()
.map(Some)
.collect::<Vec<_>>();
for _ in 0..(max_width / 2) {
let mut j: usize = rng.gen::<usize>() % max_width;
while samples[j].is_none() {
j = rng.gen::<usize>() % max_width;
}
samples[j] = None;
}
let id = format!("bench_recover scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| {
b.iter(|| {
TPolyRecover::recover_poly_from_samples(black_box(&samples), black_box(&fs)).unwrap();
})
});
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/benches/fft.rs | kzg-bench/src/benches/fft.rs | use criterion::Criterion;
use kzg::{FFTFr, FFTSettings, Fr, FFTG1, G1};
const BENCH_SCALE: usize = 15;
pub fn bench_fft_fr<TFr: Fr, TFFTSettings: FFTSettings<TFr> + FFTFr<TFr>>(c: &mut Criterion) {
let fft_settings = TFFTSettings::new(BENCH_SCALE).unwrap();
let data: Vec<TFr> = vec![TFr::rand(); fft_settings.get_max_width()];
let id = format!("bench_fft_fr scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| b.iter(|| fft_settings.fft_fr(&data, false)));
}
pub fn bench_fft_g1<TFr: Fr, TG1: G1, TFFTSettings: FFTSettings<TFr> + FFTG1<TG1>>(
c: &mut Criterion,
) {
let fft_settings = TFFTSettings::new(BENCH_SCALE).unwrap();
let data: Vec<TG1> = vec![TG1::rand(); fft_settings.get_max_width()];
let id = format!("bench_fft_g1 scale: '{}'", BENCH_SCALE);
c.bench_function(&id, |b| b.iter(|| fft_settings.fft_g1(&data, false)));
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/verify_blob_kzg_proof_batch.rs | kzg-bench/src/test_vectors/verify_blob_kzg_proof_batch.rs | #![allow(dead_code)]
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input {
blobs: Vec<String>,
commitments: Vec<String>,
proofs: Vec<String>,
}
impl Input {
pub fn get_blobs_bytes(&self) -> Vec<Vec<u8>> {
let mut v = Vec::new();
for blob in &self.blobs {
v.push(hex::decode(&blob[2..]).unwrap());
}
v
}
pub fn get_commitments_bytes(&self) -> Vec<Vec<u8>> {
let mut v = Vec::new();
for commitment in &self.commitments {
v.push(hex::decode(&commitment[2..]).unwrap());
}
v
}
pub fn get_proofs_bytes(&self) -> Vec<Vec<u8>> {
let mut v = Vec::new();
for proof in &self.proofs {
v.push(hex::decode(&proof[2..]).unwrap());
}
v
}
}
#[derive(Deserialize)]
pub struct Test {
pub input: Input,
output: Option<bool>,
}
impl Test {
pub fn get_output(&self) -> Option<bool> {
self.output
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/compute_kzg_proof.rs | kzg-bench/src/test_vectors/compute_kzg_proof.rs | #![allow(dead_code)]
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input<'a> {
blob: &'a str,
z: &'a str,
}
impl Input<'_> {
pub fn get_blob_bytes(&self) -> Vec<u8> {
hex::decode(&self.blob[2..]).unwrap()
}
pub fn get_z_bytes(&self) -> Vec<u8> {
hex::decode(&self.z[2..]).unwrap()
}
}
#[derive(Deserialize)]
pub struct Test<'a> {
#[serde(borrow)]
pub input: Input<'a>,
#[serde(borrow)]
output: Option<(&'a str, &'a str)>,
}
impl Test<'_> {
pub fn get_output_bytes(&self) -> Option<(Vec<u8>, Vec<u8>)> {
self.output.map(|(proof, y)| {
(
hex::decode(&proof[2..]).unwrap(),
hex::decode(&y[2..]).unwrap(),
)
})
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/verify_blob_kzg_proof.rs | kzg-bench/src/test_vectors/verify_blob_kzg_proof.rs | #![allow(dead_code)]
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input<'a> {
blob: &'a str,
commitment: &'a str,
proof: &'a str,
}
impl Input<'_> {
pub fn get_blob_bytes(&self) -> Vec<u8> {
hex::decode(&self.blob[2..]).unwrap()
}
pub fn get_commitment_bytes(&self) -> Vec<u8> {
hex::decode(&self.commitment[2..]).unwrap()
}
pub fn get_proof_bytes(&self) -> Vec<u8> {
hex::decode(&self.proof[2..]).unwrap()
}
}
#[derive(Deserialize)]
pub struct Test<'a> {
#[serde(borrow)]
pub input: Input<'a>,
output: Option<bool>,
}
impl Test<'_> {
pub fn get_output(&self) -> Option<bool> {
self.output
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/compute_blob_kzg_proof.rs | kzg-bench/src/test_vectors/compute_blob_kzg_proof.rs | #![allow(dead_code)]
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input<'a> {
blob: &'a str,
commitment: &'a str,
}
impl Input<'_> {
pub fn get_blob_bytes(&self) -> Vec<u8> {
hex::decode(&self.blob[2..]).unwrap()
}
pub fn get_commitment_bytes(&self) -> Vec<u8> {
hex::decode(&self.commitment[2..]).unwrap()
}
}
#[derive(Deserialize)]
pub struct Test<'a> {
#[serde(borrow)]
pub input: Input<'a>,
#[serde(borrow)]
output: Option<&'a str>,
}
impl Test<'_> {
pub fn get_output_bytes(&self) -> Option<Vec<u8>> {
self.output.map(|s| hex::decode(&s[2..]).unwrap())
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/verify_cell_kzg_proof_batch.rs | kzg-bench/src/test_vectors/verify_cell_kzg_proof_batch.rs | #![allow(dead_code)]
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input {
commitments: Vec<String>,
cell_indices: Vec<u64>,
cells: Vec<String>,
proofs: Vec<String>,
}
impl Input {
pub fn get_commitment_bytes(&self) -> Result<Vec<Vec<u8>>, String> {
self.commitments
.iter()
.map(|s| hex::decode(&s[2..]).map_err(|_| "Failed to decode hex".to_string()))
.collect::<Result<Vec<Vec<u8>>, String>>()
}
pub fn get_cell_indices(&self) -> Result<Vec<usize>, String> {
Ok(self
.cell_indices
.iter()
.map(|it| *it as usize)
.collect::<Vec<_>>())
}
pub fn get_cell_bytes(&self) -> Result<Vec<Vec<u8>>, String> {
self.cells
.iter()
.map(|s| hex::decode(&s[2..]).map_err(|_| "Failed to decode hex".to_string()))
.collect::<Result<Vec<Vec<u8>>, String>>()
}
pub fn get_proof_bytes(&self) -> Result<Vec<Vec<u8>>, String> {
self.proofs
.iter()
.map(|s| hex::decode(&s[2..]).map_err(|_| "Failed to decode hex".to_string()))
.collect::<Result<Vec<Vec<u8>>, String>>()
}
}
#[derive(Deserialize)]
pub struct Test {
pub input: Input,
output: Option<bool>,
}
impl Test {
pub fn get_output(&self) -> Option<bool> {
self.output
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/blob_to_kzg_commitment.rs | kzg-bench/src/test_vectors/blob_to_kzg_commitment.rs | #![allow(dead_code)]
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input<'a> {
blob: &'a str,
}
impl Input<'_> {
pub fn get_blob_bytes(&self) -> Vec<u8> {
hex::decode(&self.blob[2..]).unwrap()
}
}
#[derive(Deserialize)]
pub struct Test<'a> {
#[serde(borrow)]
pub input: Input<'a>,
#[serde(borrow)]
output: Option<&'a str>,
}
impl Test<'_> {
pub fn get_output_bytes(&self) -> Option<Vec<u8>> {
self.output.map(|s| hex::decode(&s[2..]).unwrap())
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/compute_verify_cell_kzg_proof_batch_challenge.rs | kzg-bench/src/test_vectors/compute_verify_cell_kzg_proof_batch_challenge.rs | #![allow(dead_code)]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input {
commitments: Vec<String>,
commitment_indices: Vec<u64>,
cell_indices: Vec<u64>,
cosets_evals: Vec<Vec<String>>,
proofs: Vec<String>,
}
impl Input {
pub fn get_commitment_bytes(&self) -> Result<Vec<Vec<u8>>, String> {
self.commitments
.iter()
.map(|s| hex::decode(&s[2..]).map_err(|_| "Failed to decode hex".to_string()))
.collect::<Result<Vec<Vec<u8>>, String>>()
}
pub fn get_commitment_indices(&self) -> Result<Vec<usize>, String> {
Ok(self
.commitment_indices
.iter()
.map(|it| *it as usize)
.collect::<Vec<_>>())
}
pub fn get_cell_indices(&self) -> Result<Vec<usize>, String> {
Ok(self
.cell_indices
.iter()
.map(|it| *it as usize)
.collect::<Vec<_>>())
}
pub fn get_coset_eval_bytes(&self) -> Result<Vec<Vec<Vec<u8>>>, String> {
self.cosets_evals
.iter()
.map(|s| {
s.iter()
.map(|s| hex::decode(&s[2..]).map_err(|_| "Failed to decode hex".to_string()))
.collect::<Result<Vec<_>, _>>()
})
.collect::<Result<Vec<_>, String>>()
}
pub fn get_proof_bytes(&self) -> Result<Vec<Vec<u8>>, String> {
self.proofs
.iter()
.map(|s| hex::decode(&s[2..]).map_err(|_| "Failed to decode hex".to_string()))
.collect::<Result<Vec<Vec<u8>>, String>>()
}
}
#[derive(Deserialize)]
pub struct Test {
pub input: Input,
output: Option<String>,
}
impl Test {
pub fn get_output_bytes(&self) -> Option<Vec<u8>> {
self.output.clone().map(|s| hex::decode(&s[2..]).unwrap())
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/verify_kzg_proof.rs | kzg-bench/src/test_vectors/verify_kzg_proof.rs | #![allow(dead_code)]
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input<'a> {
commitment: &'a str,
z: &'a str,
y: &'a str,
proof: &'a str,
}
impl Input<'_> {
pub fn get_commitment_bytes(&self) -> Vec<u8> {
hex::decode(&self.commitment[2..]).unwrap()
}
pub fn get_z_bytes(&self) -> Vec<u8> {
hex::decode(&self.z[2..]).unwrap()
}
pub fn get_y_bytes(&self) -> Vec<u8> {
hex::decode(&self.y[2..]).unwrap()
}
pub fn get_proof_bytes(&self) -> Vec<u8> {
hex::decode(&self.proof[2..]).unwrap()
}
}
#[derive(Deserialize)]
pub struct Test<'a> {
#[serde(borrow)]
pub input: Input<'a>,
output: Option<bool>,
}
impl Test<'_> {
pub fn get_output(&self) -> Option<bool> {
self.output
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/mod.rs | kzg-bench/src/test_vectors/mod.rs | /* eip-4844 */
pub mod blob_to_kzg_commitment;
pub mod compute_blob_kzg_proof;
pub mod compute_challenge;
pub mod compute_kzg_proof;
pub mod verify_blob_kzg_proof;
pub mod verify_blob_kzg_proof_batch;
pub mod verify_kzg_proof;
/* eip-7594 */
pub mod compute_cells;
pub mod compute_cells_and_kzg_proofs;
pub mod compute_verify_cell_kzg_proof_batch_challenge;
pub mod recover_cells_and_kzg_proofs;
pub mod verify_cell_kzg_proof_batch;
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/recover_cells_and_kzg_proofs.rs | kzg-bench/src/test_vectors/recover_cells_and_kzg_proofs.rs | #![allow(dead_code)]
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input {
cell_indices: Vec<u8>,
cells: Vec<String>,
}
impl Input {
pub fn get_cell_indices(&self) -> Result<Vec<u8>, String> {
Ok(self.cell_indices.clone())
}
pub fn get_cell_bytes(&self) -> Result<Vec<Vec<u8>>, String> {
self.cells
.iter()
.map(|s| hex::decode(&s[2..]).map_err(|_| "Invalid cell hex".to_string()))
.collect::<Result<Vec<Vec<u8>>, String>>()
}
}
#[derive(Deserialize)]
pub struct Test {
pub input: Input,
output: Option<(Vec<String>, Vec<String>)>,
}
impl Test {
#[allow(clippy::type_complexity)]
pub fn get_output(&self) -> Option<(Vec<Vec<u8>>, Vec<Vec<u8>>)> {
self.output.clone().map(|(cells, proofs)| {
(
cells
.iter()
.map(|s| hex::decode(&s[2..]).unwrap())
.collect::<Vec<_>>(),
proofs
.iter()
.map(|s| hex::decode(&s[2..]).unwrap())
.collect::<Vec<_>>(),
)
})
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/compute_cells_and_kzg_proofs.rs | kzg-bench/src/test_vectors/compute_cells_and_kzg_proofs.rs | #![allow(dead_code)]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input<'a> {
blob: &'a str,
}
impl Input<'_> {
pub fn get_blob_bytes(&self) -> Result<Vec<u8>, String> {
hex::decode(&self.blob[2..]).map_err(|_| "Invalid blob".to_string())
}
}
#[derive(Deserialize)]
pub struct Test<'a> {
#[serde(borrow)]
pub input: Input<'a>,
output: Option<(Vec<String>, Vec<String>)>,
}
impl Test<'_> {
#[allow(clippy::type_complexity)]
pub fn get_output(&self) -> Option<(Vec<Vec<u8>>, Vec<Vec<u8>>)> {
self.output.clone().map(|(cells, proofs)| {
(
cells
.iter()
.map(|s| hex::decode(&s[2..]).unwrap())
.collect::<Vec<_>>(),
proofs
.iter()
.map(|s| hex::decode(&s[2..]).unwrap())
.collect::<Vec<Vec<u8>>>(),
)
})
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/compute_cells.rs | kzg-bench/src/test_vectors/compute_cells.rs | #![allow(dead_code)]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input<'a> {
blob: &'a str,
}
impl Input<'_> {
pub fn get_blob_bytes(&self) -> Result<Vec<u8>, String> {
hex::decode(&self.blob[2..]).map_err(|_| "Invalid blob".to_string())
}
}
#[derive(Deserialize)]
pub struct Test<'a> {
#[serde(borrow)]
pub input: Input<'a>,
output: Option<Vec<String>>,
}
impl Test<'_> {
#[allow(clippy::type_complexity)]
pub fn get_output(&self) -> Option<Vec<Vec<u8>>> {
self.output.clone().map(|cells| {
cells
.iter()
.map(|s| hex::decode(&s[2..]).unwrap())
.collect::<Vec<_>>()
})
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/kzg-bench/src/test_vectors/compute_challenge.rs | kzg-bench/src/test_vectors/compute_challenge.rs | #![allow(dead_code)]
extern crate alloc;
use alloc::string::String;
use alloc::vec::Vec;
use serde::Deserialize;
#[derive(Deserialize)]
pub struct Input<'a> {
blob: &'a str,
commitment: &'a str,
}
impl Input<'_> {
pub fn get_blob_bytes(&self) -> Result<Vec<u8>, String> {
hex::decode(&self.blob[2..]).map_err(|_| "Invalid blob".to_string())
}
pub fn get_commitment_bytes(&self) -> Result<Vec<u8>, String> {
hex::decode(&self.commitment[2..]).map_err(|_| "Invalid commitment".to_string())
}
}
#[derive(Deserialize)]
pub struct Test<'a> {
#[serde(borrow)]
pub input: Input<'a>,
output: Option<&'a str>,
}
impl Test<'_> {
pub fn get_output_bytes(&self) -> Option<Vec<u8>> {
self.output.map(|s| hex::decode(&s[2..]).unwrap())
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/src/consts.rs | arkworks5/src/consts.rs | use kzg::eth::c_bindings::{blst_fp, blst_fp2, blst_p1, blst_p2};
use crate::kzg_types::{ArkG1, ArkG2};
/** The G1 identity/infinity */
#[rustfmt::skip]
pub const G1_IDENTITY: ArkG1 = ArkG1::from_blst_p1( blst_p1 {
x: blst_fp { l: [0, 0, 0, 0, 0, 0], },
y: blst_fp { l: [0, 0, 0, 0, 0, 0], },
z: blst_fp { l: [0, 0, 0, 0, 0, 0], },
});
pub const SCALE_FACTOR: u64 = 5;
pub const NUM_ROOTS: usize = 32;
#[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],
];
/** The G1 generator */
pub const G1_GENERATOR: ArkG1 = ArkG1::from_blst_p1(blst_p1 {
x: blst_fp {
l: [
0x5cb38790fd530c16,
0x7817fc679976fff5,
0x154f95c7143ba1c1,
0xf0ae6acdf3d0e747,
0xedce6ecc21dbf440,
0x120177419e0bfb75,
],
},
y: blst_fp {
l: [
0xbaac93d50ce72271,
0x8c22631a7918fd8e,
0xdd595f13570725ce,
0x51ac582950405194,
0x0e1c8c3fad0059c0,
0x0bbc3efc5008a26a,
],
},
z: blst_fp {
l: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
});
pub const G1_NEGATIVE_GENERATOR: ArkG1 = ArkG1::from_blst_p1(blst_p1 {
x: blst_fp {
l: [
0x5cb38790fd530c16,
0x7817fc679976fff5,
0x154f95c7143ba1c1,
0xf0ae6acdf3d0e747,
0xedce6ecc21dbf440,
0x120177419e0bfb75,
],
},
y: blst_fp {
l: [
0xff526c2af318883a,
0x92899ce4383b0270,
0x89d7738d9fa9d055,
0x12caf35ba344c12a,
0x3cff1b76964b5317,
0x0e44d2ede9774430,
],
},
z: blst_fp {
l: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
});
pub const G2_GENERATOR: ArkG2 = ArkG2::from_blst_p2(blst_p2 {
x: blst_fp2 {
fp: [
blst_fp {
l: [
0xf5f28fa202940a10,
0xb3f5fb2687b4961a,
0xa1a893b53e2ae580,
0x9894999d1a3caee9,
0x6f67b7631863366b,
0x058191924350bcd7,
],
},
blst_fp {
l: [
0xa5a9c0759e23f606,
0xaaa0c59dbccd60c3,
0x3bb17e18e2867806,
0x1b1ab6cc8541b367,
0xc2b6ed0ef2158547,
0x11922a097360edf3,
],
},
],
},
y: blst_fp2 {
fp: [
blst_fp {
l: [
0x4c730af860494c4a,
0x597cfa1f5e369c5a,
0xe7e6856caa0a635a,
0xbbefb5e96e0d495f,
0x07d3a975f0ef25a2,
0x0083fd8e7e80dae5,
],
},
blst_fp {
l: [
0xadc0fc92df64b05d,
0x18aa270a2b1461dc,
0x86adac6a3be4eba0,
0x79495c4ec93da33a,
0xe7175850a43ccaed,
0x0b2bc2a163de1bf2,
],
},
],
},
z: blst_fp2 {
fp: [
blst_fp {
l: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
blst_fp {
l: [
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
],
},
],
},
});
pub const G2_NEGATIVE_GENERATOR: ArkG2 = ArkG2::from_blst_p2(blst_p2 {
x: blst_fp2 {
fp: [
blst_fp {
l: [
0xf5f28fa202940a10,
0xb3f5fb2687b4961a,
0xa1a893b53e2ae580,
0x9894999d1a3caee9,
0x6f67b7631863366b,
0x058191924350bcd7,
],
},
blst_fp {
l: [
0xa5a9c0759e23f606,
0xaaa0c59dbccd60c3,
0x3bb17e18e2867806,
0x1b1ab6cc8541b367,
0xc2b6ed0ef2158547,
0x11922a097360edf3,
],
},
],
},
y: blst_fp2 {
fp: [
blst_fp {
l: [
0x6d8bf5079fb65e61,
0xc52f05df531d63a5,
0x7f4a4d344ca692c9,
0xa887959b8577c95f,
0x4347fe40525c8734,
0x197d145bbaff0bb5,
],
},
blst_fp {
l: [
0x0c3e036d209afa4e,
0x0601d8f4863f9e23,
0xe0832636bacc0a84,
0xeb2def362a476f84,
0x64044f659f0ee1e9,
0x0ed54f48d5a1caa7,
],
},
],
},
z: blst_fp2 {
fp: [
blst_fp {
l: [
0x760900000002fffd,
0xebf4000bc40c0002,
0x5f48985753c758ba,
0x77ce585370525745,
0x5c071a97a256ec6d,
0x15f65ec3fa80e493,
],
},
blst_fp {
l: [
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
0x0000000000000000,
],
},
],
},
});
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/src/das.rs | arkworks5/src/das.rs | use crate::kzg_proofs::FFTSettings;
use crate::kzg_types::ArkFr as BlstFr;
use kzg::{DASExtension, Fr};
use std::cmp::Ordering;
impl FFTSettings {
fn das_fft_extension_stride(&self, ab: &mut [BlstFr], stride: usize) {
match ab.len().cmp(&2_usize) {
Ordering::Less => {}
Ordering::Greater => {
let half = ab.len();
let halfhalf = half / 2;
for i in 0..halfhalf {
let tmp1 = ab[i].add(&ab[halfhalf + i]);
let tmp2 = ab[i].sub(&ab[halfhalf + i]);
ab[halfhalf + i] = tmp2.mul(&self.reverse_roots_of_unity[i * 2 * stride]);
ab[i] = tmp1;
}
#[cfg(feature = "parallel")]
{
if ab.len() > 32 {
let (lo, hi) = ab.split_at_mut(halfhalf);
rayon::join(
|| self.das_fft_extension_stride(hi, stride * 2),
|| self.das_fft_extension_stride(lo, stride * 2),
);
} else {
self.das_fft_extension_stride(&mut ab[..halfhalf], stride * 2);
self.das_fft_extension_stride(&mut ab[halfhalf..], stride * 2);
}
}
#[cfg(not(feature = "parallel"))]
{
self.das_fft_extension_stride(&mut ab[..halfhalf], stride * 2);
self.das_fft_extension_stride(&mut ab[halfhalf..], stride * 2);
}
for i in 0..halfhalf {
let x = ab[i];
let y = ab[halfhalf + i];
let y_times_root = y.mul(&self.roots_of_unity[(1 + 2 * i) * stride]);
ab[i] = x.add(&y_times_root);
ab[halfhalf + i] = x.sub(&y_times_root);
}
}
Ordering::Equal => {
let x = ab[0].add(&ab[1]);
let y = ab[0].sub(&ab[1]);
let tmp = y.mul(&self.roots_of_unity[stride]);
ab[0] = x.add(&tmp);
ab[1] = x.sub(&tmp);
}
}
}
}
impl DASExtension<BlstFr> for FFTSettings {
fn das_fft_extension(&self, vals: &[BlstFr]) -> Result<Vec<BlstFr>, String> {
if vals.is_empty() {
return Err(String::from("vals can not be empty"));
}
if !vals.len().is_power_of_two() {
return Err(String::from("vals lenght has to be power of 2"));
}
if vals.len() * 2 > self.max_width {
return Err(String::from(
"vals lenght * 2 has to equal or less than FFTSetings max width",
));
}
let mut vals = vals.to_vec();
let stride = self.max_width / (vals.len() * 2);
self.das_fft_extension_stride(&mut vals, stride);
let invlen = BlstFr::from_u64(vals.len() as u64);
let invlen = invlen.inverse();
for val in &mut vals {
val.fr *= invlen.fr
}
Ok(vals)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/src/lib.rs | arkworks5/src/lib.rs | pub mod consts;
pub mod das;
pub mod eip_4844;
pub mod eip_7594;
pub mod fft;
pub mod fft_g1;
pub mod fk20_proofs;
pub mod kzg_proofs;
pub mod kzg_types;
pub mod poly;
pub mod recover;
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/arkworks5/src/eip_4844.rs | arkworks5/src/eip_4844.rs | extern crate alloc;
use crate::kzg_proofs::KZGSettings as LKZGSettings;
#[cfg(feature = "c_bindings")]
use crate::utils::PRECOMPUTATION_TABLES;
#[cfg(feature = "c_bindings")]
use kzg::{
eth::{
self,
c_bindings::{Blob, Bytes32, Bytes48, CKZGSettings, CKzgRet, KZGCommitment, KZGProof},
},
Fr, G1,
};
#[cfg(feature = "c_bindings")]
use core::ptr;
#[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 = "std")]
pub fn load_trusted_setup_filename_rust(
filepath: &str,
) -> Result<LKZGSettings, alloc::string::String> {
use kzg::eip_4844::load_trusted_setup_rust;
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)
}
#[cfg(feature = "c_bindings")]
pub(crate) fn kzg_settings_to_c(rust_settings: &LKZGSettings) -> CKZGSettings {
CKZGSettings {
roots_of_unity: Box::leak(
rust_settings
.fs
.roots_of_unity
.iter()
.map(|r| r.to_blst_fr())
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
brp_roots_of_unity: Box::leak(
rust_settings
.fs
.brp_roots_of_unity
.iter()
.map(|r| r.to_blst_fr())
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
reverse_roots_of_unity: Box::leak(
rust_settings
.fs
.reverse_roots_of_unity
.iter()
.map(|r| r.to_blst_fr())
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
g1_values_monomial: Box::leak(
rust_settings
.g1_values_monomial
.iter()
.map(|r| r.to_blst_p1())
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
g1_values_lagrange_brp: Box::leak(
rust_settings
.g1_values_lagrange_brp
.iter()
.map(|r| r.to_blst_p1())
.collect::<Vec<_>>()
.into_boxed_slice(),
)
.as_mut_ptr(),
g2_values_monomial: Box::leak(
rust_settings
.g2_values_monomial
.iter()
.map(|r| r.to_blst_p2())
.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(|it| it.to_blst_p1())
.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 = "c_bindings")]
macro_rules! handle_ckzg_badargs {
($x: expr) => {
match $x {
Ok(value) => value,
Err(_) => return CKzgRet::BadArgs,
}
};
}
/// # 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, FIELD_ELEMENTS_PER_BLOB, TRUSTED_SETUP_NUM_G1_POINTS,
};
if TRUSTED_SETUP_NUM_G1_POINTS == 0 {
// FIXME: load_trusted_setup should set this value, but if not, it fails
TRUSTED_SETUP_NUM_G1_POINTS = FIELD_ELEMENTS_PER_BLOB
};
let settings: LKZGSettings = handle_ckzg_badargs!(s.try_into());
let tmp = handle_ckzg_badargs!(blob_to_kzg_commitment_raw((*blob).bytes, &settings));
(*out).bytes = tmp.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 {
use kzg::eip_4844::{load_trusted_setup_rust, BYTES_PER_G1, TRUSTED_SETUP_NUM_G1_POINTS};
*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 {
use kzg::eip_4844::{
load_trusted_setup_rust, BYTES_PER_G1, FIELD_ELEMENTS_PER_BLOB, TRUSTED_SETUP_NUM_G1_POINTS,
};
*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
#[cfg(feature = "c_bindings")]
#[no_mangle]
pub unsafe extern "C" fn free_trusted_setup(s: *mut CKZGSettings) {
use kzg::eip_4844::{FIELD_ELEMENTS_PER_BLOB, TRUSTED_SETUP_NUM_G2_POINTS};
if s.is_null() {
return;
}
PRECOMPUTATION_TABLES.remove_precomputation(&*s);
if !(*s).roots_of_unity.is_null() {
let v = Box::from_raw(core::slice::from_raw_parts_mut(
(*s).roots_of_unity,
eth::FIELD_ELEMENTS_PER_EXT_BLOB + 1,
));
drop(v);
(*s).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,
eth::FIELD_ELEMENTS_PER_EXT_BLOB,
));
drop(v);
(*s).brp_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,
eth::FIELD_ELEMENTS_PER_EXT_BLOB + 1,
));
drop(v);
(*s).reverse_roots_of_unity = ptr::null_mut();
}
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 x_ext_fft_columns = core::slice::from_raw_parts_mut(
(*s).x_ext_fft_columns,
2 * ((eth::FIELD_ELEMENTS_PER_EXT_BLOB / 2) / eth::FIELD_ELEMENTS_PER_CELL),
);
for column in x_ext_fft_columns.iter_mut() {
if !(*column).is_null() {
let v = Box::from_raw(core::slice::from_raw_parts_mut(
*column,
eth::FIELD_ELEMENTS_PER_CELL,
));
drop(v);
*column = ptr::null_mut();
}
}
let v = Box::from_raw(x_ext_fft_columns);
drop(v);
(*s).x_ext_fft_columns = ptr::null_mut();
}
}
/// # Safety
#[cfg(feature = "c_bindings")]
#[no_mangle]
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_raw;
let settings: LKZGSettings = handle_ckzg_badargs!(s.try_into());
let result = handle_ckzg_badargs!(verify_kzg_proof_raw(
(*commitment_bytes).bytes,
(*z_bytes).bytes,
(*y_bytes).bytes,
(*proof_bytes).bytes,
&settings
));
*ok = result;
CKzgRet::Ok
}
/// # Safety
#[cfg(feature = "c_bindings")]
#[no_mangle]
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: LKZGSettings = 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
#[cfg(feature = "c_bindings")]
#[no_mangle]
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 blobs = core::slice::from_raw_parts(blobs, n)
.iter()
.map(|v| v.bytes)
.collect::<Vec<_>>();
let commitments = core::slice::from_raw_parts(commitments_bytes, n)
.iter()
.map(|v| v.bytes)
.collect::<Vec<_>>();
let proofs = core::slice::from_raw_parts(proofs_bytes, n)
.iter()
.map(|v| v.bytes)
.collect::<Vec<_>>();
*ok = false;
let settings: LKZGSettings = handle_ckzg_badargs!(s.try_into());
let result = handle_ckzg_badargs!(verify_blob_kzg_proof_batch_raw(
&blobs,
&commitments,
&proofs,
&settings
));
*ok = result;
CKzgRet::Ok
}
/// # Safety
#[cfg(feature = "c_bindings")]
#[no_mangle]
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: LKZGSettings = 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
#[cfg(feature = "c_bindings")]
#[no_mangle]
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: LKZGSettings = 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/arkworks5/src/kzg_proofs.rs | arkworks5/src/kzg_proofs.rs | #![allow(non_camel_case_types)]
extern crate alloc;
use super::utils::{blst_poly_into_pc_poly, PolyData};
use crate::kzg_types::{ArkFp, ArkFr, ArkG1Affine, ArkG1ProjAddAffine};
use crate::kzg_types::{ArkFr as BlstFr, ArkG1, ArkG2};
use alloc::sync::Arc;
use ark_bls12_381::Bls12_381;
use ark_ec::pairing::Pairing;
use ark_ec::CurveGroup;
use ark_poly::Polynomial;
use ark_std::{vec, One};
use kzg::common_utils::log2_pow2;
use kzg::eip_4844::hash_to_bls_field;
use kzg::msm::precompute::PrecomputationTable;
use kzg::{FFTSettings as _, Fr as FrTrait, FFTG1, G1, G2};
use kzg::{G1Mul, G2Mul};
use std::ops::Neg;
#[derive(Debug, Clone)]
pub struct FFTSettings {
pub max_width: usize,
pub root_of_unity: BlstFr,
pub reverse_roots_of_unity: Vec<BlstFr>,
pub roots_of_unity: Vec<BlstFr>,
pub brp_roots_of_unity: Vec<BlstFr>,
}
pub fn expand_root_of_unity(root: &BlstFr, width: usize) -> Result<Vec<BlstFr>, String> {
let mut generated_powers = vec![BlstFr::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)
}
#[derive(Debug, Clone, Default)]
#[allow(clippy::type_complexity)]
pub struct KZGSettings {
pub fs: FFTSettings,
pub g1_values_monomial: Vec<ArkG1>,
pub g1_values_lagrange_brp: Vec<ArkG1>,
pub g2_values_monomial: Vec<ArkG2>,
pub precomputation:
Option<Arc<PrecomputationTable<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>>>,
pub x_ext_fft_columns: Vec<Vec<ArkG1>>,
pub cell_size: usize,
}
pub fn generate_trusted_setup(
len: usize,
secret: [u8; 32usize],
) -> (Vec<ArkG1>, Vec<ArkG1>, Vec<ArkG2>) {
let s = hash_to_bls_field(&secret);
let mut s_pow = ArkFr::one();
let mut g1_monomial_values = Vec::with_capacity(len);
let mut g2_monomial_values = Vec::with_capacity(len);
for _ in 0..len {
g1_monomial_values.push(ArkG1::generator().mul(&s_pow));
g2_monomial_values.push(ArkG2::generator().mul(&s_pow));
s_pow = s_pow.mul(&s);
}
let s = FFTSettings::new(log2_pow2(len)).unwrap();
let g1_lagrange_values = s.fft_g1(&g1_monomial_values, true).unwrap();
(g1_monomial_values, g1_lagrange_values, g2_monomial_values)
}
pub fn eval_poly(p: &PolyData, x: &BlstFr) -> BlstFr {
let poly = blst_poly_into_pc_poly(&p.coeffs);
BlstFr {
fr: poly.evaluate(&x.fr),
}
}
pub fn pairings_verify(a1: &ArkG1, a2: &ArkG2, b1: &ArkG1, b2: &ArkG2) -> bool {
let ark_a1_neg = a1.0.neg().into_affine();
let ark_b1 = b1.0.into_affine();
let ark_a2 = a2.0.into_affine();
let ark_b2 = b2.0.into_affine();
Bls12_381::multi_pairing([ark_a1_neg, ark_b1], [ark_a2, ark_b2])
.0
.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/arkworks5/src/eip_7594.rs | arkworks5/src/eip_7594.rs | extern crate alloc;
use kzg::EcBackend;
use crate::kzg_proofs::FFTSettings;
use crate::kzg_proofs::KZGSettings;
use crate::kzg_types::ArkFp;
use crate::kzg_types::ArkFr;
use crate::kzg_types::ArkG1;
use crate::kzg_types::ArkG1Affine;
use crate::kzg_types::ArkG1ProjAddAffine;
use crate::kzg_types::ArkG2;
use crate::utils::PolyData;
pub struct ArkBackend;
impl EcBackend for ArkBackend {
type Fr = ArkFr;
type G1Fp = ArkFp;
type G1Affine = ArkG1Affine;
type G1ProjAddAffine = ArkG1ProjAddAffine;
type G1 = ArkG1;
type G2 = ArkG2;
type Poly = PolyData;
type FFTSettings = FFTSettings;
type KZGSettings = KZGSettings;
}
#[cfg(feature = "c_bindings")]
kzg::c_bindings_eip7594!(ArkBackend);
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/src/poly.rs | arkworks5/src/poly.rs | use super::kzg_proofs::FFTSettings;
use super::utils::{blst_poly_into_pc_poly, PolyData};
use crate::kzg_types::ArkFr as BlstFr;
use crate::utils::pc_poly_into_blst_poly;
use crate::zero_poly::pad_poly;
use ark_bls12_381::Fr;
use ark_poly::univariate::DensePolynomial;
use ark_poly::DenseUVPolynomial;
use ark_std::{log2, Zero};
use kzg::common_utils::{log2_pow2, next_pow_of_2};
use kzg::{FFTFr, FFTSettings as FFTSettingsT, Fr as FrTrait, Poly};
use std::cmp::min;
pub fn poly_inverse(b: &PolyData, output_len: usize) -> Result<PolyData, String> {
if b.coeffs.is_empty() {
return Err(String::from("b.coeffs is empty"));
}
if BlstFr::is_zero(&b.coeffs[0]) {
return Err(String::from("b.coeffs[0] is zero"));
}
let mut output = PolyData {
coeffs: vec![BlstFr::zero(); output_len],
};
if b.coeffs.len() == 1 {
output.coeffs[0] = b.coeffs[0].inverse();
for i in 1..output_len {
output.coeffs[i] = BlstFr::zero();
}
return Ok(output);
}
let maxd = output_len - 1;
let scale = next_pow_of_2(log2_pow2(2 * output_len - 1));
let fs = FFTSettings::new(scale).unwrap();
let mut tmp0: PolyData;
let mut tmp1: PolyData;
output.coeffs[0] = b.coeffs[0].inverse();
let mut d: usize = 0;
let mut mask: usize = 1 << log2(maxd);
while mask != 0 {
d = 2 * d + usize::from((maxd & mask) != 0);
mask >>= 1;
let len_temp: usize = min(d + 1, b.coeffs.len() + output.coeffs.len() - 1);
tmp0 = poly_mul(b, &output, Some(&fs), len_temp).unwrap();
for i in 0..len_temp {
tmp0.coeffs[i] = tmp0.coeffs[i].negate();
}
let fr_two = BlstFr { fr: Fr::from(2) };
tmp0.coeffs[0] = tmp0.coeffs[0].add(&fr_two);
let len_temp2: usize = d + 1;
tmp1 = poly_mul(&output, &tmp0, Some(&fs), len_temp2).unwrap();
if tmp1.coeffs.len() > output_len {
tmp1.coeffs = tmp1.coeffs[..output_len].to_vec();
}
for i in 0..tmp1.coeffs.len() {
output.coeffs[i] = tmp1.coeffs[i];
}
}
if d + 1 != output_len {
return Err(String::from("d + 1 is not equals to output_len"));
}
Ok(output)
}
pub fn poly_mul_direct(p1: &PolyData, p2: &PolyData, len: usize) -> Result<PolyData, String> {
let p1 = blst_poly_into_pc_poly(&p1.coeffs);
let p2 = blst_poly_into_pc_poly(&p2.coeffs);
if p1.is_zero() || p2.is_zero() {
Ok(pc_poly_into_blst_poly(DensePolynomial::zero()))
} else {
let mut result = vec![Fr::zero(); len];
for (i, self_coeff) in p1.coeffs.iter().enumerate() {
for (j, other_coeff) in p2.coeffs.iter().enumerate() {
if i + j >= len {
break;
}
result[i + j] += &(*self_coeff * other_coeff);
}
}
let p = pc_poly_into_blst_poly(DensePolynomial::from_coefficients_vec(result));
Ok(PolyData {
coeffs: pad_poly(&p, len).unwrap(),
})
}
}
pub fn poly_long_div(p1: &PolyData, p2: &PolyData) -> Result<PolyData, String> {
Ok(pc_poly_into_blst_poly(
&blst_poly_into_pc_poly(&p1.coeffs) / &blst_poly_into_pc_poly(&p2.coeffs),
))
}
pub fn poly_mul(
a: &PolyData,
b: &PolyData,
fs: Option<&FFTSettings>,
len: usize,
) -> Result<PolyData, String> {
if a.coeffs.len() < 64 || b.coeffs.len() < 64 || len < 128 {
poly_mul_direct(a, b, len)
} else {
poly_mul_fft(a, b, fs, len)
}
}
pub fn poly_mul_fft(
a: &PolyData,
b: &PolyData,
fs: Option<&FFTSettings>,
len: usize,
) -> Result<PolyData, String> {
// Truncate a and b so as not to do excess work for the number of coefficients required.
let a_len = min(a.len(), len);
let b_len = min(b.len(), len);
let length = next_pow_of_2(a_len + b_len - 1);
// If the FFT settings are NULL then make a local set, otherwise use the ones passed in.
let fs_p = if let Some(x) = fs {
x.clone()
} else {
let scale = log2_pow2(length);
FFTSettings::new(scale).unwrap()
};
if length > fs_p.max_width {
return Err(String::from(
"length should be equals or less than FFTSettings max width",
));
}
let a = PolyData {
coeffs: a.coeffs[..a_len].to_vec(),
};
let b = PolyData {
coeffs: b.coeffs[..b_len].to_vec(),
};
let a_pad = PolyData {
coeffs: pad_poly(&a, length).unwrap(),
};
let b_pad = PolyData {
coeffs: pad_poly(&b, length).unwrap(),
};
let a_fft;
let b_fft;
#[cfg(feature = "parallel")]
{
if length > 1024 {
let mut a_fft_temp = vec![];
let mut b_fft_temp = vec![];
rayon::join(
|| a_fft_temp = fs_p.fft_fr(&a_pad.coeffs, false).unwrap(),
|| b_fft_temp = fs_p.fft_fr(&b_pad.coeffs, false).unwrap(),
);
a_fft = a_fft_temp;
b_fft = b_fft_temp;
} else {
a_fft = fs_p.fft_fr(&a_pad.coeffs, false).unwrap();
b_fft = fs_p.fft_fr(&b_pad.coeffs, false).unwrap();
}
}
#[cfg(not(feature = "parallel"))]
{
a_fft = fs_p.fft_fr(&a_pad.coeffs, false).unwrap();
b_fft = fs_p.fft_fr(&b_pad.coeffs, false).unwrap();
}
let mut ab_fft = a_pad;
let mut ab = b_pad;
for i in 0..length {
ab_fft.coeffs[i] = a_fft[i].mul(&b_fft[i]);
}
ab.coeffs = fs_p.fft_fr(&ab_fft.coeffs, true).unwrap();
let data_len = min(len, length);
let mut out = PolyData::new(len);
for i in 0..data_len {
out.coeffs[i] = ab.coeffs[i];
}
for i in data_len..len {
out.coeffs[i] = BlstFr::zero();
}
Ok(out)
}
pub fn poly_fast_div(dividend: &PolyData, divisor: &PolyData) -> Result<PolyData, String> {
if divisor.coeffs.is_empty() {
return Err(String::from("divisor coeffs are empty"));
}
if divisor.coeffs[divisor.coeffs.len() - 1].is_zero() {
return Err(String::from("divisor coeffs last member is zero"));
}
let m = dividend.coeffs.len() - 1;
let n = divisor.coeffs.len() - 1;
if n > m {
return Ok(PolyData::new(0));
}
if divisor.coeffs[divisor.coeffs.len() - 1].is_zero() {
return Err(String::from("divisor coeffs last member is zero"));
}
let mut out = PolyData::new(0);
if divisor.len() == 1 {
for i in 0..dividend.len() {
out.coeffs
.push(dividend.coeffs[i].div(&divisor.coeffs[0]).unwrap());
}
return Ok(out);
}
let a_flip = poly_flip(dividend).unwrap();
let b_flip = poly_flip(divisor).unwrap();
let inv_b_flip = poly_inverse(&b_flip, m - n + 1).unwrap();
let q_flip = poly_mul(&a_flip, &inv_b_flip, None, m - n + 1).unwrap();
out = poly_flip(&q_flip).unwrap();
Ok(PolyData {
coeffs: out.coeffs[..m - n + 1].to_vec(),
})
}
pub fn poly_flip(input: &PolyData) -> Result<PolyData, String> {
let mut output = PolyData::new(0);
for i in 0..input.len() {
output.coeffs.push(input.coeffs[input.coeffs.len() - i - 1]);
}
Ok(output)
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/src/kzg_types.rs | arkworks5/src/kzg_types.rs | use crate::consts::{
G1_GENERATOR, G1_IDENTITY, G1_NEGATIVE_GENERATOR, G2_GENERATOR, G2_NEGATIVE_GENERATOR,
SCALE2_ROOT_OF_UNITY,
};
use crate::fft_g1::g1_linear_combination;
use crate::kzg_proofs::{
eval_poly, expand_root_of_unity, pairings_verify, FFTSettings as LFFTSettings,
KZGSettings as LKZGSettings,
};
use crate::poly::{poly_fast_div, poly_inverse, poly_long_div, poly_mul_direct, poly_mul_fft};
use crate::recover::{scale_poly, unscale_poly};
use crate::utils::{
blst_fp_into_pc_fq, blst_fr_into_pc_fr, blst_p1_into_pc_g1projective,
blst_p2_into_pc_g2projective, fft_settings_to_rust, pc_fr_into_blst_fr,
pc_g1projective_into_blst_p1, pc_g2projective_into_blst_p2, PolyData, PRECOMPUTATION_TABLES,
};
use arbitrary::Arbitrary;
use ark_bls12_381::{g1, g2, Fr, G1Affine, G2Affine};
use ark_ec::{models::short_weierstrass::Projective, AdditiveGroup, AffineRepr};
use ark_ec::{CurveConfig, CurveGroup};
use ark_ff::{biginteger::BigInteger256, BigInteger, Field};
use ark_serialize::{CanonicalDeserialize, CanonicalSerialize};
use ark_std::{One, Zero};
#[cfg(feature = "rand")]
use ark_std::UniformRand;
use kzg::eth::c_bindings::{blst_fp, blst_fr, blst_p1, blst_p2, CKZGSettings};
use crate::fft_g1::fft_g1_fast;
use kzg::common_utils::reverse_bit_order;
use kzg::msm::precompute::{precompute, PrecomputationTable};
use kzg::{
eth, FFTFr, FFTSettings, FFTSettingsPoly, Fr as KzgFr, G1Affine as G1AffineTrait, G1Fp,
G1GetFp, G1LinComb, G1Mul, G1ProjAddAffine, G2Mul, KZGSettings, PairingVerify, Poly, Scalar256,
G1, G2,
};
use std::ops::{AddAssign, Mul, Neg, Sub};
use kzg::eip_4844::{BYTES_PER_FIELD_ELEMENT, BYTES_PER_G1, BYTES_PER_G2};
extern crate alloc;
use alloc::sync::Arc;
fn bytes_be_to_uint64(inp: &[u8]) -> u64 {
u64::from_be_bytes(inp.try_into().expect("Input wasn't 8 elements..."))
}
const BLS12_381_MOD_256: [u64; 4] = [
0xffffffff00000001,
0x53bda402fffe5bfe,
0x3339d80809a1d805,
0x73eda753299d7d48,
];
#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
pub struct ArkFr {
pub fr: Fr,
}
impl<'a> Arbitrary<'a> for ArkFr {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
let val: [u8; 32] = u.arbitrary()?;
Ok(Self::from_bytes_unchecked(&val).unwrap())
}
}
impl ArkFr {
pub fn from_blst_fr(fr: blst_fr) -> Self {
Self {
fr: blst_fr_into_pc_fr(fr),
}
}
pub fn to_blst_fr(&self) -> blst_fr {
pc_fr_into_blst_fr(self.fr)
}
}
fn bigint_check_mod_256(a: &[u64; 4]) -> bool {
let (_, overflow) = a[0].overflowing_sub(BLS12_381_MOD_256[0]);
let (_, overflow) = a[1].overflowing_sub(BLS12_381_MOD_256[1] + overflow as u64);
let (_, overflow) = a[2].overflowing_sub(BLS12_381_MOD_256[2] + overflow as u64);
let (_, overflow) = a[3].overflowing_sub(BLS12_381_MOD_256[3] + overflow as u64);
overflow
}
impl KzgFr for ArkFr {
fn null() -> Self {
Self {
fr: Fr::new_unchecked(BigInteger256::new([u64::MAX; 4])),
}
}
fn zero() -> Self {
// Self::from_u64(0)
Self { fr: Fr::zero() }
}
fn one() -> Self {
let one = Fr::one();
// assert_eq!(one.0.0, [0, 1, 1, 1], "must be eq");
Self { fr: one }
// Self::from_u64(1)
}
#[cfg(feature = "rand")]
fn rand() -> Self {
let mut rng = rand::thread_rng();
Self {
fr: Fr::rand(&mut rng),
}
}
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 storage: [u64; 4] = [
bytes_be_to_uint64(&bytes[24..32]),
bytes_be_to_uint64(&bytes[16..24]),
bytes_be_to_uint64(&bytes[8..16]),
bytes_be_to_uint64(&bytes[0..8]),
];
let big_int = BigInteger256::new(storage);
if !big_int.is_zero() && !bigint_check_mod_256(&big_int.0) {
return Err("Invalid scalar".to_string());
}
Ok(Self {
fr: Fr::new(big_int),
})
})
}
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 storage: [u64; 4] = [
bytes_be_to_uint64(&bytes[24..32]),
bytes_be_to_uint64(&bytes[16..24]),
bytes_be_to_uint64(&bytes[8..16]),
bytes_be_to_uint64(&bytes[0..8]),
];
let big_int = BigInteger256::new(storage);
Self {
fr: Fr::new(big_int),
}
})
}
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 {
Self {
fr: Fr::new(BigInteger256::new(*u)),
}
}
fn from_u64(val: u64) -> Self {
Self::from_u64_arr(&[val, 0, 0, 0])
}
fn to_bytes(&self) -> [u8; 32] {
let big_int_256: BigInteger256 = Fr::into(self.fr);
<[u8; 32]>::try_from(big_int_256.to_bytes_be()).unwrap()
}
fn to_u64_arr(&self) -> [u64; 4] {
let b: BigInteger256 = Fr::into(self.fr);
b.0
}
fn is_one(&self) -> bool {
self.fr.is_one()
}
fn is_zero(&self) -> bool {
self.fr.is_zero()
}
fn is_null(&self) -> bool {
self.equals(&ArkFr::null())
}
fn sqr(&self) -> Self {
Self {
fr: self.fr.square(),
}
}
fn mul(&self, b: &Self) -> Self {
Self { fr: self.fr * b.fr }
}
fn add(&self, b: &Self) -> Self {
Self { fr: self.fr + b.fr }
}
fn sub(&self, b: &Self) -> Self {
Self { fr: self.fr - b.fr }
}
fn eucl_inverse(&self) -> Self {
// Inverse and eucl inverse work the same way
Self {
fr: self.fr.inverse().unwrap(),
}
}
fn negate(&self) -> Self {
Self { fr: self.fr.neg() }
}
fn inverse(&self) -> Self {
Self {
fr: self.fr.inverse().unwrap(),
}
}
fn pow(&self, n: usize) -> Self {
Self {
fr: self.fr.pow([n as u64]),
}
}
fn div(&self, b: &Self) -> Result<Self, String> {
let div = self.fr / b.fr;
if div.0 .0.is_empty() {
Ok(Self { fr: Fr::zero() })
} else {
Ok(Self { fr: div })
}
}
fn equals(&self, b: &Self) -> bool {
self.fr == b.fr
}
fn to_scalar(&self) -> Scalar256 {
Scalar256::from_u64(BigInteger256::from(self.fr).0)
}
}
#[repr(C)]
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy, Hash)]
pub struct ArkG1(pub Projective<g1::Config>);
impl ArkG1 {
pub const fn from_blst_p1(p1: blst_p1) -> Self {
Self(blst_p1_into_pc_g1projective(&p1))
}
pub const fn to_blst_p1(&self) -> blst_p1 {
pc_g1projective_into_blst_p1(self.0)
}
}
impl From<blst_p1> for ArkG1 {
fn from(p1: blst_p1) -> Self {
Self(blst_p1_into_pc_g1projective(&p1))
}
}
impl G1 for ArkG1 {
fn identity() -> Self {
G1_IDENTITY
}
fn generator() -> Self {
G1_GENERATOR
}
fn negative_generator() -> Self {
G1_NEGATIVE_GENERATOR
}
#[cfg(feature = "rand")]
fn rand() -> Self {
let mut rng = rand::thread_rng();
Self(Projective::rand(&mut rng))
}
#[allow(clippy::bind_instead_of_map)]
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 affine = G1Affine::deserialize_compressed(bytes.as_slice());
match affine {
Err(x) => Err("Failed to deserialize G1: ".to_owned() + &(x.to_string())),
Ok(x) => Ok(Self(x.into_group())),
}
})
}
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 buff = [0u8; BYTES_PER_G1];
self.0.serialize_compressed(&mut &mut buff[..]).unwrap();
buff
}
fn add_or_dbl(&self, b: &Self) -> Self {
Self(self.0 + b.0)
}
fn is_inf(&self) -> bool {
let temp = &self.0;
temp.z.is_zero()
}
fn is_valid(&self) -> bool {
true
}
fn dbl(&self) -> Self {
Self(self.0.double())
}
fn add(&self, b: &Self) -> Self {
Self(self.0 + b.0)
}
fn sub(&self, b: &Self) -> Self {
Self(self.0.sub(&b.0))
}
fn equals(&self, b: &Self) -> bool {
self.0.eq(&b.0)
}
fn zero() -> ArkG1 {
ArkG1::from_blst_p1(blst_p1 {
x: blst_fp {
l: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
},
y: blst_fp {
l: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
},
z: blst_fp {
l: [0, 0, 0, 0, 0, 0],
},
})
}
fn add_or_dbl_assign(&mut self, b: &Self) {
self.0 += b.0;
}
fn add_assign(&mut self, b: &Self) {
self.0.add_assign(b.0);
}
fn dbl_assign(&mut self) {
self.0.double_in_place();
}
}
impl G1Mul<ArkFr> for ArkG1 {
fn mul(&self, b: &ArkFr) -> Self {
Self(self.0.mul(b.fr))
}
}
impl G1LinComb<ArkFr, ArkFp, ArkG1Affine, ArkG1ProjAddAffine> for ArkG1 {
fn g1_lincomb(
points: &[Self],
scalars: &[ArkFr],
len: usize,
precomputation: Option<
&PrecomputationTable<ArkFr, Self, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>,
>,
) -> Self {
let mut out = Self::default();
g1_linear_combination(&mut out, points, scalars, len, precomputation);
out
}
}
impl PairingVerify<ArkG1, ArkG2> for ArkG1 {
fn verify(a1: &ArkG1, a2: &ArkG2, b1: &ArkG1, b2: &ArkG2) -> bool {
pairings_verify(a1, a2, b1, b2)
}
}
#[repr(C)]
#[derive(Debug, Default, PartialEq, Eq, Clone)]
pub struct ArkG2(pub Projective<g2::Config>);
impl ArkG2 {
pub const fn from_blst_p2(p2: blst_p2) -> Self {
Self(blst_p2_into_pc_g2projective(&p2))
}
pub const fn to_blst_p2(&self) -> blst_p2 {
pc_g2projective_into_blst_p2(self.0)
}
}
impl G2 for ArkG2 {
fn generator() -> Self {
G2_GENERATOR
}
fn negative_generator() -> Self {
G2_NEGATIVE_GENERATOR
}
#[allow(clippy::bind_instead_of_map)]
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 affine = G2Affine::deserialize_compressed(bytes.as_slice());
match affine {
Err(x) => Err("Failed to deserialize G2: ".to_owned() + &(x.to_string())),
Ok(x) => Ok(Self(x.into_group())),
}
})
}
fn to_bytes(&self) -> [u8; 96] {
let mut buff = [0u8; BYTES_PER_G2];
self.0.serialize_compressed(&mut &mut buff[..]).unwrap();
buff
}
fn add_or_dbl(&mut self, b: &Self) -> Self {
Self(self.0 + b.0)
}
fn dbl(&self) -> Self {
Self(self.0.double())
}
fn sub(&self, b: &Self) -> Self {
Self(self.0 - b.0)
}
fn equals(&self, b: &Self) -> bool {
self.0.eq(&b.0)
}
}
impl G2Mul<ArkFr> for ArkG2 {
fn mul(&self, b: &ArkFr) -> Self {
Self(self.0.mul(&b.fr))
}
}
impl Poly<ArkFr> for PolyData {
fn new(size: usize) -> PolyData {
Self {
coeffs: vec![ArkFr::default(); size],
}
}
fn get_coeff_at(&self, i: usize) -> ArkFr {
self.coeffs[i]
}
fn set_coeff_at(&mut self, i: usize, x: &ArkFr) {
self.coeffs[i] = *x;
}
fn get_coeffs(&self) -> &[ArkFr] {
&self.coeffs
}
fn len(&self) -> usize {
self.coeffs.len()
}
fn eval(&self, x: &ArkFr) -> ArkFr {
eval_poly(self, x)
}
fn scale(&mut self) {
scale_poly(self);
}
fn unscale(&mut self) {
unscale_poly(self);
}
fn inverse(&mut self, new_len: usize) -> Result<Self, String> {
poly_inverse(self, new_len)
}
fn div(&mut self, x: &Self) -> Result<Self, String> {
if x.len() >= self.len() || x.len() < 128 {
poly_long_div(self, x)
} else {
poly_fast_div(self, x)
}
}
fn long_div(&mut self, x: &Self) -> Result<Self, String> {
poly_long_div(self, x)
}
fn fast_div(&mut self, x: &Self) -> Result<Self, String> {
poly_fast_div(self, x)
}
fn mul_direct(&mut self, x: &Self, len: usize) -> Result<Self, String> {
poly_mul_direct(self, x, len)
}
}
impl FFTSettingsPoly<ArkFr, PolyData, LFFTSettings> for LFFTSettings {
fn poly_mul_fft(
a: &PolyData,
x: &PolyData,
len: usize,
fs: Option<&LFFTSettings>,
) -> Result<PolyData, String> {
poly_mul_fft(a, x, fs, len)
}
}
impl Default for LFFTSettings {
fn default() -> Self {
Self {
max_width: 0,
root_of_unity: ArkFr::zero(),
reverse_roots_of_unity: Vec::new(),
roots_of_unity: Vec::new(),
brp_roots_of_unity: Vec::new(),
}
}
}
impl FFTSettings<ArkFr> for LFFTSettings {
fn new(scale: usize) -> Result<LFFTSettings, String> {
if scale >= SCALE2_ROOT_OF_UNITY.len() {
return Err(String::from(
"Scale is expected to be within root of unity matrix row size",
));
}
let max_width: usize = 1 << scale;
let root_of_unity = ArkFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[scale]);
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(LFFTSettings {
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) -> ArkFr {
self.reverse_roots_of_unity[i]
}
fn get_reversed_roots_of_unity(&self) -> &[ArkFr] {
&self.reverse_roots_of_unity
}
fn get_roots_of_unity_at(&self, i: usize) -> ArkFr {
self.roots_of_unity[i]
}
fn get_roots_of_unity(&self) -> &[ArkFr] {
&self.roots_of_unity
}
fn get_brp_roots_of_unity(&self) -> &[ArkFr] {
&self.brp_roots_of_unity
}
fn get_brp_roots_of_unity_at(&self, i: usize) -> ArkFr {
self.brp_roots_of_unity[i]
}
}
fn toeplitz_part_1(
field_elements_per_ext_blob: usize,
output: &mut [ArkG1],
x: &[ArkG1],
s: &LFFTSettings,
) -> Result<(), String> {
let n = x.len();
let n2 = n * 2;
let mut x_ext = vec![ArkG1::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<ArkFr, ArkG1, ArkG2, LFFTSettings, PolyData, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>
for LKZGSettings
{
fn new(
g1_monomial: &[ArkG1],
g1_lagrange_brp: &[ArkG1],
g2_monomial: &[ArkG2],
fft_settings: &LFFTSettings,
cell_size: usize,
) -> Result<LKZGSettings, 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![ArkG1::default(); k2];
let mut x = vec![ArkG1::default(); k];
let mut x_ext_fft_columns = vec![vec![ArkG1::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] = ArkG1::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, p: &PolyData) -> Result<ArkG1, String> {
if p.coeffs.len() > self.g1_values_monomial.len() {
return Err(String::from("Polynomial is longer than secret g1"));
}
let mut out = ArkG1::default();
g1_linear_combination(
&mut out,
&self.g1_values_monomial,
&p.coeffs,
p.coeffs.len(),
None,
);
Ok(out)
}
fn compute_proof_single(&self, p: &PolyData, x: &ArkFr) -> Result<ArkG1, 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 = PolyData { coeffs: out_coeffs };
let ret = self.commit_to_poly(&q)?;
Ok(ret)
// Ok(compute_single(p, x, self))
}
fn check_proof_single(
&self,
com: &ArkG1,
proof: &ArkG1,
x: &ArkFr,
y: &ArkFr,
) -> Result<bool, String> {
let x_g2: ArkG2 = G2_GENERATOR.mul(x);
let s_minus_x: ArkG2 = self.g2_values_monomial[1].sub(&x_g2);
let y_g1 = G1_GENERATOR.mul(y);
let commitment_minus_y: ArkG1 = com.sub(&y_g1);
Ok(pairings_verify(
&commitment_minus_y,
&G2_GENERATOR,
proof,
&s_minus_x,
))
}
fn compute_proof_multi(&self, p: &PolyData, x: &ArkFr, n: usize) -> Result<ArkG1, 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 = PolyData {
coeffs: Vec::with_capacity(n + 1),
};
// -(x0^n)
let x_pow_n = x.pow(n);
divisor.coeffs.push(x_pow_n.negate());
// Zeros
for _ in 1..n {
divisor.coeffs.push(ArkFr { fr: Fr::zero() });
}
// x^n
divisor.coeffs.push(ArkFr { fr: 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: &ArkG1,
proof: &ArkG1,
x: &ArkFr,
ys: &[ArkFr],
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 = PolyData {
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) -> ArkFr {
self.fs.get_roots_of_unity_at(i)
}
fn get_fft_settings(&self) -> &LFFTSettings {
&self.fs
}
fn get_g1_lagrange_brp(&self) -> &[ArkG1] {
&self.g1_values_lagrange_brp
}
fn get_g1_monomial(&self) -> &[ArkG1] {
&self.g1_values_monomial
}
fn get_g2_monomial(&self) -> &[ArkG2] {
&self.g2_values_monomial
}
fn get_precomputation(
&self,
) -> Option<&PrecomputationTable<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>> {
self.precomputation.as_ref().map(|v| v.as_ref())
}
fn get_x_ext_fft_columns(&self) -> &[Vec<ArkG1>] {
&self.x_ext_fft_columns
}
fn get_cell_size(&self) -> usize {
self.cell_size
}
}
impl<'a> TryFrom<&'a CKZGSettings> for LKZGSettings {
type Error = String;
fn try_from(c_settings: &'a CKZGSettings) -> Result<Self, Self::Error> {
Ok(LKZGSettings {
fs: fft_settings_to_rust(c_settings)?,
g1_values_monomial: unsafe {
core::slice::from_raw_parts(
c_settings.g1_values_monomial,
eth::FIELD_ELEMENTS_PER_BLOB,
)
}
.iter()
.map(|r| ArkG1::from_blst_p1(*r))
.collect::<Vec<_>>(),
g1_values_lagrange_brp: unsafe {
core::slice::from_raw_parts(
c_settings.g1_values_lagrange_brp,
eth::FIELD_ELEMENTS_PER_BLOB,
)
}
.iter()
.map(|r| ArkG1::from_blst_p1(*r))
.collect::<Vec<_>>(),
g2_values_monomial: unsafe {
core::slice::from_raw_parts(
c_settings.g2_values_monomial,
eth::TRUSTED_SETUP_NUM_G2_POINTS,
)
}
.iter()
.map(|r| ArkG2::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| ArkG1::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,
})
}
}
type ArkFpInt = <ark_bls12_381::g1::Config as CurveConfig>::BaseField;
#[repr(C)]
#[derive(Debug, Default, Clone, Copy, Eq, PartialEq)]
pub struct ArkFp(pub ArkFpInt);
impl G1Fp for ArkFp {
fn is_zero(&self) -> bool {
self.0.is_zero()
}
fn set_zero(&mut self) {
self.0.set_zero();
}
fn is_one(&self) -> bool {
self.0.is_one()
}
fn set_one(&mut self) {
self.0.set_one();
}
fn inverse(&self) -> Option<Self> {
Some(Self(self.0.inverse().unwrap()))
}
fn square(&self) -> Self {
Self(self.0.square())
}
fn double(&self) -> Self {
Self(self.0.double())
}
fn from_underlying_arr(arr: &[u64; 6]) -> Self {
let mut default = ArkFpInt::default();
default.0 .0 = *arr;
Self(default)
}
fn neg_assign(&mut self) {
self.0 = -self.0;
}
fn mul_assign_fp(&mut self, b: &Self) {
self.0 *= b.0;
}
fn sub_assign_fp(&mut self, b: &Self) {
self.0 -= b.0;
}
fn add_assign_fp(&mut self, b: &Self) {
self.0 += b.0;
}
fn mul3(&self) -> Self {
Self(self.0 * ArkFpInt::from(3))
}
fn zero() -> Self {
Self(ArkFpInt::ZERO)
}
fn one() -> Self {
Self(ArkFpInt::ONE)
}
fn bls12_381_rx_p() -> Self {
Self(blst_fp_into_pc_fq(&blst_fp {
l: [
8505329371266088957,
17002214543764226050,
6865905132761471162,
8632934651105793861,
6631298214892334189,
1582556514881692819,
],
}))
}
}
impl G1GetFp<ArkFp> for ArkG1 {
fn x(&self) -> &ArkFp {
unsafe {
// Transmute safe due to repr(C) on FsFp
core::mem::transmute(&self.0.x)
}
}
fn y(&self) -> &ArkFp {
unsafe {
// Transmute safe due to repr(C) on FsFp
core::mem::transmute(&self.0.y)
}
}
fn z(&self) -> &ArkFp {
unsafe {
// Transmute safe due to repr(C) on FsFp
core::mem::transmute(&self.0.z)
}
}
fn x_mut(&mut self) -> &mut ArkFp {
unsafe {
// Transmute safe due to repr(C) on FsFp
core::mem::transmute(&mut self.0.x)
}
}
fn y_mut(&mut self) -> &mut ArkFp {
unsafe {
// Transmute safe due to repr(C) on FsFp
core::mem::transmute(&mut self.0.y)
}
}
fn z_mut(&mut self) -> &mut ArkFp {
unsafe {
// Transmute safe due to repr(C) on FsFp
core::mem::transmute(&mut self.0.z)
}
}
fn from_jacobian(x: ArkFp, y: ArkFp, z: ArkFp) -> Self {
Self(Projective {
x: x.0,
y: y.0,
z: z.0,
})
}
}
#[repr(C)]
#[derive(Debug, Default, PartialEq, Eq, Clone, Copy)]
pub struct ArkG1Affine {
pub aff: G1Affine,
}
impl<'a> Arbitrary<'a> for ArkG1Affine {
fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
Ok(ArkG1Affine::into_affine(
&ArkG1::generator().mul(&u.arbitrary()?),
))
}
}
impl G1AffineTrait<ArkG1, ArkFp> for ArkG1Affine {
fn into_affine(g1: &ArkG1) -> Self {
Self {
aff: g1.0.into_affine(),
}
}
fn from_xy(x: ArkFp, y: ArkFp) -> Self {
Self {
aff: G1Affine::new(x.0, y.0),
}
}
fn into_affines(g1: &[ArkG1]) -> Vec<Self> {
let ark_points: &[Projective<g1::Config>] = unsafe { core::mem::transmute(g1) };
let ark_points = CurveGroup::normalize_batch(ark_points);
unsafe { core::mem::transmute(ark_points) }
}
fn into_affines_loc(out: &mut [Self], g1: &[ArkG1]) {
out.copy_from_slice(&Self::into_affines(g1));
}
fn to_proj(&self) -> ArkG1 {
ArkG1(self.aff.into_group())
}
fn x(&self) -> &ArkFp {
unsafe { core::mem::transmute(&self.aff.x) }
}
fn y(&self) -> &ArkFp {
unsafe { core::mem::transmute(&self.aff.y) }
}
fn is_infinity(&self) -> bool {
self.aff.infinity
}
fn is_zero(&self) -> bool {
self.aff.is_zero()
}
fn zero() -> Self {
Self {
aff: G1Affine {
x: ArkFp::zero().0,
y: ArkFp::zero().0,
infinity: true,
},
}
}
fn x_mut(&mut self) -> &mut ArkFp {
unsafe { core::mem::transmute(&mut self.aff.x) }
}
fn y_mut(&mut self) -> &mut ArkFp {
unsafe { core::mem::transmute(&mut self.aff.y) }
}
fn neg(&self) -> Self {
Self { aff: -self.aff }
}
fn to_bytes_uncompressed(&self) -> [u8; 96] {
let mut buffer = [0u8; 96];
self.aff.serialize_uncompressed(&mut buffer[..]).expect(
"impossible to happen - byte buffer won't throw IO error and is of exact needed size.",
);
buffer
}
fn from_bytes_uncompressed(bytes: [u8; 96]) -> Result<Self, String> {
G1Affine::deserialize_uncompressed(&bytes[..])
.map(|aff| ArkG1Affine { aff })
.map_err(|err| err.to_string())
}
}
#[derive(Debug)]
pub struct ArkG1ProjAddAffine;
impl G1ProjAddAffine<ArkG1, ArkFp, ArkG1Affine> for ArkG1ProjAddAffine {
fn add_assign_affine(proj: &mut ArkG1, aff: &ArkG1Affine) {
proj.0 += aff.aff;
}
fn add_or_double_assign_affine(proj: &mut ArkG1, aff: &ArkG1Affine) {
proj.0 += aff.aff;
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/src/zero_poly.rs | arkworks5/src/zero_poly.rs | use super::kzg_proofs::FFTSettings;
use super::utils::{blst_poly_into_pc_poly, pc_poly_into_blst_poly, PolyData};
use crate::kzg_types::ArkFr as BlstFr;
use kzg::common_utils::next_pow_of_2;
use kzg::{FFTFr, Fr as FrTrait, ZeroPoly};
use std::cmp::{min, Ordering};
use std::ops::Neg;
pub(crate) fn pad_poly(poly: &PolyData, new_length: usize) -> Result<Vec<BlstFr>, String> {
if new_length <= poly.coeffs.len() {
return Ok(poly.coeffs.clone());
}
let mut out = poly.coeffs.to_vec();
for _i in poly.coeffs.len()..new_length {
out.push(BlstFr::zero())
}
Ok(out)
}
impl ZeroPoly<BlstFr, PolyData> for FFTSettings {
fn do_zero_poly_mul_partial(
&self,
indices: &[usize],
stride: usize,
) -> Result<PolyData, String> {
if indices.is_empty() {
return Err(String::from("idx array must be non-zero"));
}
let blstpoly = PolyData {
coeffs: vec![BlstFr::one(); indices.len() + 1],
};
let mut poly = blst_poly_into_pc_poly(&blstpoly.coeffs);
poly.coeffs[0] = (self.roots_of_unity[indices[0] * stride]).fr.neg();
for (i, indice) in indices.iter().enumerate().skip(1) {
let neg_di = (self.roots_of_unity[indice * stride]).fr.neg();
poly.coeffs[i] = neg_di + poly.coeffs[i - 1];
let mut j = i - 1;
while j > 0 {
let temp = poly.coeffs[j] * neg_di;
poly.coeffs[j] = temp + poly.coeffs[j - 1];
j -= 1;
}
poly.coeffs[0] *= neg_di;
}
Ok(pc_poly_into_blst_poly(poly))
}
fn reduce_partials(&self, len_out: usize, partials: &[PolyData]) -> Result<PolyData, String> {
let mut out_degree: usize = 0;
for partial in partials {
out_degree += partial.coeffs.len() - 1;
}
if out_degree + 1 > len_out {
return Err(String::from("Expected domain size to be a power of 2"));
}
let mut p_partial = pad_poly(&partials[0], len_out).unwrap();
let mut mul_eval_ps = self.fft_fr(&p_partial, false).unwrap();
for partial in partials.iter().skip(1) {
p_partial = pad_poly(partial, len_out)?;
let p_eval = self.fft_fr(&p_partial, false).unwrap();
for j in 0..len_out {
mul_eval_ps[j].fr *= p_eval[j].fr;
}
}
let coeffs = self.fft_fr(&mul_eval_ps, true)?;
let out = PolyData {
coeffs: coeffs[..(out_degree + 1)].to_vec(),
};
Ok(out)
}
fn zero_poly_via_multiplication(
&self,
length: usize,
missing_indices: &[usize],
) -> Result<(Vec<BlstFr>, PolyData), String> {
let zero_eval: Vec<BlstFr>;
let mut zero_poly: PolyData;
if missing_indices.is_empty() {
zero_eval = Vec::new();
zero_poly = PolyData { coeffs: Vec::new() };
return Ok((zero_eval, zero_poly));
}
if missing_indices.len() >= length {
return Err(String::from("Missing idxs greater than domain size"));
} else if length > self.max_width {
return Err(String::from(
"Domain size greater than fft_settings.max_width",
));
} else if !length.is_power_of_two() {
return Err(String::from("Domain size must be a power of 2"));
}
let degree_of_partial = 256;
let missing_per_partial = degree_of_partial - 1;
let domain_stride = self.max_width / length;
let mut partial_count =
(missing_per_partial + missing_indices.len() - 1) / missing_per_partial;
let domain_ceiling = min(next_pow_of_2(partial_count * degree_of_partial), length);
if missing_indices.len() <= missing_per_partial {
zero_poly = self.do_zero_poly_mul_partial(missing_indices, domain_stride)?;
} else {
let mut work = vec![BlstFr::zero(); next_pow_of_2(partial_count * degree_of_partial)];
let mut partial_lens = Vec::new();
let mut offset = 0;
let mut out_offset = 0;
let max = missing_indices.len();
for _i in 0..partial_count {
let end = min(offset + missing_per_partial, max);
let mut partial =
self.do_zero_poly_mul_partial(&missing_indices[offset..end], domain_stride)?;
partial.coeffs = pad_poly(&partial, degree_of_partial)?;
work.splice(
out_offset..(out_offset + degree_of_partial),
partial.coeffs.to_vec(),
);
partial_lens.push(degree_of_partial);
offset += missing_per_partial;
out_offset += degree_of_partial;
}
partial_lens[partial_count - 1] =
1 + missing_indices.len() - (partial_count - 1) * missing_per_partial;
let reduction_factor = 4;
while partial_count > 1 {
let reduced_count = 1 + (partial_count - 1) / reduction_factor;
let partial_size = next_pow_of_2(partial_lens[0]);
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, length);
let partials_num = min(reduction_factor, partial_count - start);
let mut partial_vec = Vec::new();
for j in 0..partials_num {
let k = (start + j) * partial_size;
partial_vec.push(PolyData {
coeffs: work[k..(k + partial_lens[i + j])].to_vec(),
});
}
if partials_num > 1 {
let mut reduced_poly = self.reduce_partials(reduced_len, &partial_vec)?;
partial_lens[i] = reduced_poly.coeffs.len();
reduced_poly.coeffs = pad_poly(&reduced_poly, partial_size * partials_num)?;
work.splice(
(start * partial_size)
..(start * partial_size + reduced_poly.coeffs.len()),
reduced_poly.coeffs,
);
} else {
partial_lens[i] = partial_lens[start];
}
}
partial_count = reduced_count;
}
zero_poly = PolyData { coeffs: work };
}
match zero_poly.coeffs.len().cmp(&length) {
Ordering::Less => zero_poly.coeffs = pad_poly(&zero_poly, length)?,
Ordering::Greater => zero_poly.coeffs = zero_poly.coeffs[..length].to_vec(),
Ordering::Equal => {}
}
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/arkworks5/src/fk20_proofs.rs | arkworks5/src/fk20_proofs.rs | use crate::consts::G1_IDENTITY;
use crate::kzg_proofs::{FFTSettings, KZGSettings};
use crate::kzg_types::{ArkFp, ArkFr as BlstFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine, ArkG2};
use crate::utils::PolyData;
use kzg::common_utils::reverse_bit_order;
use kzg::{FFTFr, FK20MultiSettings, FK20SingleSettings, Fr, G1Mul, Poly, FFTG1, G1};
#[cfg(feature = "parallel")]
use rayon::prelude::*;
#[repr(C)]
#[derive(Debug, Clone, Default)]
pub struct KzgFK20SingleSettings {
pub ks: KZGSettings,
pub x_ext_fft: Vec<ArkG1>,
pub x_ext_fft_len: usize,
}
#[repr(C)]
#[derive(Debug, Clone, Default)]
pub struct KzgFK20MultiSettings {
pub ks: KZGSettings,
pub chunk_len: usize,
pub x_ext_fft_files: Vec<Vec<ArkG1>>,
}
impl
FK20SingleSettings<
BlstFr,
ArkG1,
ArkG2,
FFTSettings,
PolyData,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
> for KzgFK20SingleSettings
{
fn new(ks: &KZGSettings, n2: usize) -> Result<Self, String> {
let n = n2 / 2;
if n2 > ks.fs.max_width {
return Err(String::from(
"n2 must be equal or less than kzg settings max width",
));
}
if !n2.is_power_of_two() {
return Err(String::from("n2 must be power of 2"));
}
if n2 < 2 {
return Err(String::from("n2 must be equal or greater than 2"));
}
let mut x = Vec::new();
for i in 0..(n - 1) {
x.push(ks.g1_values_monomial[n - 2 - i])
}
x.push(G1_IDENTITY);
let new_ks = KZGSettings {
fs: ks.fs.clone(),
..KZGSettings::default()
};
Ok(KzgFK20SingleSettings {
ks: new_ks,
x_ext_fft: toeplitz_part_1(&x, &ks.fs).unwrap(),
x_ext_fft_len: n2,
})
}
fn data_availability(&self, p: &PolyData) -> Result<Vec<ArkG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.ks.fs.max_width {
return Err(String::from(
"n2 must be equal or less than kzg settings max width",
));
}
if !n.is_power_of_two() {
return Err(String::from("n2 must be power of 2"));
}
let mut out = fk20_single_da_opt(p, self).unwrap();
reverse_bit_order(&mut out)?;
Ok(out)
}
fn data_availability_optimized(&self, p: &PolyData) -> Result<Vec<ArkG1>, String> {
fk20_single_da_opt(p, self)
}
}
impl
FK20MultiSettings<
BlstFr,
ArkG1,
ArkG2,
FFTSettings,
PolyData,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
> for KzgFK20MultiSettings
{
fn new(ks: &KZGSettings, n2: usize, chunk_len: usize) -> Result<Self, String> {
if n2 > ks.fs.max_width {
return Err(String::from(
"n2 must be equal or less than kzg settings max width",
));
}
if !n2.is_power_of_two() {
return Err(String::from("n2 must be power of 2"));
}
if n2 < 2 {
return Err(String::from("n2 must be equal or greater than 2"));
}
if chunk_len > n2 / 2 {
return Err(String::from("chunk_len must be equal or less than n2/2"));
}
if !chunk_len.is_power_of_two() {
return Err(String::from("chunk_len must be power of 2"));
}
if chunk_len == 0 {
return Err(String::from("chunk_len must be greater than 0"));
}
let n = n2 / 2;
let k = n / chunk_len;
let mut x_ext_fft_files = Vec::new();
for offset in 0..chunk_len {
let mut x = vec![ArkG1::default(); k];
let start = if n >= chunk_len + 1 + offset {
n - chunk_len - 1 - offset
} else {
0
};
let mut j = start;
for i in x.iter_mut().take(k - 1) {
i.0 = ks.g1_values_monomial[j].0;
if j >= chunk_len {
j -= chunk_len;
} else {
j = 0;
}
}
x[k - 1] = G1_IDENTITY;
x_ext_fft_files.push(toeplitz_part_1(&x, &ks.fs).unwrap());
}
let new_ks = KZGSettings {
fs: ks.fs.clone(),
..KZGSettings::default()
};
Ok(KzgFK20MultiSettings {
ks: new_ks,
x_ext_fft_files,
chunk_len,
})
}
fn data_availability(&self, p: &PolyData) -> Result<Vec<ArkG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > self.ks.fs.max_width {
return Err(String::from(
"n2 must be equal or less than kzg settings max width",
));
}
if !n.is_power_of_two() {
return Err(String::from("n2 must be power of 2"));
}
let mut out = fk20_multi_da_opt(p, self).unwrap();
reverse_bit_order(&mut out)?;
Ok(out)
}
fn data_availability_optimized(&self, p: &PolyData) -> Result<Vec<ArkG1>, String> {
fk20_multi_da_opt(p, self)
}
}
fn fk20_single_da_opt(p: &PolyData, fk: &KzgFK20SingleSettings) -> Result<Vec<ArkG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > fk.ks.fs.max_width {
return Err(String::from(
"n2 must be equal or less than kzg settings max width",
));
}
if !n.is_power_of_two() {
return Err(String::from("n2 must be power of 2"));
}
let outlen = 2 * p.len();
let toeplitz_coeffs = toeplitz_coeffs_step(p, outlen).unwrap();
let h_ext_fft = toeplitz_part_2(&toeplitz_coeffs, &fk.x_ext_fft, &fk.ks.fs).unwrap();
let h = toeplitz_part_3(&h_ext_fft, &fk.ks.fs).unwrap();
fk.ks.fs.fft_g1(&h, false)
}
fn fk20_multi_da_opt(p: &PolyData, fk: &KzgFK20MultiSettings) -> Result<Vec<ArkG1>, String> {
let n = p.len();
let n2 = n * 2;
if n2 > fk.ks.fs.max_width {
return Err(String::from(
"n2 must be equal or less than kzg settings max width",
));
}
if !n.is_power_of_two() {
return Err(String::from("n2 must be power of 2"));
}
let n = n2 / 2;
let k = n / fk.chunk_len;
let k2 = k * 2;
let mut h_ext_fft = Vec::new();
for _i in 0..k2 {
h_ext_fft.push(G1_IDENTITY);
}
let mut toeplitz_coeffs = PolyData::new(n2 / fk.chunk_len);
for i in 0..fk.chunk_len {
toeplitz_coeffs =
toeplitz_coeffs_stride(p, i, fk.chunk_len, toeplitz_coeffs.len()).unwrap();
let h_ext_fft_file =
toeplitz_part_2(&toeplitz_coeffs, &fk.x_ext_fft_files[i], &fk.ks.fs).unwrap();
for j in 0..k2 {
h_ext_fft[j] = h_ext_fft[j].add_or_dbl(&h_ext_fft_file[j]);
}
}
// Calculate `h`
let mut h = toeplitz_part_3(&h_ext_fft, &fk.ks.fs).unwrap();
// Overwrite the second half of `h` with zero
for i in h.iter_mut().take(k2).skip(k) {
i.0 = G1_IDENTITY.0;
}
fk.ks.fs.fft_g1(&h, false)
}
fn toeplitz_coeffs_step(p: &PolyData, outlen: usize) -> Result<PolyData, String> {
toeplitz_coeffs_stride(p, 0, 1, outlen)
}
fn toeplitz_coeffs_stride(
poly: &PolyData,
offset: usize,
stride: usize,
outlen: usize,
) -> Result<PolyData, String> {
let n = poly.len();
if stride == 0 {
return Err(String::from("stride must be greater than 0"));
}
let k = n / stride;
let k2 = k * 2;
if outlen < k2 {
return Err(String::from("outlen must be equal or greater than k2"));
}
let mut out = PolyData::new(outlen);
out.set_coeff_at(0, &poly.coeffs[n - 1 - offset]);
let mut i = 1;
while i <= (k + 1) && i < k2 {
out.set_coeff_at(i, &BlstFr::zero());
i += 1;
}
let mut j = 2 * stride - offset - 1;
for i in (k + 2)..k2 {
out.set_coeff_at(i, &poly.coeffs[j]);
j += stride;
}
Ok(out)
}
fn toeplitz_part_1(x: &[ArkG1], fs: &FFTSettings) -> Result<Vec<ArkG1>, String> {
let n = x.len();
let n2 = n * 2;
let mut x_ext = Vec::new();
for i in x.iter().take(n) {
x_ext.push(*i);
}
for _i in n..n2 {
x_ext.push(G1_IDENTITY);
}
fs.fft_g1(&x_ext, false)
}
fn toeplitz_part_2(
toeplitz_coeffs: &PolyData,
x_ext_fft: &[ArkG1],
fs: &FFTSettings,
) -> Result<Vec<ArkG1>, String> {
let toeplitz_coeffs_fft = fs.fft_fr(&toeplitz_coeffs.coeffs, false).unwrap();
#[cfg(feature = "parallel")]
{
let out: Vec<_> = (0..toeplitz_coeffs.len())
.into_par_iter()
.map(|i| x_ext_fft[i].mul(&toeplitz_coeffs_fft[i]))
.collect();
Ok(out)
}
#[cfg(not(feature = "parallel"))]
{
let mut out = Vec::new();
for i in 0..toeplitz_coeffs.len() {
out.push(x_ext_fft[i].mul(&toeplitz_coeffs_fft[i]));
}
Ok(out)
}
}
fn toeplitz_part_3(h_ext_fft: &[ArkG1], fs: &FFTSettings) -> Result<Vec<ArkG1>, String> {
let n = h_ext_fft.len() / 2;
let mut out = fs.fft_g1(h_ext_fft, true).unwrap();
// Zero the second half of h
for i in out.iter_mut().take(h_ext_fft.len()).skip(n) {
i.0 = G1_IDENTITY.0;
}
Ok(out)
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/src/utils.rs | arkworks5/src/utils.rs | use crate::kzg_proofs::FFTSettings;
use crate::kzg_types::{ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine};
use ark_bls12_381::{g1, g2, Fq, Fq2, Fr as Bls12Fr};
use ark_ec::models::short_weierstrass::Projective;
use ark_ff::Fp2;
use ark_poly::univariate::DensePolynomial as DensePoly;
use ark_poly::DenseUVPolynomial;
use kzg::eip_4844::PrecomputationTableManager;
use kzg::eth::c_bindings::{blst_fp, blst_fp2, blst_fr, blst_p1, blst_p2, CKZGSettings};
use kzg::eth;
#[derive(Debug, PartialEq, Eq)]
pub struct Error;
#[derive(Debug, Clone, Eq, PartialEq, Default)]
pub struct PolyData {
pub coeffs: Vec<ArkFr>,
}
// FIXME: Store just dense poly here
pub fn pc_poly_into_blst_poly(poly: DensePoly<Bls12Fr>) -> PolyData {
let mut bls_pol: Vec<ArkFr> = { Vec::new() };
for x in poly.coeffs {
bls_pol.push(ArkFr { fr: x });
}
PolyData { coeffs: bls_pol }
}
pub fn blst_poly_into_pc_poly(pd: &[ArkFr]) -> DensePoly<Bls12Fr> {
let mut poly: Vec<Bls12Fr> = vec![Bls12Fr::default(); pd.len()];
for i in 0..pd.len() {
poly[i] = pd[i].fr;
}
DensePoly::from_coefficients_vec(poly)
}
pub const fn pc_fq_into_blst_fp(fq: Fq) -> blst_fp {
blst_fp { l: fq.0 .0 }
}
pub const fn blst_fr_into_pc_fr(fr: blst_fr) -> Bls12Fr {
Bls12Fr {
0: ark_ff::BigInt(fr.l),
1: core::marker::PhantomData,
}
}
pub const fn pc_fr_into_blst_fr(fr: Bls12Fr) -> blst_fr {
blst_fr { l: fr.0 .0 }
}
pub const fn blst_fp_into_pc_fq(fp: &blst_fp) -> Fq {
Fq {
0: ark_ff::BigInt(fp.l),
1: core::marker::PhantomData,
}
}
pub const fn blst_fp2_into_pc_fq2(fp: &blst_fp2) -> Fq2 {
Fp2 {
c0: blst_fp_into_pc_fq(&fp.fp[0]),
c1: blst_fp_into_pc_fq(&fp.fp[1]),
}
}
pub const fn blst_p1_into_pc_g1projective(p1: &blst_p1) -> Projective<g1::Config> {
Projective {
x: blst_fp_into_pc_fq(&p1.x),
y: blst_fp_into_pc_fq(&p1.y),
z: blst_fp_into_pc_fq(&p1.z),
}
}
pub const fn pc_g1projective_into_blst_p1(p1: Projective<g1::Config>) -> blst_p1 {
blst_p1 {
x: blst_fp { l: p1.x.0 .0 },
y: blst_fp { l: p1.y.0 .0 },
z: blst_fp { l: p1.z.0 .0 },
}
}
pub const fn blst_p2_into_pc_g2projective(p2: &blst_p2) -> Projective<g2::Config> {
Projective {
x: blst_fp2_into_pc_fq2(&p2.x),
y: blst_fp2_into_pc_fq2(&p2.y),
z: blst_fp2_into_pc_fq2(&p2.z),
}
}
pub const fn pc_g2projective_into_blst_p2(p2: Projective<g2::Config>) -> blst_p2 {
blst_p2 {
x: blst_fp2 {
fp: [blst_fp { l: p2.x.c0.0 .0 }, blst_fp { l: p2.x.c1.0 .0 }],
},
y: blst_fp2 {
fp: [blst_fp { l: p2.y.c0.0 .0 }, blst_fp { l: p2.y.c1.0 .0 }],
},
z: blst_fp2 {
fp: [blst_fp { l: p2.z.c0.0 .0 }, blst_fp { l: p2.z.c1.0 .0 }],
},
}
}
pub(crate) fn fft_settings_to_rust(c_settings: *const CKZGSettings) -> Result<FFTSettings, 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| ArkFr::from_blst_fr(*r))
.collect::<Vec<ArkFr>>()
};
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| ArkFr::from_blst_fr(*r))
.collect::<Vec<ArkFr>>()
};
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| ArkFr::from_blst_fr(*r))
.collect::<Vec<ArkFr>>()
};
Ok(FFTSettings {
max_width: eth::FIELD_ELEMENTS_PER_EXT_BLOB,
root_of_unity: roots_of_unity[0],
roots_of_unity,
brp_roots_of_unity,
reverse_roots_of_unity,
})
}
pub(crate) static mut PRECOMPUTATION_TABLES: PrecomputationTableManager<
ArkFr,
ArkG1,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
> = 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/arkworks5/src/fft_g1.rs | arkworks5/src/fft_g1.rs | use crate::consts::G1_GENERATOR;
use crate::kzg_proofs::FFTSettings;
use crate::kzg_types::{ArkFp, ArkFr, ArkG1, ArkG1Affine};
use crate::kzg_types::ArkG1ProjAddAffine;
use kzg::msm::msm_impls::msm;
use kzg::msm::precompute::PrecomputationTable;
use kzg::{Fr as KzgFr, G1Mul};
use kzg::{FFTG1, G1};
use std::ops::MulAssign;
extern crate alloc;
pub fn g1_linear_combination(
out: &mut ArkG1,
points: &[ArkG1],
scalars: &[ArkFr],
len: usize,
precomputation: Option<
&PrecomputationTable<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>,
>,
) {
*out = msm::<ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, ArkFr>(
points,
scalars,
len,
precomputation,
);
}
pub fn make_data(data: usize) -> Vec<ArkG1> {
let mut vec = Vec::new();
if data != 0 {
vec.push(G1_GENERATOR);
for i in 1..data as u64 {
let res = vec[(i - 1) as usize].add_or_dbl(&G1_GENERATOR);
vec.push(res);
}
}
vec
}
impl FFTG1<ArkG1> for FFTSettings {
fn fft_g1(&self, data: &[ArkG1], inverse: bool) -> Result<Vec<ArkG1>, String> {
if data.len() > self.max_width {
return Err(String::from("data length is longer than allowed max width"));
}
if !data.len().is_power_of_two() {
return Err(String::from("data length is not power of 2"));
}
let stride: usize = self.max_width / data.len();
let mut ret = vec![ArkG1::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 = ArkFr::from_u64(data.len() as u64).inverse();
ret[..data.len()]
.iter_mut()
.for_each(|f| f.0.mul_assign(&inv_fr_len.fr));
}
Ok(ret)
}
}
pub fn fft_g1_slow(
ret: &mut [ArkG1],
data: &[ArkG1],
stride: usize,
roots: &[ArkFr],
roots_stride: usize,
) {
for i in 0..data.len() {
ret[i] = data[0].mul(&roots[0]);
for j in 1..data.len() {
let jv = data[j * stride];
let r = roots[((i * j) % data.len()) * roots_stride];
let v = jv.mul(&r);
ret[i] = ret[i].add_or_dbl(&v);
}
}
}
pub fn fft_g1_fast(
ret: &mut [ArkG1],
data: &[ArkG1],
stride: usize,
roots: &[ArkFr],
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(hi, &data[stride..], stride * 2, roots, roots_stride * 2),
|| fft_g1_fast(lo, data, 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];
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/src/recover.rs | arkworks5/src/recover.rs | use crate::consts::SCALE_FACTOR;
use crate::kzg_proofs::FFTSettings;
use crate::kzg_types::ArkFr as BlstFr;
use crate::utils::PolyData;
use kzg::{FFTFr, Fr, Poly, PolyRecover, ZeroPoly};
#[cfg(feature = "parallel")]
use kzg::common_utils::next_pow_of_2;
#[cfg(feature = "parallel")]
static mut INVERSE_FACTORS: Vec<BlstFr> = Vec::new();
#[cfg(feature = "parallel")]
static mut UNSCALE_FACTOR_POWERS: Vec<BlstFr> = Vec::new();
#[allow(clippy::needless_range_loop)]
pub fn scale_poly(p: &mut PolyData) {
let scale_factor = BlstFr::from_u64(SCALE_FACTOR);
let inv_factor = scale_factor.inverse();
#[allow(static_mut_refs)]
#[cfg(feature = "parallel")]
{
let optim = next_pow_of_2(p.len() - 1);
if optim <= 1024 {
unsafe {
if INVERSE_FACTORS.len() < p.len() {
if INVERSE_FACTORS.is_empty() {
INVERSE_FACTORS.push(BlstFr::one());
}
for i in (INVERSE_FACTORS.len())..p.len() {
INVERSE_FACTORS.push(INVERSE_FACTORS[i - 1].mul(&inv_factor));
}
}
for i in 1..p.len() {
p.coeffs[i] = p.coeffs[i].mul(&INVERSE_FACTORS[i]);
}
}
} else {
let mut factor_power = BlstFr::one();
for i in 1..p.len() {
factor_power = factor_power.mul(&inv_factor);
p.set_coeff_at(i, &p.get_coeff_at(i).mul(&factor_power));
}
}
}
#[cfg(not(feature = "parallel"))]
{
let mut factor_power = BlstFr::one();
for i in 1..p.len() {
factor_power = factor_power.mul(&inv_factor);
p.set_coeff_at(i, &p.get_coeff_at(i).mul(&factor_power));
}
}
}
#[allow(clippy::needless_range_loop)]
pub fn unscale_poly(p: &mut PolyData) {
let scale_factor = BlstFr::from_u64(SCALE_FACTOR);
#[allow(static_mut_refs)]
#[cfg(feature = "parallel")]
{
unsafe {
if UNSCALE_FACTOR_POWERS.len() < p.len() {
if UNSCALE_FACTOR_POWERS.is_empty() {
UNSCALE_FACTOR_POWERS.push(BlstFr::one());
}
for i in (UNSCALE_FACTOR_POWERS.len())..p.len() {
UNSCALE_FACTOR_POWERS.push(UNSCALE_FACTOR_POWERS[i - 1].mul(&scale_factor));
}
}
for i in 1..p.len() {
p.coeffs[i] = p.coeffs[i].mul(&UNSCALE_FACTOR_POWERS[i]);
}
}
}
#[cfg(not(feature = "parallel"))]
{
let mut factor_power = BlstFr::one();
for i in 1..p.len() {
factor_power = factor_power.mul(&scale_factor);
p.set_coeff_at(i, &p.get_coeff_at(i).mul(&factor_power));
}
}
}
impl PolyRecover<BlstFr, PolyData, FFTSettings> for PolyData {
fn recover_poly_coeffs_from_samples(
samples: &[Option<BlstFr>],
fs: &FFTSettings,
) -> Result<Self, String> {
if !samples.len().is_power_of_two() {
return Err(String::from("samples lenght has to be power of 2"));
}
let mut missing = Vec::new();
for (i, sample) in samples.iter().enumerate() {
if sample.is_none() {
missing.push(i);
}
}
if missing.len() > samples.len() / 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(samples.len(), missing.as_slice())?;
// Check all is well
for (i, item) in zero_eval.iter().enumerate().take(samples.len()) {
if samples[i].is_none() != item.is_zero() {
return Err(String::from("sample and item are both zero"));
}
}
// Construct E * Z_r,I: the loop makes the evaluation polynomial
let mut poly_evaluations_with_zero = vec![BlstFr::zero(); samples.len()];
for i in 0..samples.len() {
if samples[i].is_none() {
poly_evaluations_with_zero[i] = BlstFr::zero();
} else {
poly_evaluations_with_zero[i] = samples[i].unwrap().mul(&zero_eval[i]);
}
}
// Now inverse FFT so that poly_with_zero is (E * Z_r,I)(x) = (D * Z_r,I)(x)
let mut poly_with_zero = PolyData {
coeffs: fs
.fft_fr(poly_evaluations_with_zero.as_slice(), true)
.unwrap(),
};
#[cfg(feature = "parallel")]
let optim = next_pow_of_2(poly_with_zero.len() - 1);
#[cfg(feature = "parallel")]
{
if optim > 1024 {
rayon::join(
|| scale_poly(&mut poly_with_zero),
|| scale_poly(&mut zero_poly),
);
} else {
scale_poly(&mut poly_with_zero);
scale_poly(&mut zero_poly);
}
}
#[cfg(not(feature = "parallel"))]
{
scale_poly(&mut poly_with_zero);
scale_poly(&mut zero_poly);
}
// Q1 = (D * Z_r,I)(k * x)
let scaled_poly_with_zero = poly_with_zero; // Renaming
// Q2 = Z_r,I(k * x)
let scaled_zero_poly = zero_poly.coeffs; // Renaming
let eval_scaled_poly_with_zero;
let eval_scaled_zero_poly;
#[cfg(feature = "parallel")]
{
if optim > 1024 {
let mut eval_scaled_poly_with_zero_temp = vec![];
let mut eval_scaled_zero_poly_temp = vec![];
rayon::join(
|| {
eval_scaled_poly_with_zero_temp =
fs.fft_fr(&scaled_poly_with_zero.coeffs, false).unwrap()
},
|| eval_scaled_zero_poly_temp = fs.fft_fr(&scaled_zero_poly, false).unwrap(),
);
eval_scaled_poly_with_zero = eval_scaled_poly_with_zero_temp;
eval_scaled_zero_poly = eval_scaled_zero_poly_temp;
} else {
eval_scaled_poly_with_zero =
fs.fft_fr(&scaled_poly_with_zero.coeffs, false).unwrap();
eval_scaled_zero_poly = fs.fft_fr(&scaled_zero_poly, false).unwrap();
}
}
#[cfg(not(feature = "parallel"))]
{
eval_scaled_poly_with_zero = fs.fft_fr(&scaled_poly_with_zero.coeffs, false).unwrap();
eval_scaled_zero_poly = fs.fft_fr(&scaled_zero_poly, false).unwrap();
}
let mut eval_scaled_reconstructed_poly = eval_scaled_poly_with_zero.clone();
for i in 0..samples.len() {
eval_scaled_reconstructed_poly[i] = eval_scaled_poly_with_zero[i]
.div(&eval_scaled_zero_poly[i])
.unwrap();
}
// The result of the division is D(k * x):
let mut scaled_reconstructed_poly = PolyData {
coeffs: fs.fft_fr(&eval_scaled_reconstructed_poly, true).unwrap(),
};
// k * x -> x
unscale_poly(&mut scaled_reconstructed_poly);
// Finally we have D(x) which evaluates to our original data at the powers of roots of unity
Ok(scaled_reconstructed_poly)
}
fn recover_poly_from_samples(
samples: &[Option<BlstFr>],
fs: &FFTSettings,
) -> 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 out = PolyData {
coeffs: fs.fft_fr(&reconstructed_poly.coeffs, false).unwrap(),
};
// Check all is well
for (i, sample) in samples.iter().enumerate() {
if !sample.is_none() && !out.get_coeff_at(i).equals(&sample.unwrap()) {
return Err(String::from(
"sample is zero and out coeff at i is not equals to sample",
));
}
}
Ok(out)
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/src/fft.rs | arkworks5/src/fft.rs | use crate::kzg_proofs::FFTSettings;
use crate::kzg_types::ArkFr as BlstFr;
use kzg::{FFTFr, Fr as FFr};
impl FFTFr<BlstFr> for FFTSettings {
fn fft_fr(&self, data: &[BlstFr], inverse: bool) -> Result<Vec<BlstFr>, String> {
if data.len() > self.max_width {
return Err(String::from("data length is longer than allowed max width"));
}
if !data.len().is_power_of_two() {
return Err(String::from("data length is not power of 2"));
}
let stride = self.max_width / data.len();
let mut ret = vec![BlstFr::default(); data.len()];
let roots = if inverse {
&self.reverse_roots_of_unity
} else {
&self.roots_of_unity
};
fft_fr_fast(&mut ret, data, 1, roots, stride);
if inverse {
let inv_fr_len = BlstFr::from_u64(data.len() as u64).inverse();
ret[..data.len()]
.iter_mut()
.for_each(|f| *f = BlstFr::mul(f, &inv_fr_len));
}
Ok(ret)
}
}
pub fn fft_fr_fast(
ret: &mut [BlstFr],
data: &[BlstFr],
stride: usize,
roots: &[BlstFr],
roots_stride: usize,
) {
let half: usize = ret.len() / 2;
if half > 0 {
#[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 {
ret[0] = data[0];
}
}
pub fn fft_fr_slow(
ret: &mut [BlstFr],
data: &[BlstFr],
stride: usize,
roots: &[BlstFr],
roots_stride: usize,
) {
let mut v;
let mut jv;
let mut r;
for i in 0..data.len() {
ret[i] = data[0].mul(&roots[0]);
for j in 1..data.len() {
jv = data[j * stride];
r = roots[((i * j) % data.len()) * roots_stride];
v = jv.mul(&r);
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/arkworks5/tests/consts.rs | arkworks5/tests/consts.rs | #[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_arkworks5::consts::SCALE2_ROOT_OF_UNITY;
use rust_kzg_arkworks5::kzg_proofs::expand_root_of_unity;
use rust_kzg_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::ArkFr;
#[test]
fn roots_of_unity_out_of_bounds_fails_() {
roots_of_unity_out_of_bounds_fails::<ArkFr, FFTSettings>();
}
#[test]
fn roots_of_unity_are_plausible_() {
roots_of_unity_are_plausible::<ArkFr>(&SCALE2_ROOT_OF_UNITY);
}
#[test]
fn expand_roots_is_plausible_() {
expand_roots_is_plausible::<ArkFr>(&SCALE2_ROOT_OF_UNITY, &expand_root_of_unity);
}
#[test]
fn new_fft_settings_is_plausible_() {
new_fft_settings_is_plausible::<ArkFr, FFTSettings>();
}
#[test]
fn roots_of_unity_is_the_expected_size_() {
roots_of_unity_is_the_expected_size(&SCALE2_ROOT_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/arkworks5/tests/das.rs | arkworks5/tests/das.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::das::{das_extension_test_known, das_extension_test_random};
use rust_kzg_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::ArkFr;
#[test]
fn das_extension_test_known_() {
das_extension_test_known::<ArkFr, FFTSettings>();
}
#[test]
fn das_extension_test_random_() {
das_extension_test_random::<ArkFr, FFTSettings>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/eip_4844.rs | arkworks5/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_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,
verify_kzg_proof_batch_fails_with_incorrect_proof_test, verify_kzg_proof_batch_test,
};
use rust_kzg_arkworks5::consts::SCALE2_ROOT_OF_UNITY;
use rust_kzg_arkworks5::eip_4844::load_trusted_setup_filename_rust;
use rust_kzg_arkworks5::kzg_proofs::{expand_root_of_unity, FFTSettings, KZGSettings};
use rust_kzg_arkworks5::kzg_types::{
ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine, ArkG2,
};
use rust_kzg_arkworks5::utils::PolyData;
#[test]
pub fn bytes_to_bls_field_test_() {
bytes_to_bls_field_test::<ArkFr>();
}
#[test]
pub fn compute_powers_test_() {
compute_powers_test::<ArkFr>(&compute_powers);
}
#[test]
pub fn blob_to_kzg_commitment_test_() {
blob_to_kzg_commitment_test::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&load_trusted_setup_filename_rust,
&blob_to_kzg_commitment_rust,
);
}
#[test]
pub fn compute_kzg_proof_test_() {
compute_kzg_proof_test::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(&load_trusted_setup_filename_rust, &verify_kzg_proof_rust);
}
#[test]
pub fn test_vectors_verify_blob_kzg_proof_() {
test_vectors_verify_blob_kzg_proof::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
&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::<ArkFr, ArkG1>(&bytes_to_blob, &compute_challenge_rust);
}
#[test]
pub fn expand_root_of_unity_too_long() {
let out = expand_root_of_unity(&ArkFr::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(&ArkFr::from_u64_arr(&SCALE2_ROOT_OF_UNITY[1]), 3);
assert!(out.is_err());
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/kzg_proofs.rs | arkworks5/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_arkworks5::eip_7594::ArkBackend;
use rust_kzg_arkworks5::kzg_proofs::generate_trusted_setup;
#[test]
pub fn test_trusted_setup_in_correct_form() {
trusted_setup_in_correct_form::<ArkBackend>(&generate_trusted_setup);
}
#[test]
fn proof_single_() {
proof_single::<ArkBackend>(&generate_trusted_setup);
}
#[test]
fn commit_to_nil_poly_() {
commit_to_nil_poly::<ArkBackend>(&generate_trusted_setup);
}
#[test]
fn commit_to_too_long_poly_() {
commit_to_too_long_poly_returns_err::<ArkBackend>(&generate_trusted_setup);
}
#[test]
fn proof_multi_() {
proof_multi::<ArkBackend>(&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/arkworks5/tests/eip_7594.rs | arkworks5/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_arkworks5::eip_4844::load_trusted_setup_filename_rust;
use rust_kzg_arkworks5::eip_7594::ArkBackend;
#[test]
pub fn test_vectors_compute_cells_() {
test_vectors_compute_cells::<ArkBackend>(&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::<ArkBackend>(
&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::<ArkBackend>(&load_trusted_setup_filename_rust);
}
#[test]
pub fn test_vectors_verify_cell_kzg_proof_batch_() {
test_vectors_verify_cell_kzg_proof_batch::<ArkBackend>(&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::<ArkBackend>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/msm.rs | arkworks5/tests/msm.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::msm::msm_slice::{
test_msm_slice_window_size_1, test_msm_slice_window_size_16, test_msm_slice_window_size_2,
test_msm_slice_window_size_3,
};
#[test]
pub fn test_msm_slice_window_size_1_() {
test_msm_slice_window_size_1()
}
#[test]
fn test_msm_slice_window_size_2_() {
test_msm_slice_window_size_2();
}
#[test]
fn test_msm_slice_window_size_3_() {
test_msm_slice_window_size_3();
}
#[test]
fn test_msm_slice_window_size_16_() {
test_msm_slice_window_size_16();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/poly.rs | arkworks5/tests/poly.rs | #[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_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::ArkFr;
use rust_kzg_arkworks5::utils::PolyData;
#[test]
fn create_poly_of_length_ten_() {
create_poly_of_length_ten::<ArkFr, PolyData>();
}
#[test]
fn poly_eval_check_() {
poly_eval_check::<ArkFr, PolyData>();
}
#[test]
fn poly_eval_0_check_() {
poly_eval_0_check::<ArkFr, PolyData>();
}
#[test]
fn poly_eval_nil_check_() {
poly_eval_nil_check::<ArkFr, PolyData>();
}
#[test]
fn poly_inverse_simple_0_() {
poly_inverse_simple_0::<ArkFr, PolyData>();
}
#[test]
fn poly_inverse_simple_1_() {
poly_inverse_simple_1::<ArkFr, PolyData>();
}
#[test]
fn poly_test_div_() {
poly_test_div::<ArkFr, PolyData>();
}
#[test]
#[should_panic]
fn poly_div_by_zero_() {
poly_div_by_zero::<ArkFr, PolyData>();
}
#[test]
fn poly_mul_direct_test_() {
poly_mul_direct_test::<ArkFr, PolyData>();
}
#[test]
fn poly_mul_fft_test_() {
poly_mul_fft_test::<ArkFr, PolyData, FFTSettings>();
}
#[test]
fn poly_mul_random_() {
poly_mul_random::<ArkFr, PolyData, FFTSettings>();
}
#[test]
fn poly_div_random_() {
poly_div_random::<ArkFr, PolyData>();
}
#[test]
fn poly_div_long_test_() {
poly_div_long_test::<ArkFr, PolyData>()
}
#[test]
fn poly_div_fast_test_() {
poly_div_fast_test::<ArkFr, PolyData>()
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/zero_poly.rs | arkworks5/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_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::ArkFr;
use rust_kzg_arkworks5::utils::PolyData;
#[test]
fn test_reduce_partials_() {
test_reduce_partials::<ArkFr, FFTSettings, PolyData>();
}
#[test]
fn reduce_partials_random_() {
reduce_partials_random::<ArkFr, FFTSettings, PolyData>();
}
#[test]
fn check_test_data_() {
check_test_data::<ArkFr, FFTSettings, PolyData>();
}
#[test]
fn zero_poly_known_() {
zero_poly_known::<ArkFr, FFTSettings, PolyData>();
}
#[test]
fn zero_poly_random_() {
zero_poly_random::<ArkFr, FFTSettings, PolyData>();
}
#[test]
fn zero_poly_all_but_one_() {
zero_poly_all_but_one::<ArkFr, FFTSettings, PolyData>();
}
#[test]
fn zero_poly_252_() {
zero_poly_252::<ArkFr, FFTSettings, PolyData>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/bls12_381.rs | arkworks5/tests/bls12_381.rs | #[cfg(test)]
mod tests {
use kzg::common_utils::log_2_byte;
use kzg_bench::tests::bls12_381::*;
use rust_kzg_arkworks5::fft_g1::g1_linear_combination;
use rust_kzg_arkworks5::kzg_proofs::pairings_verify;
use rust_kzg_arkworks5::kzg_types::{
ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine, ArkG2,
};
#[test]
pub fn log_2_byte_works_() {
log_2_byte_works(&log_2_byte);
}
#[test]
pub fn fr_is_zero_works_() {
fr_is_zero_works::<ArkFr>();
}
#[test]
pub fn fr_is_one_works_() {
fr_is_one_works::<ArkFr>();
}
#[test]
pub fn fr_from_uint64_works_() {
fr_from_uint64_works::<ArkFr>();
}
#[test]
pub fn fr_equal_works_() {
fr_equal_works::<ArkFr>();
}
#[test]
pub fn fr_negate_works_() {
fr_negate_works::<ArkFr>();
}
#[test]
pub fn fr_pow_works_() {
fr_pow_works::<ArkFr>();
}
#[test]
pub fn fr_div_works_() {
fr_div_works::<ArkFr>();
}
#[test]
#[should_panic]
pub fn fr_div_by_zero_() {
fr_div_by_zero::<ArkFr>();
}
#[test]
pub fn fr_uint64s_roundtrip_() {
fr_uint64s_roundtrip::<ArkFr>();
}
#[test]
pub fn p1_mul_works_() {
p1_mul_works::<ArkFr, ArkG1>();
}
#[test]
pub fn p1_sub_works_() {
p1_sub_works::<ArkG1>();
}
#[test]
pub fn p1_add_or_dbl_works_() {
p1_add_or_dbl_works::<ArkG1>();
}
#[test]
pub fn p1_add_zero_works_() {
p1_add_zero_works::<ArkG1>();
}
#[test]
pub fn p2_add_or_dbl_works_() {
p2_add_or_dbl_works::<ArkG2>();
}
#[test]
pub fn p2_mul_works_() {
p2_mul_works::<ArkFr, ArkG2>();
}
#[test]
pub fn p2_sub_works_() {
p2_sub_works::<ArkG2>();
}
#[test]
pub fn g1_identity_is_infinity_() {
g1_identity_is_infinity::<ArkG1>();
}
#[test]
pub fn g1_identity_is_identity_() {
g1_identity_is_identity::<ArkG1>();
}
#[test]
pub fn g1_make_linear_combination_() {
g1_make_linear_combination::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>(
&g1_linear_combination,
);
}
#[test]
pub fn g1_random_linear_combination_() {
g1_random_linear_combination::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>(
&g1_linear_combination,
);
}
#[test]
pub fn g1_linear_combination_infinity_points_() {
g1_linear_combination_infinity_points::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>(
&g1_linear_combination,
);
}
#[test]
fn g1_small_linear_combination_() {
g1_small_linear_combination::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>(
&g1_linear_combination,
)
}
#[test]
pub fn pairings_work_() {
pairings_work::<ArkFr, ArkG1, ArkG2>(&pairings_verify);
}
#[test]
pub fn fr_is_null_works_() {
fr_is_null_works::<ArkFr>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/fk20_proofs.rs | arkworks5/tests/fk20_proofs.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::fk20_proofs::*;
use rust_kzg_arkworks5::eip_7594::ArkBackend;
use rust_kzg_arkworks5::fk20_proofs::{KzgFK20MultiSettings, KzgFK20SingleSettings};
use rust_kzg_arkworks5::kzg_proofs::generate_trusted_setup;
#[test]
fn test_fk_single() {
fk_single::<ArkBackend, KzgFK20SingleSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_single_strided() {
fk_single_strided::<ArkBackend, KzgFK20SingleSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_settings() {
fk_multi_settings::<ArkBackend, KzgFK20MultiSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_chunk_len_1_512() {
fk_multi_chunk_len_1_512::<ArkBackend, KzgFK20MultiSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_chunk_len_16_512() {
fk_multi_chunk_len_16_512::<ArkBackend, KzgFK20MultiSettings>(&generate_trusted_setup);
}
#[test]
fn test_fk_multi_chunk_len_16_16() {
fk_multi_chunk_len_16_16::<ArkBackend, KzgFK20MultiSettings>(&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/arkworks5/tests/bucket_msm.rs | arkworks5/tests/bucket_msm.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::msm::bucket_msm::{
test_process_point_and_slices_deal_three_points,
test_process_point_and_slices_glv_deal_two_points,
};
use rust_kzg_arkworks5::kzg_types::{ArkFp, ArkG1, ArkG1Affine, ArkG1ProjAddAffine};
#[test]
pub fn test_process_point_and_slices_deal_three_points_() {
test_process_point_and_slices_deal_three_points::<
ArkG1,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>();
}
#[test]
fn test_process_point_and_slices_glv_deal_two_points_() {
test_process_point_and_slices_glv_deal_two_points::<
ArkG1,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/fft_g1.rs | arkworks5/tests/fft_g1.rs | #[cfg(test)]
mod tests {
use kzg_bench::tests::fft_g1::{compare_ft_fft, roundtrip_fft, stride_fft};
use rust_kzg_arkworks5::fft_g1::{fft_g1_fast, fft_g1_slow, make_data};
use rust_kzg_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::{ArkFr, ArkG1};
#[test]
fn roundtrip_fft_() {
roundtrip_fft::<ArkFr, ArkG1, FFTSettings>(&make_data);
}
#[test]
fn stride_fft_() {
stride_fft::<ArkFr, ArkG1, FFTSettings>(&make_data);
}
#[test]
fn compare_sft_fft_() {
compare_ft_fft::<ArkFr, ArkG1, FFTSettings>(&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/arkworks5/tests/fft_fr.rs | arkworks5/tests/fft_fr.rs | mod batch_adder;
#[cfg(test)]
mod tests {
use kzg_bench::tests::fft_fr::{compare_sft_fft, inverse_fft, roundtrip_fft, stride_fft};
use rust_kzg_arkworks5::fft::{fft_fr_fast, fft_fr_slow};
use rust_kzg_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::ArkFr;
#[test]
fn compare_sft_fft_() {
compare_sft_fft::<ArkFr, FFTSettings>(&fft_fr_slow, &fft_fr_fast);
}
#[test]
fn roundtrip_fft_() {
roundtrip_fft::<ArkFr, FFTSettings>();
}
#[test]
fn inverse_fft_() {
inverse_fft::<ArkFr, FFTSettings>();
}
#[test]
fn stride_fft_() {
stride_fft::<ArkFr, FFTSettings>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/batch_adder.rs | arkworks5/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_arkworks5::kzg_types::{ArkFp, ArkG1, ArkG1Affine};
#[test]
fn test_phase_one_zero_or_neg_() {
test_phase_one_zero_or_neg::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_phase_one_p_add_p_() {
test_phase_one_p_add_p::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_phase_one_p_add_q_() {
test_phase_one_p_add_q::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_phase_one_p_add_q_twice_() {
test_phase_one_p_add_q_twice::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_phase_two_zero_add_p_() {
test_phase_two_zero_add_p::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_phase_two_p_add_neg_() {
test_phase_two_p_add_neg::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_phase_two_p_add_q_() {
test_phase_two_p_add_q::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
pub fn test_phase_two_p_add_p_() {
test_phase_two_p_add_p::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_batch_add_() {
test_batch_add::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_batch_add_step_n_() {
test_batch_add_step_n::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_batch_add_indexed_() {
test_batch_add_indexed::<ArkG1, ArkFp, ArkG1Affine>();
}
#[test]
fn test_batch_add_indexed_single_bucket_() {
test_batch_add_indexed_single_bucket::<ArkG1, ArkFp, ArkG1Affine>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/tests/recover.rs | arkworks5/tests/recover.rs | #[cfg(test)]
mod recover_tests {
use kzg_bench::tests::recover::*;
use rust_kzg_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::ArkFr as Fr;
use rust_kzg_arkworks5::utils::PolyData;
#[test]
fn recover_simple_() {
recover_simple::<Fr, FFTSettings, PolyData, PolyData>();
}
//Could be not working because of zero poly.
#[test]
fn recover_random_() {
recover_random::<Fr, FFTSettings, PolyData, PolyData>();
}
#[test]
fn more_than_half_missing_() {
more_than_half_missing::<Fr, FFTSettings, PolyData, PolyData>();
}
}
| rust | Apache-2.0 | d47acbdf587753f466a5e6842395e03930ae1f96 | 2026-01-04T20:22:26.256259Z | false |
grandinetech/rust-kzg | https://github.com/grandinetech/rust-kzg/blob/d47acbdf587753f466a5e6842395e03930ae1f96/arkworks5/benches/das.rs | arkworks5/benches/das.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::das::bench_das_extension;
use rust_kzg_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::ArkFr;
fn bench_das_extension_(c: &mut Criterion) {
bench_das_extension::<ArkFr, FFTSettings>(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/arkworks5/benches/eip_4844.rs | arkworks5/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_arkworks5::eip_4844::load_trusted_setup_filename_rust;
use rust_kzg_arkworks5::kzg_proofs::{FFTSettings, KZGSettings};
use rust_kzg_arkworks5::kzg_types::{ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine, ArkG2};
use rust_kzg_arkworks5::utils::PolyData;
fn bench_eip_4844_(c: &mut Criterion) {
bench_eip_4844::<
ArkFr,
ArkG1,
ArkG2,
PolyData,
FFTSettings,
KZGSettings,
ArkFp,
ArkG1Affine,
ArkG1ProjAddAffine,
>(
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/arkworks5/benches/eip_7594.rs | arkworks5/benches/eip_7594.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg::eip_4844::{blob_to_kzg_commitment_rust, bytes_to_blob};
use kzg_bench::benches::eip_7594::bench_eip_7594;
use rust_kzg_arkworks5::{eip_4844::load_trusted_setup_filename_rust, eip_7594::ArkBackend};
fn bench_eip_7594_(c: &mut Criterion) {
bench_eip_7594::<ArkBackend>(
c,
&load_trusted_setup_filename_rust,
&bytes_to_blob,
&blob_to_kzg_commitment_rust,
);
}
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/arkworks5/benches/poly.rs | arkworks5/benches/poly.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::poly::bench_new_poly_div;
use rust_kzg_arkworks5::kzg_types::ArkFr;
use rust_kzg_arkworks5::utils::PolyData;
fn bench_new_poly_div_(c: &mut Criterion) {
bench_new_poly_div::<ArkFr, PolyData>(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/arkworks5/benches/zero_poly.rs | arkworks5/benches/zero_poly.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::zero_poly::bench_zero_poly;
use rust_kzg_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::ArkFr;
use rust_kzg_arkworks5::utils::PolyData;
fn bench_zero_poly_(c: &mut Criterion) {
bench_zero_poly::<ArkFr, FFTSettings, PolyData>(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/arkworks5/benches/kzg.rs | arkworks5/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_arkworks5::eip_7594::ArkBackend;
use rust_kzg_arkworks5::kzg_proofs::generate_trusted_setup;
fn bench_commit_to_poly_(c: &mut Criterion) {
bench_commit_to_poly::<ArkBackend>(c, &generate_trusted_setup);
}
fn bench_compute_proof_single_(c: &mut Criterion) {
bench_compute_proof_single::<ArkBackend>(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/arkworks5/benches/lincomb.rs | arkworks5/benches/lincomb.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::lincomb::bench_g1_lincomb;
use rust_kzg_arkworks5::fft_g1::g1_linear_combination;
use rust_kzg_arkworks5::kzg_types::{ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine};
fn bench_g1_lincomb_(c: &mut Criterion) {
bench_g1_lincomb::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>(
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/arkworks5/benches/fk_20.rs | arkworks5/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_arkworks5::eip_7594::ArkBackend;
use rust_kzg_arkworks5::fk20_proofs::{KzgFK20MultiSettings, KzgFK20SingleSettings};
use rust_kzg_arkworks5::kzg_proofs::generate_trusted_setup;
fn bench_fk_single_da_(c: &mut Criterion) {
bench_fk_single_da::<ArkBackend, KzgFK20SingleSettings>(c, &generate_trusted_setup)
}
fn bench_fk_multi_da_(c: &mut Criterion) {
bench_fk_multi_da::<ArkBackend, KzgFK20MultiSettings>(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/arkworks5/benches/recover.rs | arkworks5/benches/recover.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::recover::bench_recover;
use rust_kzg_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::ArkFr;
use rust_kzg_arkworks5::utils::PolyData;
fn bench_recover_(c: &mut Criterion) {
bench_recover::<ArkFr, FFTSettings, PolyData, PolyData>(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/arkworks5/benches/fft.rs | arkworks5/benches/fft.rs | use criterion::{criterion_group, criterion_main, Criterion};
use kzg_bench::benches::fft::{bench_fft_fr, bench_fft_g1};
use rust_kzg_arkworks5::kzg_proofs::FFTSettings;
use rust_kzg_arkworks5::kzg_types::{ArkFr, ArkG1};
fn bench_fft_fr_(c: &mut Criterion) {
bench_fft_fr::<ArkFr, FFTSettings>(c);
}
fn bench_fft_g1_(c: &mut Criterion) {
bench_fft_g1::<ArkFr, ArkG1, FFTSettings>(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/msm-benches/src/lib.rs | msm-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/msm-benches/benches/g1_fixed_base_msm.rs | msm-benches/benches/g1_fixed_base_msm.rs | use std::env;
use blst::{blst_p1_is_equal, blst_p1s_mult_wbits, blst_p1s_mult_wbits_precompute};
use criterion::{criterion_group, criterion_main, BenchmarkId, Criterion};
use ekzg_bls12_381::fixed_base_msm_window::FixedBaseMSMPrecompWindow;
use human_bytes::human_bytes;
use kzg::{
msm::{msm_impls::msm, precompute::precompute},
Fr, G1Affine, G1Mul, G1,
};
use rand::Rng;
use rand_chacha::rand_core::SeedableRng;
use rust_kzg_blst::types::{
fp::FsFp,
fr::FsFr,
g1::{FsG1, FsG1Affine, FsG1ProjAddAffine},
};
fn bench_fixed_base_msm(c: &mut Criterion) {
let npow: usize = env::var("BENCH_NPOW")
.unwrap_or("12".to_owned())
.parse()
.unwrap();
let npoints = 1usize << npow;
let mut rng = {
let seed = env::var("SEED").unwrap_or("rand".to_owned());
if seed == "rand" {
rand_chacha::ChaCha8Rng::from_rng(rand::thread_rng()).unwrap()
} else {
rand_chacha::ChaCha8Rng::seed_from_u64(seed.parse().unwrap())
}
};
let points = (0..npoints)
.map(|_| {
let fr = FsFr::from_bytes_unchecked(&rng.gen::<[u8; 32]>()).unwrap();
let p = FsG1::generator().mul(&fr);
p.to_bytes()
})
.collect::<Vec<_>>();
let scalars = (0..npoints)
.map(|_| {
let fr = FsFr::from_bytes_unchecked(&rng.gen::<[u8; 32]>()).unwrap();
fr.to_bytes()
})
.collect::<Vec<_>>();
let expected_result = {
let mut res = FsG1::zero();
for (p, s) in points.iter().zip(scalars.iter()) {
let p = FsG1::from_bytes(p).unwrap();
let s = FsFr::from_bytes(s).unwrap();
res = res.add_or_dbl(&p.mul(&s));
}
res.to_bytes()
};
{
let points = points
.iter()
.map(|p| FsG1Affine::into_affine(&FsG1::from_bytes(p).unwrap()).0)
.collect::<Vec<_>>();
let points = [points.as_ptr(), std::ptr::null()];
let mut group = c.benchmark_group("blst wbits initialization");
let precomputations = option_env!("WINDOW_SIZE")
.map(|v| {
v.parse()
.expect("WINDOW_SIZE environment variable must be valid number")
})
.map(|v| v..=v)
.unwrap_or(8..=10)
.map(|wbits| {
let precompute_size =
unsafe { blst::blst_p1s_mult_wbits_precompute_sizeof(wbits, npoints) };
let mut precomputation = vec![
blst::blst_p1_affine::default();
precompute_size / size_of::<blst::blst_p1_affine>()
];
unsafe {
blst_p1s_mult_wbits_precompute(
precomputation.as_mut_ptr(),
wbits,
points.as_ptr(),
npoints,
)
};
group.bench_function(
BenchmarkId::from_parameter(format!(
"points: 2^{}, wbits: {}, precomp_size: {}",
npow,
wbits,
human_bytes(precompute_size as f64)
)),
|b| {
b.iter(|| {
unsafe {
blst_p1s_mult_wbits_precompute(
precomputation.as_mut_ptr(),
wbits,
points.as_ptr(),
npoints,
)
};
});
},
);
(wbits, precomputation)
})
.collect::<Vec<_>>();
group.finish();
let scalars = scalars
.iter()
.map(|s| {
let mut scalar = blst::blst_scalar::default();
unsafe {
blst::blst_scalar_from_bendian(&mut scalar, s.as_ptr());
}
scalar.b
})
.collect::<Vec<_>>();
let expected_result = FsG1::from_bytes(&expected_result).unwrap().0;
let mut group = c.benchmark_group("blst wbits mult");
precomputations
.into_iter()
.for_each(|(wbits, precomputation)| {
let scratch_size = unsafe { blst::blst_p1s_mult_wbits_scratch_sizeof(npoints) };
let mut scratch =
vec![blst::limb_t::default(); scratch_size / size_of::<blst::limb_t>()];
let scalars_arg = [scalars.as_ptr() as *const u8, std::ptr::null()];
group.bench_function(
BenchmarkId::from_parameter(format!("points: 2^{}, wbits: {}", npow, wbits)),
|b| {
b.iter(|| {
let mut output = blst::blst_p1::default();
unsafe {
blst_p1s_mult_wbits(
&mut output,
precomputation.as_ptr(),
wbits,
npoints,
scalars_arg.as_ptr(),
255,
scratch.as_mut_ptr(),
);
}
assert!(unsafe { blst_p1_is_equal(&output, &expected_result) });
})
},
);
});
group.finish();
}
{
let points = points
.iter()
.map(|p| blstrs::G1Projective::from_compressed(p).unwrap().into())
.collect::<Vec<_>>();
let mut group = c.benchmark_group("crate-crypto wbits initialization");
let precomputations = option_env!("WINDOW_SIZE")
.map(|v| {
v.parse()
.expect("WINDOW_SIZE environment variable must be valid number")
})
.map(|v| v..=v)
.unwrap_or(8..=10)
.map(|wbits| {
group.bench_function(
BenchmarkId::from_parameter(format!("points: 2^{}, wbits: {}", npow, wbits)),
|b| {
b.iter(|| FixedBaseMSMPrecompWindow::new(&points, wbits));
},
);
(wbits, FixedBaseMSMPrecompWindow::new(&points, wbits))
})
.collect::<Vec<_>>();
group.finish();
let scalars = scalars
.iter()
.map(|s| blstrs::Scalar::from_bytes_be(s).unwrap())
.collect::<Vec<_>>();
let expected_result = blstrs::G1Projective::from_compressed(&expected_result).unwrap();
let mut group = c.benchmark_group("crate-crypto wbits mult");
precomputations
.into_iter()
.for_each(|(wbits, precomputation)| {
group.bench_function(
BenchmarkId::from_parameter(format!("points: 2^{}, wbits: {}", npow, wbits)),
|b| {
b.iter(|| {
let result = precomputation.msm(&scalars);
assert_eq!(result, expected_result);
})
},
);
});
group.finish();
}
{
let points = points
.iter()
.map(|p| FsG1::from_bytes(p).unwrap())
.collect::<Vec<_>>();
let table = precompute::<FsFr, FsG1, FsFp, FsG1Affine, FsG1ProjAddAffine>(&points, &[])
.ok()
.flatten();
if table.is_some() {
c.bench_function(
format!("rust-kzg-blst msm initialization, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
precompute::<FsFr, FsG1, FsFp, FsG1Affine, FsG1ProjAddAffine>(&points, &[])
.unwrap()
.unwrap()
});
},
);
}
let scalars = scalars
.iter()
.map(|s| FsFr::from_bytes(s).unwrap())
.collect::<Vec<_>>();
let expected_result = FsG1::from_bytes(&expected_result).unwrap();
c.bench_function(
format!("rust-kzg-blst msm mult, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
let result = msm::<FsG1, FsFp, FsG1Affine, FsG1ProjAddAffine, FsFr>(
&points,
&scalars,
npoints,
table.as_ref(),
);
assert!(result.equals(&expected_result));
})
},
);
}
{
use rust_kzg_constantine::types::{
fp::CtFp,
fr::CtFr,
g1::{CtG1, CtG1Affine, CtG1ProjAddAffine},
};
let points = points
.iter()
.map(|p| CtG1::from_bytes(p).unwrap())
.collect::<Vec<_>>();
let table = precompute::<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>(&points, &[])
.ok()
.flatten();
if table.is_some() {
c.bench_function(
format!(
"rust-kzg-constantine msm initialization, points: 2^{}",
npow
)
.as_str(),
|b| {
b.iter(|| {
precompute::<CtFr, CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine>(&points, &[])
.unwrap()
.unwrap()
});
},
);
}
let scalars = scalars
.iter()
.map(|s| CtFr::from_bytes(s).unwrap())
.collect::<Vec<_>>();
let expected_result = CtG1::from_bytes(&expected_result).unwrap();
c.bench_function(
format!("rust-kzg-constantine msm mult, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
let result = msm::<CtG1, CtFp, CtG1Affine, CtG1ProjAddAffine, CtFr>(
&points,
&scalars,
npoints,
table.as_ref(),
);
assert!(result.equals(&expected_result));
})
},
);
}
{
use rust_kzg_arkworks3::{
fft_g1::g1_linear_combination,
kzg_types::{ArkFr, ArkG1},
};
let points = points
.iter()
.map(|p| ArkG1::from_bytes(p).unwrap())
.collect::<Vec<_>>();
let scalars = scalars
.iter()
.map(|s| ArkFr::from_bytes(s).unwrap())
.collect::<Vec<_>>();
let expected_result = ArkG1::from_bytes(&expected_result).unwrap();
c.bench_function(
format!("rust-kzg-arkworks3 msm mult, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
let mut output = ArkG1::default();
g1_linear_combination(&mut output, &points, &scalars, npoints, None);
assert!(output.equals(&expected_result));
})
},
);
}
{
use rust_kzg_arkworks4::kzg_types::{ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine};
let points = points
.iter()
.map(|p| ArkG1::from_bytes(p).unwrap())
.collect::<Vec<_>>();
let table =
precompute::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>(&points, &[])
.ok()
.flatten();
if table.is_some() {
c.bench_function(
format!("rust-kzg-arkworks4 msm initialization, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
precompute::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>(
&points,
&[],
)
.unwrap()
.unwrap()
});
},
);
}
let scalars = scalars
.iter()
.map(|s| ArkFr::from_bytes(s).unwrap())
.collect::<Vec<_>>();
c.bench_function(
format!("rust-kzg-arkworks4 msm mult, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
msm::<ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, ArkFr>(
&points,
&scalars,
npoints,
table.as_ref(),
);
})
},
);
}
{
use rust_kzg_arkworks5::kzg_types::{ArkFp, ArkFr, ArkG1, ArkG1Affine, ArkG1ProjAddAffine};
let points = points
.iter()
.map(|p| ArkG1::from_bytes(p).unwrap())
.collect::<Vec<_>>();
let table =
precompute::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>(&points, &[])
.ok()
.flatten();
if table.is_some() {
c.bench_function(
format!("rust-kzg-arkworks5 msm initialization, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
precompute::<ArkFr, ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine>(
&points,
&[],
)
.unwrap()
.unwrap()
});
},
);
}
let scalars = scalars
.iter()
.map(|s| ArkFr::from_bytes(s).unwrap())
.collect::<Vec<_>>();
let expected_result = ArkG1::from_bytes(&expected_result).unwrap();
c.bench_function(
format!("rust-kzg-arkworks5 msm mult, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
let result = msm::<ArkG1, ArkFp, ArkG1Affine, ArkG1ProjAddAffine, ArkFr>(
&points,
&scalars,
npoints,
table.as_ref(),
);
assert!(result.equals(&expected_result));
})
},
);
}
{
use rust_kzg_mcl::{
kzg_proofs::g1_linear_combination,
types::{fr::MclFr, g1::MclG1},
};
let points = points
.iter()
.map(|p| MclG1::from_bytes(p).unwrap())
.collect::<Vec<_>>();
let scalars = scalars
.iter()
.map(|s| MclFr::from_bytes(s).unwrap())
.collect::<Vec<_>>();
let expected_result = MclG1::from_bytes(&expected_result).unwrap();
c.bench_function(
format!("rust-kzg-mcl msm mult, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
let mut output = MclG1::default();
g1_linear_combination(&mut output, &points, &scalars, npoints, None);
assert!(output.equals(&expected_result));
})
},
);
}
{
use rust_kzg_zkcrypto::{
fft_g1::g1_linear_combination,
kzg_types::{ZFr, ZG1},
};
let points = points
.iter()
.map(|p| ZG1::from_bytes(p).unwrap())
.collect::<Vec<_>>();
let scalars = scalars
.iter()
.map(|s| ZFr::from_bytes(s).unwrap())
.collect::<Vec<_>>();
let expected_result = ZG1::from_bytes(&expected_result).unwrap();
c.bench_function(
format!("rust-kzg-zkcrypto msm mult, points: 2^{}", npow).as_str(),
|b| {
b.iter(|| {
let mut output = ZG1::default();
g1_linear_combination(&mut output, &points, &scalars, npoints, None);
assert!(output.equals(&expected_result));
})
},
);
}
}
criterion_group!(benches, bench_fixed_base_msm);
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/kzg/src/das.rs | kzg/src/das.rs | use alloc::format;
use core::mem::size_of;
use core::{fmt::Debug, hash::Hash};
use hashbrown::{HashMap, HashSet};
#[cfg(feature = "parallel")]
use rayon::prelude::*;
use alloc::{
string::{String, ToString},
vec,
vec::Vec,
};
use crate::G1ProjAddAffine;
use crate::{
cfg_iter, cfg_iter_mut,
common_utils::{reverse_bit_order, reverse_bits_limited},
eip_4844::{
blob_to_polynomial, compute_powers, hash, hash_to_bls_field, BYTES_PER_COMMITMENT,
BYTES_PER_FIELD_ELEMENT, BYTES_PER_PROOF,
},
eth, FFTFr, FFTSettings, Fr, G1Affine, G1Fp, G1LinComb, KZGSettings, PairingVerify, Poly,
FFTG1, G1, G2,
};
pub const RANDOM_CHALLENGE_KZG_CELL_BATCH_DOMAIN: [u8; 16] = *b"RCKZGCBATCH__V1_";
pub trait EcBackend {
type Fr: Fr + Debug + Send;
type G1Fp: G1Fp;
type G1Affine: G1Affine<Self::G1, Self::G1Fp>;
type G1ProjAddAffine: G1ProjAddAffine<Self::G1, Self::G1Fp, Self::G1Affine>;
type G1: G1
+ G1LinComb<Self::Fr, Self::G1Fp, Self::G1Affine, Self::G1ProjAddAffine>
+ PairingVerify<Self::G1, Self::G2>
+ Eq
+ Hash;
type G2: G2;
type Poly: Poly<Self::Fr>;
type FFTSettings: FFTSettings<Self::Fr> + FFTFr<Self::Fr> + FFTG1<Self::G1>;
type KZGSettings: KZGSettings<
Self::Fr,
Self::G1,
Self::G2,
Self::FFTSettings,
Self::Poly,
Self::G1Fp,
Self::G1Affine,
Self::G1ProjAddAffine,
>;
}
/// Deduplicates a vector and creates a mapping of original indices to deduplicated indices.
///
/// This function is taken from https://github.com/crate-crypto/rust-eth-kzg/blob/63d469ce1c98a9898a0d8cd717aa3ebe46ace227/eip7594/src/verifier.rs#L43-L68
fn deduplicate_with_indices<T: Eq + core::hash::Hash + Clone>(input: &[T]) -> (Vec<T>, Vec<usize>) {
let mut unique_items = Vec::new();
let mut index_map = HashMap::new();
let mut indices = Vec::with_capacity(input.len());
for item in input {
let index = match index_map.get(&item) {
Some(&index) => index,
None => {
let new_index = unique_items.len();
unique_items.push(item.clone());
index_map.insert(item, new_index);
new_index
}
};
indices.push(index);
}
(unique_items, indices)
}
/**
* This is a precomputed map of cell index to reverse-bits-limited cell index.
*
* for (size_t i = 0; i < CELLS_PER_EXT_BLOB; i++)
* printf("%#04llx,\n", reverse_bits_limited(CELLS_PER_EXT_BLOB, i));
*
* Because of the way our evaluation domain is defined, we can use CELL_INDICES_RBL to find the
* coset factor of a cell. In particular, for cell i, its coset factor is
* roots_of_unity[CELLS_INDICES_RBL[i]].
*/
const CELL_INDICES_RBL: [usize; 128] = [
0x00, 0x40, 0x20, 0x60, 0x10, 0x50, 0x30, 0x70, 0x08, 0x48, 0x28, 0x68, 0x18, 0x58, 0x38, 0x78,
0x04, 0x44, 0x24, 0x64, 0x14, 0x54, 0x34, 0x74, 0x0c, 0x4c, 0x2c, 0x6c, 0x1c, 0x5c, 0x3c, 0x7c,
0x02, 0x42, 0x22, 0x62, 0x12, 0x52, 0x32, 0x72, 0x0a, 0x4a, 0x2a, 0x6a, 0x1a, 0x5a, 0x3a, 0x7a,
0x06, 0x46, 0x26, 0x66, 0x16, 0x56, 0x36, 0x76, 0x0e, 0x4e, 0x2e, 0x6e, 0x1e, 0x5e, 0x3e, 0x7e,
0x01, 0x41, 0x21, 0x61, 0x11, 0x51, 0x31, 0x71, 0x09, 0x49, 0x29, 0x69, 0x19, 0x59, 0x39, 0x79,
0x05, 0x45, 0x25, 0x65, 0x15, 0x55, 0x35, 0x75, 0x0d, 0x4d, 0x2d, 0x6d, 0x1d, 0x5d, 0x3d, 0x7d,
0x03, 0x43, 0x23, 0x63, 0x13, 0x53, 0x33, 0x73, 0x0b, 0x4b, 0x2b, 0x6b, 0x1b, 0x5b, 0x3b, 0x7b,
0x07, 0x47, 0x27, 0x67, 0x17, 0x57, 0x37, 0x77, 0x0f, 0x4f, 0x2f, 0x6f, 0x1f, 0x5f, 0x3f, 0x7f,
];
pub trait DAS<B: EcBackend> {
fn kzg_settings(&self) -> &B::KZGSettings;
fn recover_cells_and_kzg_proofs(
&self,
recovered_cells: &mut [B::Fr],
recovered_proofs: Option<&mut [B::G1]>,
cell_indices: &[usize],
cells: &[B::Fr],
) -> Result<(), String> {
let kzg_settings = self.kzg_settings();
let ts_len = kzg_settings.get_g1_monomial().len();
let cell_size = kzg_settings.get_cell_size();
if recovered_cells.len() != 2 * ts_len
|| recovered_proofs
.as_ref()
.is_some_and(|it| it.len() != (2 * ts_len) / cell_size)
{
return Err("Invalid output array length".to_string());
}
if cells.len() / cell_size != cell_indices.len() {
return Err(
"Cell indicies mismatch - cells length must be equal to cell indicies length"
.to_string(),
);
}
if cells.len() > 2 * ts_len {
return Err("Cell length cannot be larger than CELLS_PER_EXT_BLOB".to_string());
}
if cells.len() < ts_len {
return Err(
"Impossible to recover - cells length cannot be less than CELLS_PER_EXT_BLOB / 2"
.to_string(),
);
}
for fr in recovered_cells.iter_mut() {
*fr = B::Fr::null();
}
// Trick to use HashSet, to check for duplicate commitments, is taken from rust-eth-kzg:
// https://github.com/crate-crypto/rust-eth-kzg/blob/63d469ce1c98a9898a0d8cd717aa3ebe46ace227/eip7594/src/recovery.rs#L64-L76
let mut provided_indices = HashSet::new();
for ((i, &cell_index), next_cell_index) in cell_indices
.iter()
.enumerate()
.zip(cell_indices.iter().map(Some).skip(1).chain(Some(None)))
{
if cell_index >= (2 * ts_len) / cell_size {
return Err(format!("Invalid cell index {cell_index}, position {i}: Cell index cannot be larger than CELLS_PER_EXT_BLOB"));
}
if let Some(&idx) = next_cell_index {
if idx <= cell_index {
return Err(
format!("Invalid cell indices: Indices must be in strictly ascending order, but indices at positions {i} and {next} are not ({cell_index} >= {idx})", next = i + 1)
);
}
}
if !provided_indices.insert(cell_index) {
return Err(format!(
"Invalid cell indices: cell index {cell_index} appears twice."
));
}
recovered_cells[cell_index * cell_size..(cell_index + 1) * cell_size]
.clone_from_slice(&cells[i * cell_size..(i + 1) * cell_size]);
}
let fft_settings = kzg_settings.get_fft_settings();
if cells.len() != 2 * ts_len {
recover_cells::<B>(
cell_size,
recovered_cells,
&provided_indices,
fft_settings,
2 * ts_len,
)
.map_err(|err| format!("Cell recovery failed with error: {err}"))?;
}
#[allow(clippy::redundant_slicing)]
let recovered_cells = &recovered_cells[..];
if let Some(recovered_proofs) = recovered_proofs {
let mut poly = vec![B::Fr::default(); ts_len * 2];
poly.clone_from_slice(recovered_cells);
poly_lagrange_to_monomial::<B>(&mut poly, fft_settings)?;
let res = compute_fk20_proofs::<B>(
cell_size,
&poly,
ts_len,
fft_settings,
self.kzg_settings(),
)
.map_err(|err| format!("Proof computation failed with error: {err}"))?;
recovered_proofs.clone_from_slice(&res);
reverse_bit_order(recovered_proofs)?;
}
Ok(())
}
#[allow(clippy::type_complexity)]
fn recover_cells_and_kzg_proofs_batch(
&self,
cell_indices: &[Vec<usize>],
cells: &[Vec<B::Fr>],
) -> Result<(Vec<Vec<B::Fr>>, Vec<Vec<B::G1>>), String>
where
Self: Sync,
{
if cell_indices.len() != cells.len() {
return Err("Cell indices & cells mismatch".to_string());
}
let kzg_settings = self.kzg_settings();
let ts_len = kzg_settings.get_g1_monomial().len();
let cell_size = kzg_settings.get_cell_size();
cfg_iter!(cells)
.zip(cfg_iter!(cell_indices))
.map(|(cells, cell_indices)| {
let mut recovered_cells = vec![B::Fr::null(); 2 * ts_len];
let mut recovered_proofs = vec![B::G1::default(); (2 * ts_len) / cell_size];
self.recover_cells_and_kzg_proofs(
&mut recovered_cells,
Some(&mut recovered_proofs),
cell_indices,
cells,
)?;
Ok((recovered_cells, recovered_proofs))
})
.collect::<Result<(Vec<_>, Vec<_>), String>>()
}
fn compute_cells_and_kzg_proofs(
&self,
cells: Option<&mut [B::Fr]>,
proofs: Option<&mut [B::G1]>,
blob: &[B::Fr],
) -> Result<(), String> {
if cells.is_none() && proofs.is_none() {
return Err("Both cells & proofs cannot be none".to_string());
}
let settings = self.kzg_settings();
let ts_size = settings.get_g1_monomial().len();
let cell_size = settings.get_cell_size();
let poly = blob_to_polynomial::<B::Fr, B::Poly>(blob)?;
let mut poly_monomial = vec![B::Fr::zero(); 2 * ts_size];
poly_monomial[0..ts_size].clone_from_slice(poly.get_coeffs());
let fft_settings = self.kzg_settings().get_fft_settings();
poly_lagrange_to_monomial::<B>(&mut poly_monomial[..ts_size], fft_settings)?;
// compute cells
if let Some(cells) = cells {
cells.clone_from_slice(
&fft_settings
.fft_fr(&poly_monomial, false)
.map_err(|err| format!("Cell computation failed with error: {err}"))?,
);
reverse_bit_order(cells)?;
};
// compute proofs
if let Some(proofs) = proofs {
let result = compute_fk20_proofs::<B>(
cell_size,
&poly_monomial,
ts_size,
fft_settings,
settings,
)
.map_err(|err| format!("Proof computation failed with error: {err:?}"))?;
proofs.clone_from_slice(&result);
reverse_bit_order(proofs)?;
}
Ok(())
}
fn verify_cell_kzg_proof_batch(
&self,
commitments: &[B::G1],
cell_indices: &[usize],
cells: &[B::Fr],
proofs: &[B::G1],
) -> Result<bool, String> {
let settings = self.kzg_settings();
let cell_size = settings.get_cell_size();
let cell_count = cells.len() / cell_size;
let ts_size = settings.get_g1_monomial().len();
if cells.len() != cell_indices.len() * cell_size {
return Err("Cell count mismatch".to_string());
}
if commitments.len() != cell_count {
return Err("Commitment count mismatch".to_string());
}
if proofs.len() != cell_count {
return Err("Proof count mismatch".to_string());
}
if cells.is_empty() {
return Ok(true);
}
if cfg_iter!(cell_indices).any(|&cell_index| cell_index >= (2 * ts_size) / cell_size) {
return Err("Invalid cell index".to_string());
}
if cfg_iter!(proofs).any(|proof| !proof.is_valid()) {
return Err("Proof is not valid".to_string());
}
let (unique_commitments, commitment_indices) = deduplicate_with_indices(commitments);
if cfg_iter!(unique_commitments).any(|commitment| !commitment.is_valid()) {
return Err("Commitment is not valid".to_string());
}
let fft_settings = settings.get_fft_settings();
let r = Self::compute_verify_cell_kzg_proof_batch_challenge(
cell_size,
&unique_commitments,
&commitment_indices,
cell_indices,
cells,
proofs,
ts_size,
)?;
let r_powers = compute_powers(&r, cell_count);
let proof_lincomb = B::G1::g1_lincomb(proofs, &r_powers, cell_count, None);
let final_g1_sum = compute_weighted_sum_of_commitments::<B>(
&unique_commitments,
&commitment_indices,
&r_powers,
);
let interpolation_poly_commit = compute_commitment_to_aggregated_interpolation_poly::<B>(
cell_size,
&r_powers,
cell_indices,
cells,
fft_settings,
settings.get_g1_monomial(),
)?;
let final_g1_sum = final_g1_sum.sub(&interpolation_poly_commit);
let weighted_sum_of_proofs = computed_weighted_sum_of_proofs::<B>(
cell_size,
proofs,
&r_powers,
cell_indices,
fft_settings,
ts_size * 2,
)?;
let final_g1_sum = final_g1_sum.add(&weighted_sum_of_proofs);
let power_of_s = &settings.get_g2_monomial()[cell_size];
Ok(B::G1::verify(
&final_g1_sum,
&B::G2::generator(),
&proof_lincomb,
power_of_s,
))
}
fn compute_verify_cell_kzg_proof_batch_challenge(
cell_size: usize,
commitments: &[B::G1],
commitment_indices: &[usize],
cell_indices: &[usize],
cells: &[B::Fr],
proofs: &[B::G1],
blob_size: usize,
) -> Result<B::Fr, String> {
let cell_count = cells.len() / cell_size;
if commitment_indices.len() != cell_count
|| cell_indices.len() != cell_count
|| proofs.len() != cell_count
{
return Err("Cell count mismatch".to_string());
}
let input_size = RANDOM_CHALLENGE_KZG_CELL_BATCH_DOMAIN.len() /* the domain separator */
+ size_of::<u64>() /* field elements per blob */
+ size_of::<u64>() /* cell_size */
+ size_of::<u64>() /* commitment count */
+ size_of::<u64>() /* cell count */
+ (commitments.len() * BYTES_PER_COMMITMENT) /* commitment bytes */
+ (cell_count * size_of::<u64>()) /* commitment indices */
+ (cell_count * size_of::<u64>()) /* cell indices */
+ (cell_count * cell_size * BYTES_PER_FIELD_ELEMENT) /* cells */
+ (cell_count * BYTES_PER_PROOF) /* proofs bytes */
;
let mut bytes = Vec::with_capacity(input_size);
bytes.extend_from_slice(&RANDOM_CHALLENGE_KZG_CELL_BATCH_DOMAIN);
bytes.extend_from_slice(&(blob_size as u64).to_be_bytes());
bytes.extend_from_slice(&(cell_size as u64).to_be_bytes());
bytes.extend_from_slice(&(commitments.len() as u64).to_be_bytes());
bytes.extend_from_slice(&(cell_count as u64).to_be_bytes());
for commitment in commitments {
bytes.extend_from_slice(&commitment.to_bytes());
}
for i in 0..cell_count {
bytes.extend_from_slice(&(commitment_indices[i] as u64).to_be_bytes());
bytes.extend_from_slice(&(cell_indices[i] as u64).to_be_bytes());
for fr in &cells[(i * cell_size)..((i + 1) * cell_size)] {
bytes.extend_from_slice(&fr.to_bytes());
}
bytes.extend_from_slice(&(proofs[i].to_bytes()));
}
let bytes = &bytes[..];
if bytes.len() != input_size {
return Err("Failed to create challenge - invalid length".to_string());
}
let eval_challenge = hash(bytes);
let r = hash_to_bls_field(&eval_challenge);
Ok(r)
}
}
fn shift_poly<B: EcBackend>(poly: &mut [B::Fr], shift_factor: &B::Fr) {
let mut factor_power = B::Fr::one();
for coeff in poly.iter_mut().skip(1) {
factor_power = factor_power.mul(shift_factor);
*coeff = coeff.mul(&factor_power);
}
}
fn coset_fft<B: EcBackend>(
mut input: Vec<B::Fr>,
fft_settings: &B::FFTSettings,
) -> Result<Vec<B::Fr>, String> {
if input.is_empty() {
return Err("Invalid input length".to_string());
}
// TODO: move 7 to constant
shift_poly::<B>(&mut input, &B::Fr::from_u64(7));
fft_settings.fft_fr(&input, false)
}
fn coset_ifft<B: EcBackend>(
input: &[B::Fr],
fft_settings: &B::FFTSettings,
) -> Result<Vec<B::Fr>, String> {
if input.is_empty() {
return Err("Invalid input length".to_string());
}
let mut output = fft_settings.fft_fr(input, true)?;
// TODO: move 1/7 to constant
shift_poly::<B>(&mut output, &B::Fr::one().div(&B::Fr::from_u64(7))?);
Ok(output)
}
fn compute_vanishing_polynomial_from_roots<B: EcBackend>(
roots: &[B::Fr],
) -> Result<Vec<B::Fr>, String> {
if roots.is_empty() {
return Err("Roots cannot be empty".to_string());
}
let mut poly = Vec::new();
poly.push(roots[0].negate());
for i in 1..roots.len() {
let neg_root = roots[i].negate();
poly.push(neg_root.add(&poly[i - 1]));
for j in (1..i).rev() {
poly[j] = poly[j].mul(&neg_root).add(&poly[j - 1]);
}
poly[0] = poly[0].mul(&neg_root);
}
poly.push(B::Fr::one());
Ok(poly)
}
fn vanishing_polynomial_for_missing_cells<B: EcBackend>(
cell_size: usize,
missing_cell_indicies: &[usize],
fft_settings: &B::FFTSettings,
field_elements_per_ext_blob: usize,
) -> Result<Vec<B::Fr>, String> {
let cells_per_ext_blob = field_elements_per_ext_blob / cell_size;
if missing_cell_indicies.is_empty() || missing_cell_indicies.len() >= cells_per_ext_blob {
return Err("Invalid missing cell indicies count".to_string());
}
let stride = field_elements_per_ext_blob / cells_per_ext_blob;
let roots = missing_cell_indicies
.iter()
.map(|i| fft_settings.get_roots_of_unity_at(*i * stride))
.collect::<Vec<_>>();
let short_vanishing_poly = compute_vanishing_polynomial_from_roots::<B>(&roots)?;
let mut vanishing_poly = vec![B::Fr::zero(); field_elements_per_ext_blob];
for (i, coeff) in short_vanishing_poly.into_iter().enumerate() {
vanishing_poly[i * cell_size] = coeff
}
Ok(vanishing_poly)
}
fn recover_cells<B: EcBackend>(
cell_size: usize,
output: &mut [B::Fr],
cell_indicies: &HashSet<usize>,
fft_settings: &B::FFTSettings,
field_elements_per_ext_blob: usize,
) -> Result<(), String> {
let cells_per_ext_blob = field_elements_per_ext_blob / cell_size;
let mut missing_cell_indicies = Vec::new();
let mut cells_brp = output.to_vec();
reverse_bit_order(&mut cells_brp)?;
for i in 0..cells_per_ext_blob {
if !cell_indicies.contains(&i) {
missing_cell_indicies.push(reverse_bits_limited(cells_per_ext_blob, i));
}
}
let missing_cell_indicies = &missing_cell_indicies[..];
if missing_cell_indicies.len() > cells_per_ext_blob / 2 {
return Err("Not enough cells".to_string());
}
let vanishing_poly_coeff = vanishing_polynomial_for_missing_cells::<B>(
cell_size,
missing_cell_indicies,
fft_settings,
field_elements_per_ext_blob,
)?;
let vanishing_poly_eval = fft_settings
.fft_fr(&vanishing_poly_coeff, false)
.map_err(|err| format!("Vanishing polynomial evaluation failed: {err}"))?;
let mut extended_evaluation_times_zero = Vec::with_capacity(field_elements_per_ext_blob);
for i in 0..field_elements_per_ext_blob {
if cells_brp[i].is_null() {
extended_evaluation_times_zero.push(B::Fr::zero());
} else {
extended_evaluation_times_zero.push(cells_brp[i].mul(&vanishing_poly_eval[i]));
}
}
let extended_evaluation_times_zero_coeffs =
fft_settings.fft_fr(&extended_evaluation_times_zero, true)?;
let mut extended_evaluations_over_coset =
coset_fft::<B>(extended_evaluation_times_zero_coeffs, fft_settings)?;
let mut vanishing_poly_over_coset = coset_fft::<B>(vanishing_poly_coeff, fft_settings)?;
batch_inverse::<B>(&mut vanishing_poly_over_coset);
for i in 0..field_elements_per_ext_blob {
extended_evaluations_over_coset[i] =
extended_evaluations_over_coset[i].mul(&vanishing_poly_over_coset[i]);
}
let reconstructed_poly_coeff = coset_ifft::<B>(&extended_evaluations_over_coset, fft_settings)?;
let out = fft_settings.fft_fr(&reconstructed_poly_coeff, false)?;
output.clone_from_slice(&out);
reverse_bit_order(output)?;
Ok(())
}
fn poly_lagrange_to_monomial<B: EcBackend>(
lagrange_poly: &mut [B::Fr],
fft_settings: &B::FFTSettings,
) -> Result<(), String> {
let mut poly = lagrange_poly.to_vec();
reverse_bit_order(&mut poly)?;
lagrange_poly.clone_from_slice(&fft_settings.fft_fr(&poly, true)?);
Ok(())
}
fn toeplitz_coeffs_stride<B: EcBackend>(
out: &mut [B::Fr],
input: &[B::Fr],
n: usize,
offset: usize,
stride: usize,
) -> Result<(), String> {
let r = n / stride;
let l = stride;
let d = n - 1;
let d_minus_i = d - offset;
if d < offset {
return Err("Invalid offset".to_string());
}
for j in out.iter_mut() {
*j = B::Fr::zero();
}
out[0] = input[d_minus_i].clone();
for j in 1..r - 1 {
out[2 * r - j] = input[d_minus_i - j * l].clone();
}
Ok(())
}
fn compute_fk20_proofs<B: EcBackend>(
cell_size: usize,
poly: &[B::Fr],
n: usize,
fft_settings: &B::FFTSettings,
kzg_settings: &B::KZGSettings,
) -> Result<Vec<B::G1>, String> {
let k = n / cell_size;
let k2 = k * 2;
let mut coeffs = vec![vec![B::Fr::default(); k]; k2];
let mut toeplitz_coeffs = vec![B::Fr::default(); k2];
let mut toeplitz_coeffs_fft = vec![B::Fr::default(); k2];
for i in 0..cell_size {
toeplitz_coeffs_stride::<B>(&mut toeplitz_coeffs, poly, n, i, cell_size)?;
toeplitz_coeffs_fft.clone_from_slice(&fft_settings.fft_fr(&toeplitz_coeffs, false)?);
for j in 0..k2 {
coeffs[j][i] = toeplitz_coeffs_fft[j].clone();
}
}
let h_ext_fft = B::G1::g1_lincomb_batch(
kzg_settings.get_x_ext_fft_columns(),
&coeffs,
kzg_settings.get_precomputation(),
)?;
let mut h = fft_settings.fft_g1(&h_ext_fft, true)?;
cfg_iter_mut!(h)
.take(k2)
.skip(k)
.for_each(|h| *h = B::G1::identity());
fft_settings.fft_g1(&h, false)
}
fn compute_weighted_sum_of_commitments<B: EcBackend>(
commitments: &[B::G1],
commitment_indices: &[usize],
r_powers: &[B::Fr],
) -> B::G1 {
let mut commitment_weights = vec![B::Fr::zero(); commitments.len()];
#[cfg(feature = "parallel")]
{
let num_threads = rayon::current_num_threads();
let chunk_size = r_powers.len().div_ceil(num_threads);
let intermediate_weights: Vec<_> = r_powers
.par_chunks(chunk_size)
.zip(commitment_indices.par_chunks(chunk_size))
.map(|(r_chunk, idx_chunk)| {
let mut local_weights = vec![B::Fr::zero(); commitments.len()];
for (r_power, &index) in r_chunk.iter().zip(idx_chunk.iter()) {
local_weights[index] = local_weights[index].add(r_power);
}
local_weights
})
.collect();
for local_weights in intermediate_weights {
for (i, weight) in local_weights.into_iter().enumerate() {
commitment_weights[i] = commitment_weights[i].add(&weight);
}
}
}
#[cfg(not(feature = "parallel"))]
{
for i in 0..r_powers.len() {
commitment_weights[commitment_indices[i]] =
commitment_weights[commitment_indices[i]].add(&r_powers[i]);
}
}
B::G1::g1_lincomb(commitments, &commitment_weights, commitments.len(), None)
}
fn get_inv_coset_shift_for_cell<B: EcBackend>(
cell_size: usize,
cell_index: usize,
fft_settings: &B::FFTSettings,
field_elements_per_ext_blob: usize,
) -> Result<B::Fr, String> {
let cells_per_ext_blob = field_elements_per_ext_blob / cell_size;
/*
* Get the cell index in reverse-bit order.
* This index points to this cell's coset factor h_k in the roots_of_unity array.
*/
let cell_index_rbl = if cells_per_ext_blob == eth::CELLS_PER_EXT_BLOB {
CELL_INDICES_RBL[cell_index]
} else {
reverse_bits_limited(cells_per_ext_blob, cell_index)
};
/*
* Observe that for every element in roots_of_unity, we can find its inverse by
* accessing its reflected element.
*
* For example, consider a multiplicative subgroup with eight elements:
* roots = {w^0, w^1, w^2, ... w^7, w^0}
* For a root of unity in roots[i], we can find its inverse in roots[-i].
*/
if cell_index_rbl > field_elements_per_ext_blob {
return Err("Invalid cell index".to_string());
}
let inv_coset_factor_idx = field_elements_per_ext_blob - cell_index_rbl;
/* Get h_k^{-1} using the index */
if inv_coset_factor_idx > field_elements_per_ext_blob {
return Err("Invalid cell index".to_string());
}
Ok(fft_settings.get_roots_of_unity_at(inv_coset_factor_idx))
}
fn compute_commitment_to_aggregated_interpolation_poly<B: EcBackend>(
cell_size: usize,
r_powers: &[B::Fr],
cell_indices: &[usize],
cells: &[B::Fr],
fft_settings: &B::FFTSettings,
g1_monomial: &[B::G1],
) -> Result<B::G1, String> {
let cells_per_ext_blob = g1_monomial.len() * 2 / cell_size;
let mut aggregated_column_cells = vec![B::Fr::zero(); cells_per_ext_blob * cell_size];
for (cell_index, column_index) in cell_indices.iter().enumerate() {
for fr_index in 0..cell_size {
let original_fr = cells[cell_index * cell_size + fr_index].clone();
let scaled_fr = original_fr.mul(&r_powers[cell_index]);
let array_index = column_index * cell_size + fr_index;
aggregated_column_cells[array_index] =
aggregated_column_cells[array_index].add(&scaled_fr);
}
}
let mut is_cell_used = vec![false; cells_per_ext_blob];
for cell_index in cell_indices {
is_cell_used[*cell_index] = true;
}
let mut aggregated_interpolation_poly = vec![B::Fr::zero(); cell_size];
for (i, is_cell_used) in is_cell_used.iter().enumerate() {
if !is_cell_used {
continue;
}
let index = i * cell_size;
reverse_bit_order(&mut aggregated_column_cells[index..(index + cell_size)])?;
let mut column_interpolation_poly =
fft_settings.fft_fr(&aggregated_column_cells[index..(index + cell_size)], true)?;
let inv_coset_factor =
get_inv_coset_shift_for_cell::<B>(cell_size, i, fft_settings, g1_monomial.len() * 2)?;
shift_poly::<B>(&mut column_interpolation_poly, &inv_coset_factor);
for k in 0..cell_size {
aggregated_interpolation_poly[k] =
aggregated_interpolation_poly[k].add(&column_interpolation_poly[k]);
}
}
// TODO: maybe pass precomputation here?
Ok(B::G1::g1_lincomb(
g1_monomial,
&aggregated_interpolation_poly,
cell_size,
None,
))
}
fn get_coset_shift_pow_for_cell<B: EcBackend>(
cell_size: usize,
cell_index: usize,
fft_settings: &B::FFTSettings,
field_elements_per_ext_blob: usize,
) -> Result<B::Fr, String> {
let cells_per_ext_blob = field_elements_per_ext_blob / cell_size;
/*
* Get the cell index in reverse-bit order.
* This index points to this cell's coset factor h_k in the roots_of_unity array.
*/
let cell_idx_rbl = if cells_per_ext_blob == eth::CELLS_PER_EXT_BLOB {
CELL_INDICES_RBL[cell_index]
} else {
reverse_bits_limited(cells_per_ext_blob, cell_index)
};
/*
* Get the index to h_k^n in the roots_of_unity array.
*
* Multiplying the index of h_k by n, effectively raises h_k to the n-th power,
* because advancing in the roots_of_unity array corresponds to increasing exponents.
*/
let h_k_pow_idx = cell_idx_rbl * cell_size;
if h_k_pow_idx > field_elements_per_ext_blob {
return Err("Invalid cell index".to_string());
}
/* Get h_k^n using the index */
Ok(fft_settings.get_roots_of_unity_at(h_k_pow_idx))
}
fn computed_weighted_sum_of_proofs<B: EcBackend>(
cell_size: usize,
proofs: &[B::G1],
r_powers: &[B::Fr],
cell_indices: &[usize],
fft_settings: &B::FFTSettings,
field_elements_per_ext_blob: usize,
) -> Result<B::G1, String> {
let num_cells = proofs.len();
if r_powers.len() != num_cells || cell_indices.len() != num_cells {
return Err("Length mismatch".to_string());
}
let mut weighted_powers_of_r = Vec::with_capacity(num_cells);
for i in 0..num_cells {
let h_k_pow = get_coset_shift_pow_for_cell::<B>(
cell_size,
cell_indices[i],
fft_settings,
field_elements_per_ext_blob,
)?;
weighted_powers_of_r.push(r_powers[i].mul(&h_k_pow));
}
Ok(B::G1::g1_lincomb(
proofs,
&weighted_powers_of_r,
num_cells,
None,
))
}
/// This function is taken from rust-eth-kzg:
/// https://github.com/crate-crypto/rust-eth-kzg/blob/63d469ce1c98a9898a0d8cd717aa3ebe46ace227/cryptography/bls12_381/src/batch_inversion.rs#L4-L50
fn batch_inverse<B: EcBackend>(v: &mut [B::Fr]) {
let mut scratch_pad = Vec::with_capacity(v.len());
let mut tmp = B::Fr::one();
for f in v.iter() {
tmp = tmp.mul(f);
scratch_pad.push(tmp.clone());
}
tmp = tmp.inverse();
for (f, s) in v
.iter_mut()
.rev()
.zip(scratch_pad.iter().rev().skip(1).chain(Some(&B::Fr::one())))
{
let new_tmp = tmp.mul(f);
*f = tmp.mul(s);
tmp = new_tmp;
}
}
/*
* Automatically implement DAS for all backends
*/
impl<B: EcBackend> DAS<B> for B::KZGSettings {
fn kzg_settings(&self) -> &<B as EcBackend>::KZGSettings {
self
}
}
| 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.