diff --git a/Cargo.toml b/Cargo.toml index c73568a..326a3f0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -31,6 +31,7 @@ byteorder = "1.4" ark-poly = {version = "0.4.2", features = ["parallel"]} crossbeam-channel = "0.5" num_cpus = "1.13.0" +sys-info = "0.9" [dev-dependencies] criterion = "0.5" @@ -74,6 +75,11 @@ name = "bench_kzg_commit_large_blobs" harness = false path = "benches/bench_kzg_commit_large_blobs.rs" +[[bench]] +name = "bench_kzg_ifft_cache" +harness = false +path = "benches/bench_kzg_ifft_cache.rs" + [[bench]] name = "bench_kzg_proof" harness = false diff --git a/benches/bench_g1_ifft.rs b/benches/bench_g1_ifft.rs index b475dee..029a8b8 100644 --- a/benches/bench_g1_ifft.rs +++ b/benches/bench_g1_ifft.rs @@ -22,6 +22,7 @@ fn bench_g1_ifft(c: &mut Criterion) { "tests/test-files/mainnet-data/g2.point.powerOf2", 3000, 3000, + "".to_owned(), ) .unwrap(); b.iter(|| { diff --git a/benches/bench_kzg_commit.rs b/benches/bench_kzg_commit.rs index bcdabb2..9f67435 100644 --- a/benches/bench_kzg_commit.rs +++ b/benches/bench_kzg_commit.rs @@ -11,6 +11,7 @@ fn bench_kzg_commit(c: &mut Criterion) { "tests/test-files/mainnet-data/g2.point.powerOf2", 268435456, 131072, + "".to_owned(), ) .unwrap(); diff --git a/benches/bench_kzg_commit_large_blobs.rs b/benches/bench_kzg_commit_large_blobs.rs index 2bc143a..0f7dce5 100644 --- a/benches/bench_kzg_commit_large_blobs.rs +++ b/benches/bench_kzg_commit_large_blobs.rs @@ -11,6 +11,7 @@ fn bench_kzg_commit(c: &mut Criterion) { "tests/test-files/mainnet-data/g2.point.powerOf2", 268435456, 524288, + "".to_owned(), ) .unwrap(); diff --git a/benches/bench_kzg_ifft_cache.rs b/benches/bench_kzg_ifft_cache.rs new file mode 100644 index 0000000..27c6fdc --- /dev/null +++ b/benches/bench_kzg_ifft_cache.rs @@ -0,0 +1,33 @@ +use criterion::{criterion_group, criterion_main, Criterion}; +use rust_kzg_bn254::kzg::Kzg; +use std::time::Duration; + +fn bench_kzg_ifft_cache(c: &mut Criterion) { + let kzg = Kzg::setup( + "tests/test-files/mainnet-data/g1.32mb.point", + "", + "tests/test-files/mainnet-data/g2.point.powerOf2", + 268435456, + 524288, + "/tmp".to_owned(), + ) + .unwrap(); + + c.bench_function("bench_kzg_ifft_cache", |b| { + b.iter(|| kzg.initialize_cache(true).unwrap()); + }); +} + +fn criterion_config() -> Criterion { + Criterion::default() + .warm_up_time(Duration::from_secs(5)) // Warm-up time + .measurement_time(Duration::from_secs(70)) // Measurement time + .sample_size(10) // Number of samples to take +} + +criterion_group!( + name = benches; + config = criterion_config(); + targets = bench_kzg_ifft_cache +); +criterion_main!(benches); diff --git a/benches/bench_kzg_proof.rs b/benches/bench_kzg_proof.rs index f9d356c..a02bf80 100644 --- a/benches/bench_kzg_proof.rs +++ b/benches/bench_kzg_proof.rs @@ -11,6 +11,7 @@ fn bench_kzg_proof(c: &mut Criterion) { "tests/test-files/mainnet-data/g2.point.powerOf2", 268435456, 131072, + "".to_owned(), ) .unwrap(); diff --git a/benches/bench_kzg_setup.rs b/benches/bench_kzg_setup.rs index 29f5f91..b5d9f4a 100644 --- a/benches/bench_kzg_setup.rs +++ b/benches/bench_kzg_setup.rs @@ -11,6 +11,7 @@ fn bench_kzg_setup(c: &mut Criterion) { "tests/test-files/g2.point.powerOf2", 3000, 3000, + "".to_owned(), ) .unwrap() }); @@ -22,6 +23,7 @@ fn bench_kzg_setup(c: &mut Criterion) { "tests/test-files/mainnet-data/g2.point.powerOf2", 268435456, 131072, + "".to_owned(), ) .unwrap() }); diff --git a/benches/bench_kzg_verify.rs b/benches/bench_kzg_verify.rs index 1e5b1fc..be8b4d8 100644 --- a/benches/bench_kzg_verify.rs +++ b/benches/bench_kzg_verify.rs @@ -11,6 +11,7 @@ fn bench_kzg_verify(c: &mut Criterion) { "tests/test-files/mainnet-data/g2.point.powerOf2", 268435456, 131072, + "".to_owned(), ) .unwrap(); diff --git a/src/consts.rs b/src/consts.rs index ac2793f..ea3a542 100644 --- a/src/consts.rs +++ b/src/consts.rs @@ -1,3 +1,4 @@ pub const BYTES_PER_FIELD_ELEMENT: usize = 32; pub const SIZE_OF_G1_AFFINE_COMPRESSED: usize = 32; // in bytes pub const SIZE_OF_G2_AFFINE_COMPRESSED: usize = 64; // in bytes +pub const REQUIRED_FREE_SPACE: u64 = 100 * 1024 * 1024; // 100 MB in bytes diff --git a/src/helpers.rs b/src/helpers.rs index d5db66d..dcb59c4 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -1,13 +1,22 @@ use ark_bn254::{Fq, Fq2, Fr, G1Affine, G1Projective, G2Affine, G2Projective}; use ark_ec::AffineRepr; use ark_ff::{sbb, BigInt, BigInteger, Field, LegendreSymbol, PrimeField}; +use ark_serialize::Write; use ark_std::{str::FromStr, vec::Vec, One, Zero}; use crossbeam_channel::Receiver; -use std::cmp; +use std::{ + cmp, + fs::{self, OpenOptions}, + path::Path, +}; +use sys_info::disk_info; use crate::{ arith, - consts::{BYTES_PER_FIELD_ELEMENT, SIZE_OF_G1_AFFINE_COMPRESSED, SIZE_OF_G2_AFFINE_COMPRESSED}, + consts::{ + BYTES_PER_FIELD_ELEMENT, REQUIRED_FREE_SPACE, SIZE_OF_G1_AFFINE_COMPRESSED, + SIZE_OF_G2_AFFINE_COMPRESSED, + }, traits::ReadPointFromBytes, }; @@ -297,16 +306,21 @@ pub fn read_g1_point_from_bytes_be(g1_bytes_be: &[u8]) -> Result Ok(point) } -pub fn process_chunks(receiver: Receiver<(Vec, usize)>) -> Vec<(T, usize)> +pub fn process_chunks(receiver: Receiver<(Vec, usize, bool)>) -> Vec<(T, usize)> where T: ReadPointFromBytes, { #[allow(clippy::unnecessary_filter_map)] receiver .iter() - .map(|(chunk, position)| { - let point = - T::read_point_from_bytes_be(&chunk).expect("Failed to read point from bytes"); + .map(|(chunk, position, is_native)| { + let point: T = if is_native { + T::read_point_from_bytes_native_compressed(&chunk) + .expect("Failed to read point from bytes") + } else { + T::read_point_from_bytes_be(&chunk).expect("Failed to read point from bytes") + }; + (point, position) }) .collect() @@ -362,3 +376,43 @@ pub fn is_on_curve_g2(g2: &G2Projective) -> bool { right += &tmp; left == right } + +pub fn check_directory + std::fmt::Display>(path: P) -> Result { + let test_file_path = path.as_ref().join("cache_dir_write_test.tmp"); + + // Try to create and write to a temporary file + let result = OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .open(&test_file_path) + .and_then(|mut file| file.write_all(b"test")); + + // Clean up the test file + let _ = fs::remove_file(test_file_path); + + // Return true if writing was successful, otherwise false + if result.is_err() { + return Err(format!( + "directory {} unable to be modified by kzg program", + path + )); + } + + // Get disk information + let disk = match disk_info() { + Ok(info) => info, + Err(_) => return Err(format!("unable to get disk information for path {}", path)), + }; + + // Calculate available space in the directory's disk + let free_space = disk.free * 1024; // Convert from KB to bytes + + if free_space < REQUIRED_FREE_SPACE { + return Err(format!( + "the cache path {} does not have {} space on disk", + path, REQUIRED_FREE_SPACE + )); + } + Ok(true) +} diff --git a/src/kzg.rs b/src/kzg.rs index ab0c138..a6b32dc 100644 --- a/src/kzg.rs +++ b/src/kzg.rs @@ -2,19 +2,23 @@ use crate::{ blob::Blob, consts::BYTES_PER_FIELD_ELEMENT, errors::KzgError, - helpers, + helpers::{self, check_directory}, polynomial::{Polynomial, PolynomialFormat}, traits::ReadPointFromBytes, }; use ark_bn254::{g1::G1Affine, Bn254, Fr, G1Projective, G2Affine}; use ark_ec::{pairing::Pairing, AffineRepr, CurveGroup, VariableBaseMSM}; use ark_poly::{EvaluationDomain, GeneralEvaluationDomain}; -use ark_serialize::Read; +use ark_serialize::CanonicalSerialize; +use ark_serialize::{Read, Write}; use ark_std::{ops::Div, str::FromStr, One, Zero}; use crossbeam_channel::{bounded, Sender}; use num_traits::ToPrimitive; use rayon::iter::{IntoParallelRefIterator, ParallelIterator}; -use std::{fs::File, io, io::BufReader}; +use std::{ + fs::{self, File}, + io::{self, BufReader}, +}; #[derive(Debug, PartialEq, Clone)] pub struct Kzg { @@ -23,6 +27,7 @@ pub struct Kzg { params: Params, srs_order: u64, expanded_roots_of_unity: Vec, + cache_dir: String, } #[derive(Debug, PartialEq, Clone)] @@ -40,6 +45,7 @@ impl Kzg { g2_power_of2_path: &str, srs_order: u32, srs_points_to_load: u32, + cache_dir: String, ) -> Result { if srs_points_to_load > srs_order { return Err(KzgError::GenericError( @@ -47,16 +53,25 @@ impl Kzg { )); } + if !cache_dir.is_empty() { + match check_directory(&cache_dir) { + Ok(info) => info, + Err(err) => return Err(KzgError::GenericError(err)), + }; + } + let g1_points = - Self::parallel_read_g1_points(path_to_g1_points.to_owned(), srs_points_to_load) + Self::parallel_read_g1_points(path_to_g1_points.to_owned(), srs_points_to_load, false) .map_err(|e| KzgError::SerializationError(e.to_string()))?; let g2_points_result: Result, KzgError> = match (path_to_g2_points.is_empty(), g2_power_of2_path.is_empty()) { - (false, _) => { - Self::parallel_read_g2_points(path_to_g2_points.to_owned(), srs_points_to_load) - .map_err(|e| KzgError::SerializationError(e.to_string())) - }, + (false, _) => Self::parallel_read_g2_points( + path_to_g2_points.to_owned(), + srs_points_to_load, + false, + ) + .map_err(|e| KzgError::SerializationError(e.to_string())), (_, false) => Self::read_g2_point_on_power_of_2(g2_power_of2_path), (true, true) => { return Err(KzgError::GenericError( @@ -78,6 +93,7 @@ impl Kzg { }, srs_order: srs_order.into(), expanded_roots_of_unity: vec![], + cache_dir, }) } @@ -268,9 +284,10 @@ impl Kzg { /// read files in chunks with specified length fn read_file_chunks( file_path: &str, - sender: Sender<(Vec, usize)>, + sender: Sender<(Vec, usize, bool)>, point_size: usize, num_points: u32, + is_native: bool, ) -> io::Result<()> { let file = File::open(file_path)?; let mut reader = BufReader::new(file); @@ -283,7 +300,7 @@ impl Kzg { break; } sender - .send((buffer[..bytes_read].to_vec(), position)) + .send((buffer[..bytes_read].to_vec(), position, is_native)) .unwrap(); position += bytes_read; buffer.resize(point_size, 0); // Ensure the buffer is always the correct size @@ -299,13 +316,14 @@ impl Kzg { pub fn parallel_read_g2_points( file_path: String, srs_points_to_load: u32, + is_native: bool, ) -> Result, KzgError> { - let (sender, receiver) = bounded::<(Vec, usize)>(1000); + let (sender, receiver) = bounded::<(Vec, usize, bool)>(1000); // Spawning the reader thread let reader_thread = std::thread::spawn( move || -> Result<(), Box> { - Self::read_file_chunks(&file_path, sender, 64, srs_points_to_load) + Self::read_file_chunks(&file_path, sender, 64, srs_points_to_load, is_native) .map_err(|e| -> Box { Box::new(e) }) }, ); @@ -340,17 +358,64 @@ impl Kzg { Ok(all_points.iter().map(|(point, _)| *point).collect()) } + pub fn parallel_read_g1_points_native( + file_path: String, + srs_points_to_load: u32, + is_native: bool, + ) -> Result, KzgError> { + let (sender, receiver) = bounded::<(Vec, usize, bool)>(1000); + + // Spawning the reader thread + let reader_thread = std::thread::spawn( + move || -> Result<(), Box> { + Self::read_file_chunks(&file_path, sender, 32, srs_points_to_load, is_native) + .map_err(|e| -> Box { Box::new(e) }) + }, + ); + + let num_workers = num_cpus::get(); + + let workers: Vec<_> = (0..num_workers) + .map(|_| { + let receiver = receiver.clone(); + std::thread::spawn(move || helpers::process_chunks::(receiver)) + }) + .collect(); + + // Wait for the reader thread to finish + match reader_thread.join() { + Ok(result) => match result { + Ok(_) => {}, + Err(e) => return Err(KzgError::GenericError(e.to_string())), + }, + Err(_) => return Err(KzgError::GenericError("Thread panicked".to_string())), + } + + // Collect and sort results + let mut all_points = Vec::new(); + for worker in workers { + let points = worker.join().expect("Worker thread panicked"); + all_points.extend(points); + } + + // Sort by original position to maintain order + all_points.sort_by_key(|&(_, position)| position); + + Ok(all_points.iter().map(|(point, _)| *point).collect()) + } + /// read G1 points in parallel pub fn parallel_read_g1_points( file_path: String, srs_points_to_load: u32, + is_native: bool, ) -> Result, KzgError> { - let (sender, receiver) = bounded::<(Vec, usize)>(1000); + let (sender, receiver) = bounded::<(Vec, usize, bool)>(1000); // Spawning the reader thread let reader_thread = std::thread::spawn( move || -> Result<(), Box> { - Self::read_file_chunks(&file_path, sender, 32, srs_points_to_load) + Self::read_file_chunks(&file_path, sender, 32, srs_points_to_load, is_native) .map_err(|e| -> Box { Box::new(e) }) }, ); @@ -399,29 +464,21 @@ impl Kzg { )); } - // Configure multi-threading - let config = rayon::ThreadPoolBuilder::new() - .num_threads(num_cpus::get()) - .build() - .map_err(|err| KzgError::CommitError(err.to_string()))?; - - config.install(|| { - let bases = match polynomial.get_form() { - PolynomialFormat::InEvaluationForm => { - // If the polynomial is in evaluation form, use the original g1 points - self.g1[..polynomial.len()].to_vec() - }, - PolynomialFormat::InCoefficientForm => { - // If the polynomial is in coefficient form, use inverse FFT - self.g1_ifft(polynomial.len())? - }, - }; + let bases = match polynomial.get_form() { + PolynomialFormat::InEvaluationForm => { + // If the polynomial is in evaluation form, use the original g1 points + self.g1[..polynomial.len()].to_vec() + }, + PolynomialFormat::InCoefficientForm => { + // If the polynomial is in coefficient form, use inverse FFT + self.g1_ifft(polynomial.len())? + }, + }; - match G1Projective::msm(&bases, &polynomial.to_vec()) { - Ok(res) => Ok(res.into_affine()), - Err(err) => Err(KzgError::CommitError(err.to_string())), - } - }) + match G1Projective::msm(&bases, &polynomial.to_vec()) { + Ok(res) => Ok(res.into_affine()), + Err(err) => Err(KzgError::CommitError(err.to_string())), + } } pub fn blob_to_kzg_commitment( @@ -550,6 +607,46 @@ impl Kzg { quotient } + pub fn read_from_cache_if_exists(&self, length: usize) -> Vec { + // check if the cache_dir has the file with the length in it + let cache_file = format!("{}/2_pow_{}.cache", self.cache_dir, length); + + match Self::parallel_read_g1_points_native(cache_file, length as u32, true) { + Ok(points) => points, + Err(_) => Vec::new(), + } + } + + // computes the IFFT, deserialize it and store it in file format. + pub fn initialize_cache(&self, force: bool) -> Result<(), KzgError> { + // powers of 2 from 10 to 20 + for length in 10..20_usize { + let in_pow_2 = 2_u32.pow(length as u32); + let cache_file = format!("{}/2_pow_{}.cache", self.cache_dir, in_pow_2); + + if fs::metadata(&cache_file).is_ok() && force { + // Cache file already exists, delete it if force cache is set + fs::remove_file(&cache_file) + .map_err(|err| KzgError::GenericError(err.to_string()))?; + } + + let g1_ifft_points = self.g1_ifft(in_pow_2 as usize)?; + + let mut file = + File::create(&cache_file).map_err(|err| KzgError::GenericError(err.to_string()))?; + for point in g1_ifft_points { + let mut serialized_point = vec![]; + point + .serialize_compressed(&mut serialized_point) + .map_err(|err| KzgError::SerializationError(err.to_string()))?; + file.write_all(&serialized_point) + .map_err(|err| KzgError::SerializationError(err.to_string()))?; + } + } + + Ok(()) + } + /// function to compute the inverse FFT pub fn g1_ifft(&self, length: usize) -> Result, KzgError> { // is not power of 2 @@ -559,21 +656,26 @@ impl Kzg { )); } - let points_projective: Vec = self.g1[..length] - .par_iter() - .map(|&p| G1Projective::from(p)) - .collect(); - - match GeneralEvaluationDomain::::new(length) { - Some(domain) => { - let ifft_result = domain.ifft(&points_projective); - let ifft_result_affine: Vec<_> = - ifft_result.par_iter().map(|p| p.into_affine()).collect(); - Ok(ifft_result_affine) - }, - None => Err(KzgError::FftError( - "Could not perform IFFT due to domain consturction error".to_string(), - )), + let cached_points = self.read_from_cache_if_exists(length); + if cached_points.is_empty() { + let points_projective: Vec = self.g1[..length] + .par_iter() + .map(|&p| G1Projective::from(p)) + .collect(); + + match GeneralEvaluationDomain::::new(length) { + Some(domain) => { + let ifft_result = domain.ifft(&points_projective); + let ifft_result_affine: Vec<_> = + ifft_result.par_iter().map(|p| p.into_affine()).collect(); + Ok(ifft_result_affine) + }, + None => Err(KzgError::FftError( + "Could not perform IFFT due to domain consturction error".to_string(), + )), + } + } else { + Ok(cached_points) } } diff --git a/src/traits.rs b/src/traits.rs index db08545..6a7192b 100644 --- a/src/traits.rs +++ b/src/traits.rs @@ -1,10 +1,12 @@ use crate::helpers; use ark_bn254::{g1::G1Affine, g2::G2Affine}; use ark_ec::AffineRepr; +use ark_serialize::CanonicalDeserialize; use std::io; pub trait ReadPointFromBytes: AffineRepr { fn read_point_from_bytes_be(bytes: &[u8]) -> io::Result; + fn read_point_from_bytes_native_compressed(bytes: &[u8]) -> io::Result; } // Implement this trait for G1Affine and G2Affine @@ -13,6 +15,11 @@ impl ReadPointFromBytes for G1Affine { helpers::read_g1_point_from_bytes_be(bytes) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) } + + fn read_point_from_bytes_native_compressed(bytes: &[u8]) -> io::Result { + G1Affine::deserialize_compressed(bytes) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) + } } impl ReadPointFromBytes for G2Affine { @@ -20,4 +27,9 @@ impl ReadPointFromBytes for G2Affine { helpers::read_g2_point_from_bytes_be(bytes) .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) } + + fn read_point_from_bytes_native_compressed(bytes: &[u8]) -> io::Result { + G2Affine::deserialize_compressed(bytes) + .map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e)) + } } diff --git a/tests/kzg_test.rs b/tests/kzg_test.rs index 1b4d646..28d1539 100644 --- a/tests/kzg_test.rs +++ b/tests/kzg_test.rs @@ -2,6 +2,7 @@ mod tests { use ark_bn254::{Fr, G1Affine, G2Affine}; use lazy_static::lazy_static; + use rand::Rng; use rust_kzg_bn254::{ blob::Blob, errors::KzgError, @@ -11,8 +12,8 @@ mod tests { }; use std::{ env, - fs::File, - io::{BufRead, BufReader}, + fs::{self, File}, + io::{BufRead, BufReader}, path::{Path, PathBuf}, }; const GETTYSBURG_ADDRESS_BYTES: &[u8] = "Fourscore and seven years ago our fathers brought forth, on this continent, a new nation, conceived in liberty, and dedicated to the proposition that all men are created equal. Now we are engaged in a great civil war, testing whether that nation, or any nation so conceived, and so dedicated, can long endure. We are met on a great battle-field of that war. We have come to dedicate a portion of that field, as a final resting-place for those who here gave their lives, that that nation might live. It is altogether fitting and proper that we should do this. But, in a larger sense, we cannot dedicate, we cannot consecrate—we cannot hallow—this ground. The brave men, living and dead, who struggled here, have consecrated it far above our poor power to add or detract. The world will little note, nor long remember what we say here, but it can never forget what they did here. It is for us the living, rather, to be dedicated here to the unfinished work which they who fought here have thus far so nobly advanced. It is rather for us to be here dedicated to the great task remaining before us—that from these honored dead we take increased devotion to that cause for which they here gave the last full measure of devotion—that we here highly resolve that these dead shall not have died in vain—that this nation, under God, shall have a new birth of freedom, and that government of the people, by the people, for the people, shall not perish from the earth.".as_bytes(); use ark_std::{str::FromStr, One}; @@ -26,6 +27,7 @@ mod tests { "tests/test-files/mainnet-data/g2.point.powerOf2", 268435456, 131072, + "".to_owned() ) .unwrap(), _ => Kzg::setup( @@ -34,6 +36,7 @@ mod tests { "tests/test-files/g2.point.powerOf2", 3000, 3000, + "".to_owned() ) .unwrap(), } @@ -47,7 +50,8 @@ mod tests { "tests/test-files/g2.point", "tests/test-files/g2.point.powerOf2", 3000, - 3000 + 3000, + "".to_owned() ) .unwrap(); } @@ -71,7 +75,7 @@ mod tests { #[test] fn test_kzg_setup_errors() { - let kzg1 = Kzg::setup("tests/test-files/g1.point", "", "", 3000, 3000); + let kzg1 = Kzg::setup("tests/test-files/g1.point", "", "", 3000, 3000, "".to_owned()); assert_eq!( kzg1, Err(KzgError::GenericError( @@ -85,6 +89,7 @@ mod tests { "tests/test-files/g2.point.powerOf2", 2, 2, + "".to_owned() ) .unwrap(); @@ -103,6 +108,7 @@ mod tests { "tests/test-files/g2.point.powerOf2", 3000, 3001, + "".to_owned() ); assert_eq!( kzg3, @@ -124,6 +130,7 @@ mod tests { "tests/test-files/g2.point.powerOf2", 3000, 3000, + "".to_owned() ) .unwrap(); @@ -154,6 +161,54 @@ mod tests { } } + #[test] + fn test_cache_read_and_commitment() { + + let mut rng = rand::thread_rng(); + let cache_dir = "/tmp"; + let mut kzg = Kzg::setup( + "tests/test-files/mainnet-data/g1.32mb.point", + "", + "tests/test-files/mainnet-data/g2.point.powerOf2", + 268435456, + 524288, + cache_dir.to_owned() + ) + .unwrap(); + + let tmp_dir = Path::new("/tmp"); + + // Iterate over the files in the /tmp directory + for entry in fs::read_dir(tmp_dir).unwrap() { + let entry = entry.unwrap(); + let path: PathBuf = entry.path(); + + // Check if the entry is a file and ends with .cache + if path.is_file() && path.extension().and_then(|ext| ext.to_str()) == Some("cache") { + // Delete the file + fs::remove_file(&path).unwrap(); + } + } + + let random_blob: Vec = (0..8000000) + .map(|_| rng.gen_range(32..=126) as u8) + .collect(); + let input = Blob::from_bytes_and_pad(&random_blob); + let input_poly = input + .to_polynomial(PolynomialFormat::InCoefficientForm) + .unwrap(); + kzg.data_setup_custom(1, input.len().try_into().unwrap()) + .unwrap(); + + let commitment_raw_computed = kzg.commit(&input_poly); + + kzg.initialize_cache(false).unwrap(); + + let commitment_cache = kzg.commit(&input_poly); + + assert_eq!(commitment_raw_computed, commitment_cache); + } + #[test] fn test_roots_of_unity_setup() { use rand::Rng;