From 3a03a68c49b50e8cd4c405fe6def44a78ac31b25 Mon Sep 17 00:00:00 2001 From: afk <84330705+afkbyte@users.noreply.github.com> Date: Fri, 31 May 2024 19:40:26 -0400 Subject: [PATCH] Revert "Compatability changes to work with arb nitro" --- Cargo.toml | 4 +- benches/bench_kzg_commit.rs | 8 +-- benches/bench_kzg_proof.rs | 8 +-- benches/bench_kzg_verify.rs | 8 +-- rust-toolchain | 4 +- src/blob.rs | 34 ++-------- src/errors.rs | 6 -- src/helpers.rs | 45 +++++++------- src/kzg.rs | 74 ++++++++-------------- src/polynomial.rs | 74 +--------------------- tests/blob_test.rs | 24 +------- tests/error_tests.rs | 16 ----- tests/helpers_test.rs | 6 +- tests/kzg_test.rs | 33 +++------- tests/polynomial_test.rs | 120 ++---------------------------------- 15 files changed, 87 insertions(+), 377 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index e6b9cfc..1a41733 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -30,13 +30,11 @@ num-traits = "0.2" byteorder = "1.4" ark-poly = "0.4.2" crossbeam-channel = "0.5" -num_cpus = "1.13.0" +num_cpus = "^1.16.0" [dev-dependencies] criterion = "0.5" lazy_static = "1.4" -tracing = { version = "^0.1.34", features = ["log"] } -tracing-subscriber = "0.3.18" [[test]] name = "kzg" diff --git a/benches/bench_kzg_commit.rs b/benches/bench_kzg_commit.rs index 8061df6..d68a81d 100644 --- a/benches/bench_kzg_commit.rs +++ b/benches/bench_kzg_commit.rs @@ -1,6 +1,6 @@ use criterion::{criterion_group, criterion_main, Criterion}; use rand::Rng; -use rust_kzg_bn254::{blob::Blob, kzg::Kzg, polynomial::PolynomialFormat}; +use rust_kzg_bn254::{blob::Blob, kzg::Kzg}; use std::time::Duration; fn bench_kzg_commit(c: &mut Criterion) { @@ -17,7 +17,7 @@ fn bench_kzg_commit(c: &mut Criterion) { c.bench_function("bench_kzg_commit_10000", |b| { let random_blob: Vec = (0..10000).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(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); b.iter(|| kzg.commit(&input_poly).unwrap()); @@ -26,7 +26,7 @@ fn bench_kzg_commit(c: &mut Criterion) { c.bench_function("bench_kzg_commit_30000", |b| { let random_blob: Vec = (0..30000).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(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); b.iter(|| kzg.commit(&input_poly).unwrap()); @@ -35,7 +35,7 @@ fn bench_kzg_commit(c: &mut Criterion) { c.bench_function("bench_kzg_commit_50000", |b| { let random_blob: Vec = (0..50000).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(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); b.iter(|| kzg.commit(&input_poly).unwrap()); diff --git a/benches/bench_kzg_proof.rs b/benches/bench_kzg_proof.rs index 3bcd6b9..c2711f7 100644 --- a/benches/bench_kzg_proof.rs +++ b/benches/bench_kzg_proof.rs @@ -1,6 +1,6 @@ use criterion::{criterion_group, criterion_main, Criterion}; use rand::Rng; -use rust_kzg_bn254::{blob::Blob, kzg::Kzg, polynomial::PolynomialFormat}; +use rust_kzg_bn254::{blob::Blob, kzg::Kzg}; use std::time::Duration; fn bench_kzg_proof(c: &mut Criterion) { @@ -17,7 +17,7 @@ fn bench_kzg_proof(c: &mut Criterion) { c.bench_function("bench_kzg_proof_10000", |b| { let random_blob: Vec = (0..10000).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(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); let index = @@ -31,7 +31,7 @@ fn bench_kzg_proof(c: &mut Criterion) { c.bench_function("bench_kzg_proof_30000", |b| { let random_blob: Vec = (0..30000).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(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); let index = @@ -45,7 +45,7 @@ fn bench_kzg_proof(c: &mut Criterion) { c.bench_function("bench_kzg_proof_50000", |b| { let random_blob: Vec = (0..50000).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(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); let index = diff --git a/benches/bench_kzg_verify.rs b/benches/bench_kzg_verify.rs index 8c22b8b..9c089e2 100644 --- a/benches/bench_kzg_verify.rs +++ b/benches/bench_kzg_verify.rs @@ -1,6 +1,6 @@ use criterion::{criterion_group, criterion_main, Criterion}; use rand::Rng; -use rust_kzg_bn254::{blob::Blob, kzg::Kzg, polynomial::PolynomialFormat}; +use rust_kzg_bn254::{blob::Blob, kzg::Kzg}; use std::time::Duration; fn bench_kzg_verify(c: &mut Criterion) { @@ -17,7 +17,7 @@ fn bench_kzg_verify(c: &mut Criterion) { c.bench_function("bench_kzg_verify_10000", |b| { let random_blob: Vec = (0..10000).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(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); let index = @@ -34,7 +34,7 @@ fn bench_kzg_verify(c: &mut Criterion) { c.bench_function("bench_kzg_verify_30000", |b| { let random_blob: Vec = (0..30000).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(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); let index = @@ -51,7 +51,7 @@ fn bench_kzg_verify(c: &mut Criterion) { c.bench_function("bench_kzg_verify_50000", |b| { let random_blob: Vec = (0..50000).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(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); let index = diff --git a/rust-toolchain b/rust-toolchain index 4f3b032..8beb4a0 100644 --- a/rust-toolchain +++ b/rust-toolchain @@ -1,5 +1,5 @@ [toolchain] -channel = '1.74' +channel = 'nightly-2024-04-29' profile = 'minimal' components = ['clippy', 'rustfmt'] -targets = ["x86_64-unknown-linux-gnu", "x86_64-pc-windows-gnu", "wasm32-unknown-unknown", "aarch64-apple-darwin"] +targets = ["x86_64-unknown-linux-gnu", "x86_64-pc-windows-gnu", "wasm32-unknown-unknown"] diff --git a/src/blob.rs b/src/blob.rs index 4cca1ae..7820482 100644 --- a/src/blob.rs +++ b/src/blob.rs @@ -1,8 +1,4 @@ -use crate::{ - errors::BlobError, - helpers, - polynomial::{Polynomial, PolynomialFormat}, -}; +use crate::{errors::BlobError, helpers, polynomial::Polynomial}; /// A blob which is Eigen DA spec aligned. #[derive(Clone, Debug, PartialEq, Eq)] @@ -43,22 +39,6 @@ impl Blob { } } - /// Creates a new `Blob` from the provided byte slice and assumes it's - /// already padded according to DA specs. - /// WARNING: This function does not check if the bytes are modulo bn254 - /// if the data has 32 byte segments exceeding the modulo of the field - /// then the bytes will be modded by the order of the field and the data - /// will be transformed incorrectly - pub fn from_padded_bytes_unchecked(input: &[u8]) -> Self { - let length_after_padding = input.len(); - - Blob { - blob_data: input.to_vec(), - is_padded: true, - length_after_padding, - } - } - /// Returns the blob data pub fn get_blob_data(&self) -> Vec { self.blob_data.clone() @@ -69,11 +49,6 @@ impl Blob { self.blob_data.len() } - /// Checks if the blob data is empty. - pub fn is_empty(&self) -> bool { - self.blob_data.is_empty() - } - /// Pads the blob data in-place if it is not already padded. pub fn pad_data(&mut self) -> Result<(), BlobError> { if self.is_padded { @@ -91,8 +66,7 @@ impl Blob { if !self.is_padded { Err(BlobError::NotPaddedError) } else { - self.blob_data = - helpers::remove_empty_byte_from_padded_bytes_unchecked(&self.blob_data); + self.blob_data = helpers::remove_empty_byte_from_padded_bytes(&self.blob_data); self.is_padded = false; self.length_after_padding = 0; Ok(()) @@ -100,12 +74,12 @@ impl Blob { } /// Converts the blob data to a `Polynomial` if the data is padded. - pub fn to_polynomial(&self, form: PolynomialFormat) -> Result { + pub fn to_polynomial(&self) -> Result { if !self.is_padded { Err(BlobError::NotPaddedError) } else { let fr_vec = helpers::to_fr_array(&self.blob_data); - let poly = Polynomial::new(&fr_vec, self.length_after_padding, form) + let poly = Polynomial::new(&fr_vec, self.length_after_padding) .map_err(|err| BlobError::GenericError(err.to_string()))?; Ok(poly) } diff --git a/src/errors.rs b/src/errors.rs index ad85059..c5b5509 100644 --- a/src/errors.rs +++ b/src/errors.rs @@ -24,8 +24,6 @@ pub enum PolynomialError { SerializationFromStringError, CommitError(String), GenericError(String), - FFTError(String), - IncorrectFormError(String), } impl fmt::Display for PolynomialError { @@ -35,11 +33,7 @@ impl fmt::Display for PolynomialError { write!(f, "couldn't load string to fr vector") }, PolynomialError::CommitError(ref msg) => write!(f, "Commitment error: {}", msg), - PolynomialError::FFTError(ref msg) => write!(f, "FFT error: {}", msg), PolynomialError::GenericError(ref msg) => write!(f, "generic error: {}", msg), - PolynomialError::IncorrectFormError(ref msg) => { - write!(f, "Incorrect form error: {}", msg) - }, } } } diff --git a/src/helpers.rs b/src/helpers.rs index 518d456..9942668 100644 --- a/src/helpers.rs +++ b/src/helpers.rs @@ -11,7 +11,7 @@ use crate::{ traits::ReadPointFromBytes, }; -pub fn blob_to_polynomial(blob: &[u8]) -> Vec { +pub fn blob_to_polynomial(blob: &Vec) -> Vec { to_fr_array(blob) } @@ -55,7 +55,7 @@ pub fn convert_by_padding_empty_byte(data: &[u8]) -> Vec { valid_data } -pub fn remove_empty_byte_from_padded_bytes_unchecked(data: &[u8]) -> Vec { +pub fn remove_empty_byte_from_padded_bytes(data: &[u8]) -> Vec { let data_size = data.len(); let parse_size = BYTES_PER_FIELD_ELEMENT; let data_len = (data_size + parse_size - 1) / parse_size; @@ -94,15 +94,15 @@ pub fn to_fr_array(data: &[u8]) -> Vec { let num_ele = get_num_element(data.len(), BYTES_PER_FIELD_ELEMENT); let mut eles = vec![Fr::zero(); num_ele]; // Initialize with zero elements - for (i, element) in eles.iter_mut().enumerate().take(num_ele) { + for i in 0..num_ele { let start = i * BYTES_PER_FIELD_ELEMENT; let end = (i + 1) * BYTES_PER_FIELD_ELEMENT; if end > data.len() { let mut padded = vec![0u8; BYTES_PER_FIELD_ELEMENT]; padded[..data.len() - start].copy_from_slice(&data[start..]); - *element = set_bytes_canonical(&padded); + eles[i] = set_bytes_canonical(&padded); } else { - *element = set_bytes_canonical(&data[start..end]); + eles[i] = set_bytes_canonical(&data[start..end]); } } eles @@ -113,8 +113,8 @@ pub fn to_byte_array(data_fr: &[Fr], max_data_size: usize) -> Vec { let data_size = cmp::min(n * BYTES_PER_FIELD_ELEMENT, max_data_size); let mut data = vec![0u8; data_size]; - for (i, element) in data_fr.iter().enumerate().take(n) { - let v: Vec = element.into_bigint().to_bytes_be(); + for i in 0..n { + let v: Vec = data_fr[i].into_bigint().to_bytes_be(); let start = i * BYTES_PER_FIELD_ELEMENT; let end = (i + 1) * BYTES_PER_FIELD_ELEMENT; @@ -136,8 +136,8 @@ pub fn is_zeroed(first_byte: u8, buf: Vec) -> bool { return false; } - for byte in &buf { - if *byte != 0 { + for i in 0..buf.len() { + if buf[i] != 0 { return false; } } @@ -147,13 +147,13 @@ pub fn is_zeroed(first_byte: u8, buf: Vec) -> bool { pub fn str_vec_to_fr_vec(input: Vec<&str>) -> Result, &str> { let mut output: Vec = Vec::::with_capacity(input.len()); - for element in &input { - if *element == "-1" { + for i in 0..input.len() { + if input[i] == "-1" { let mut test = Fr::one(); test.neg_in_place(); output.push(test); } else { - let fr_data = Fr::from_str(element).expect("could not load string to Fr"); + let fr_data = Fr::from_str(input[i]).expect("could not load string to Fr"); output.push(fr_data); } } @@ -232,11 +232,13 @@ pub fn read_g2_point_from_bytes_be(g2_bytes_be: &Vec) -> Result Some((point, position)), + Err(err) => panic!("{}", err), + }, + ) .collect() } diff --git a/src/kzg.rs b/src/kzg.rs index f862dcd..52c77fb 100644 --- a/src/kzg.rs +++ b/src/kzg.rs @@ -1,16 +1,16 @@ use crate::{ - blob::Blob, - consts::BYTES_PER_FIELD_ELEMENT, - errors::KzgError, - helpers, - polynomial::{Polynomial, PolynomialFormat}, + blob::Blob, consts::BYTES_PER_FIELD_ELEMENT, errors::KzgError, helpers, polynomial::Polynomial, 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_std::{ops::Div, str::FromStr, One, Zero}; +use ark_std::{ + ops::{Div, Mul}, + str::FromStr, + One, Zero, +}; use crossbeam_channel::{bounded, Sender}; use num_traits::ToPrimitive; use std::{fs::File, io, io::BufReader}; @@ -49,8 +49,7 @@ impl Kzg { let g1_points = Self::parallel_read_g1_points(path_to_g1_points.to_owned(), srs_points_to_load) .map_err(|e| KzgError::SerializationError(e.to_string()))?; - - let g2_points: Vec; + let mut g2_points: Vec = vec![]; if !path_to_g2_points.is_empty() { g2_points = Self::parallel_read_g2_points(path_to_g2_points.to_owned(), srs_points_to_load) @@ -401,18 +400,9 @@ impl Kzg { .build() .map_err(|err| KzgError::CommitError(err.to_string()))?; + // Perform the multi-exponentiation 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 = self.g1_ifft(polynomial.len()).unwrap(); match G1Projective::msm(&bases, &polynomial.to_vec()) { Ok(res) => Ok(res.into_affine()), Err(err) => Err(KzgError::CommitError(err.to_string())), @@ -420,13 +410,10 @@ impl Kzg { }) } - pub fn blob_to_kzg_commitment( - &self, - blob: &Blob, - form: PolynomialFormat, - ) -> Result { + /// 4844 compatible helper function + pub fn blob_to_kzg_commitment(&self, blob: &Blob) -> Result { let polynomial = blob - .to_polynomial(form) + .to_polynomial() .map_err(|err| KzgError::SerializationError(err.to_string()))?; let commitment = self.commit(&polynomial)?; Ok(commitment) @@ -473,13 +460,13 @@ impl Kzg { let value_fr = eval_fr[usized_index]; let z_fr = root_of_unities[usized_index]; - for fr in &eval_fr { - poly_shift.push(*fr - value_fr); + for i in 0..eval_fr.len() { + poly_shift.push(eval_fr[i] - value_fr); } let mut denom_poly = Vec::::with_capacity(root_of_unities.len()); - for root_of_unity in root_of_unities.iter().take(eval_fr.len()) { - denom_poly.push(*root_of_unity - z_fr); + for i in 0..eval_fr.len() { + denom_poly.push(root_of_unities[i] - z_fr); } let mut quotient_poly = Vec::::with_capacity(root_of_unities.len()); @@ -497,18 +484,9 @@ impl Kzg { } } - 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 g1_lagrange = self.g1_ifft(polynomial.len())?; - match G1Projective::msm(&bases, "ient_poly) { + match G1Projective::msm(&g1_lagrange, "ient_poly) { Ok(res) => Ok(G1Affine::from(res)), Err(err) => Err(KzgError::SerializationError(err.to_string())), } @@ -518,15 +496,15 @@ impl Kzg { pub fn compute_quotient_eval_on_domain( &self, z_fr: Fr, - eval_fr: &[Fr], + eval_fr: &Vec, value_fr: Fr, roots_of_unities: &Vec, ) -> Fr { let mut quotient = Fr::zero(); - let mut fi: Fr; - let mut numerator: Fr; - let mut denominator: Fr; - let mut temp: Fr; + let mut fi = Fr::zero(); + let mut numerator: Fr = Fr::zero(); + let mut denominator: Fr = Fr::zero(); + let mut temp: Fr = Fr::zero(); for i in 0..roots_of_unities.len() { let omega_i = roots_of_unities[i]; @@ -534,7 +512,7 @@ impl Kzg { continue; } fi = eval_fr[i] - value_fr; - numerator = fi * omega_i; + numerator = fi.mul(omega_i); denominator = z_fr - omega_i; denominator *= z_fr; temp = numerator.div(denominator); @@ -560,14 +538,14 @@ impl Kzg { match GeneralEvaluationDomain::::new(length) { Some(domain) => { let ifft_result = domain.ifft(&points_projective); - let ifft_result_affine: Vec<_> = - ifft_result.iter().map(|p| p.into_affine()).collect(); + let ifft_result_affine: Vec<_> = ifft_result.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(), )), } + } pub fn verify_kzg_proof( diff --git a/src/polynomial.rs b/src/polynomial.rs index 911bffb..1b63b02 100644 --- a/src/polynomial.rs +++ b/src/polynomial.rs @@ -1,29 +1,17 @@ use crate::{errors::PolynomialError, helpers}; use ark_bn254::Fr; -use ark_poly::{EvaluationDomain, GeneralEvaluationDomain}; use ark_std::Zero; -#[derive(Clone, Debug, PartialEq, Copy)] -pub enum PolynomialFormat { - InCoefficientForm, - InEvaluationForm, -} - #[derive(Clone, Debug, PartialEq)] pub struct Polynomial { elements: Vec, length_of_padded_blob: usize, length_of_padded_blob_as_fr_vector: usize, - form: PolynomialFormat, } impl Polynomial { /// Constructs a new `Polynomial` with a given vector of `Fr` elements. - pub fn new( - elements: &Vec, - length_of_padded_blob: usize, - form: PolynomialFormat, - ) -> Result { + pub fn new(elements: &Vec, length_of_padded_blob: usize) -> Result { if elements.is_empty() { return Err(PolynomialError::GenericError( "elements are empty".to_string(), @@ -41,7 +29,6 @@ impl Polynomial { elements: padded_input_fr, length_of_padded_blob, length_of_padded_blob_as_fr_vector: elements.len(), - form, }) } @@ -49,11 +36,6 @@ impl Polynomial { self.length_of_padded_blob_as_fr_vector } - /// Returns the form of the polynomial. - pub fn get_form(&self) -> PolynomialFormat { - self.form - } - /// Returns the number of elements in the polynomial. pub fn len(&self) -> usize { self.elements.len() @@ -77,58 +59,4 @@ impl Polynomial { pub fn to_vec(&self) -> Vec { self.elements.clone() } - - /// Helper function to transform the polynomial to the given form. - pub fn transform_to_form(&mut self, form: PolynomialFormat) -> Result<(), PolynomialError> { - if self.form == form { - return Err(PolynomialError::IncorrectFormError( - "Polynomial is already in the given form".to_string(), - )); - } - - match form { - PolynomialFormat::InCoefficientForm => { - // Transform from evaluation form to coefficient form using FFT - self.form = form; - self.fft_on_elements(false) - }, - PolynomialFormat::InEvaluationForm => { - // Transform from coefficient form to evaluation form using IFFT - self.form = form; - self.fft_on_elements(true) - }, - } - } - - /// Performs an fft or ifft on the polynomial's elements - pub fn fft_on_elements(&mut self, inverse: bool) -> Result<(), PolynomialError> { - let fft_result = Self::fft(&self.to_vec(), inverse); - match fft_result { - Ok(fft_result) => { - self.elements = fft_result; - Ok(()) - }, - Err(e) => Err(e), - } - } - - /// helper function to perform fft or ifft on a vector of Fr - pub fn fft(vals: &Vec, inverse: bool) -> Result, PolynomialError> { - let length = vals.len(); - - match GeneralEvaluationDomain::::new(length) { - Some(domain) => { - if inverse { - let result = domain.ifft(vals); - Ok(result) - } else { - let result = domain.fft(vals); - Ok(result) - } - }, - None => Err(PolynomialError::FFTError( - "Failed to construct domain for FFT".to_string(), - )), - } - } } diff --git a/tests/blob_test.rs b/tests/blob_test.rs index 548eda1..0a54430 100644 --- a/tests/blob_test.rs +++ b/tests/blob_test.rs @@ -1,6 +1,6 @@ #[cfg(test)] mod tests { - use rust_kzg_bn254::{blob::Blob, errors::BlobError, polynomial::PolynomialFormat}; + use rust_kzg_bn254::{blob::Blob, errors::BlobError}; 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(); #[test] @@ -11,27 +11,7 @@ mod tests { blob.remove_padding().unwrap(); result = blob.remove_padding(); assert_eq!(result, Err(BlobError::NotPaddedError)); - assert_eq!( - blob.to_polynomial(PolynomialFormat::InCoefficientForm), - Err(BlobError::NotPaddedError) - ); - } - - #[test] - fn test_is_empty() { - let mut blob_empty = Blob::from_bytes_and_pad("".as_bytes()); - assert!(blob_empty.is_empty(), "blob should be empty"); - - let mut blob = Blob::from_bytes_and_pad("hi".as_bytes()); - assert!(!blob.is_empty(), "blob should not be empty"); - } - - #[test] - fn test_from_padded_bytes_unchecked() { - let mut blob = Blob::from_bytes_and_pad("hi".as_bytes()); - let mut blob_unchecked = Blob::from_padded_bytes_unchecked(blob.get_blob_data().as_slice()); - - assert_eq!(blob, blob_unchecked, "blob should be equal"); + assert_eq!(blob.to_polynomial(), Err(BlobError::NotPaddedError)); } #[test] diff --git a/tests/error_tests.rs b/tests/error_tests.rs index 591373b..af53a08 100644 --- a/tests/error_tests.rs +++ b/tests/error_tests.rs @@ -24,22 +24,6 @@ mod tests { assert_eq!(format!("{}", error), format!("generic error: {}", msg)); } - #[test] - fn test_polynomial_error_fft() { - let msg = String::from("test fft error"); - let error = PolynomialError::FFTError(msg.clone()); - assert_eq!(format!("{}", error), format!("FFT error: {}", msg)); - } - #[test] - fn test_polynomial_error_incorrect_form() { - let msg = String::from("test incorrect form error"); - let error = PolynomialError::IncorrectFormError(msg.clone()); - assert_eq!( - format!("{}", error), - format!("Incorrect form error: {}", msg) - ); - } - #[test] fn test_polynomial_error_equality() { let error1 = PolynomialError::SerializationFromStringError; diff --git a/tests/helpers_test.rs b/tests/helpers_test.rs index 9cd8d0f..048369a 100644 --- a/tests/helpers_test.rs +++ b/tests/helpers_test.rs @@ -5,7 +5,7 @@ use rust_kzg_bn254::{ consts::{BYTES_PER_FIELD_ELEMENT, SIZE_OF_G1_AFFINE_COMPRESSED}, helpers::{ blob_to_polynomial, convert_by_padding_empty_byte, get_num_element, is_on_curve_g1, - is_on_curve_g2, remove_empty_byte_from_padded_bytes_unchecked, set_bytes_canonical, + is_on_curve_g2, remove_empty_byte_from_padded_bytes, set_bytes_canonical, set_bytes_canonical_manual, to_byte_array, to_fr_array, }, }; @@ -140,7 +140,7 @@ fn test_convert_by_padding_empty_byte() { let mut padded_data = convert_by_padding_empty_byte("hi".as_bytes()); assert_eq!(padded_data, vec![0, 104, 105], "testing adding padding"); - let mut unpadded_data = remove_empty_byte_from_padded_bytes_unchecked(&padded_data); + let mut unpadded_data = remove_empty_byte_from_padded_bytes(&padded_data); assert_eq!(unpadded_data, vec![104, 105], "testing removing padding"); let result: Vec = vec![ @@ -227,7 +227,7 @@ fn test_convert_by_padding_empty_byte() { padded_data = convert_by_padding_empty_byte(GETTYSBURG_ADDRESS_BYTES); assert_eq!(padded_data, result, "testing adding padding"); - unpadded_data = remove_empty_byte_from_padded_bytes_unchecked(&padded_data); + unpadded_data = remove_empty_byte_from_padded_bytes(&padded_data); assert_eq!( unpadded_data, GETTYSBURG_ADDRESS_BYTES, diff --git a/tests/kzg_test.rs b/tests/kzg_test.rs index 1b4d646..b2c118d 100644 --- a/tests/kzg_test.rs +++ b/tests/kzg_test.rs @@ -2,13 +2,7 @@ mod tests { use ark_bn254::{Fr, G1Affine, G2Affine}; use lazy_static::lazy_static; - use rust_kzg_bn254::{ - blob::Blob, - errors::KzgError, - helpers, - kzg::Kzg, - polynomial::{Polynomial, PolynomialFormat}, - }; + use rust_kzg_bn254::{blob::Blob, errors::KzgError, helpers, kzg::Kzg, polynomial::Polynomial}; use std::{ env, fs::File, @@ -59,7 +53,7 @@ mod tests { poly.push(Fr::one()); } - let polynomial = Polynomial::new(&poly, 2, PolynomialFormat::InCoefficientForm).unwrap(); + let polynomial = Polynomial::new(&poly, 2).unwrap(); let result = KZG_3000.commit(&polynomial); assert_eq!( result, @@ -176,9 +170,7 @@ mod tests { .calculate_roots_of_unity(input.get_length_after_padding().try_into().unwrap()) .unwrap(); - let polynomial_input = input - .to_polynomial(PolynomialFormat::InCoefficientForm) - .unwrap(); + let polynomial_input = input.to_polynomial().unwrap(); let expanded_roots_of_unity_vec_1: Vec<&Fr> = (0..polynomial_input.len()) .map(|i| kzg_clone1.get_nth_root_of_unity(i).unwrap()) .collect(); @@ -195,9 +187,7 @@ mod tests { use ark_bn254::Fq; let blob = Blob::from_bytes_and_pad(GETTYSBURG_ADDRESS_BYTES); - let fn_output = KZG_3000 - .blob_to_kzg_commitment(&blob, PolynomialFormat::InCoefficientForm) - .unwrap(); + let fn_output = KZG_3000.blob_to_kzg_commitment(&blob).unwrap(); let commitment_from_da = G1Affine::new_unchecked( Fq::from_str( "2961155957874067312593973807786254905069537311739090798303675273531563528369", @@ -226,9 +216,7 @@ mod tests { println!("generating blob of length is {}", blob_length); let input = Blob::from_bytes_and_pad(&random_blob); - let input_poly = input - .to_polynomial(PolynomialFormat::InCoefficientForm) - .unwrap(); + let input_poly = input.to_polynomial().unwrap(); kzg.data_setup_custom(1, input.len().try_into().unwrap()) .unwrap(); @@ -268,9 +256,7 @@ mod tests { let mut kzg = KZG_INSTANCE.clone(); let input = Blob::from_bytes_and_pad(GETTYSBURG_ADDRESS_BYTES); - let input_poly = input - .to_polynomial(PolynomialFormat::InCoefficientForm) - .unwrap(); + let input_poly = input.to_polynomial().unwrap(); for index in 0..input_poly.len() - 1 { kzg.data_setup_custom(4, input.len().try_into().unwrap()) @@ -459,12 +445,7 @@ mod tests { let hard_coded_x = Fq::from_str(the_strings_str[1]).expect("should be fine"); let hard_coded_y = Fq::from_str(the_strings_str[2]).expect("should be fine"); let gnark_proof = G1Affine::new(hard_coded_x, hard_coded_y); - let poly = Polynomial::new( - &padded_input_fr_elements, - 30, - PolynomialFormat::InCoefficientForm, - ) - .unwrap(); + let poly = Polynomial::new(&padded_input_fr_elements, 30).unwrap(); kzg.data_setup_custom(4, poly.len().try_into().unwrap()) .unwrap(); let result = kzg diff --git a/tests/polynomial_test.rs b/tests/polynomial_test.rs index 21c7dfd..ba86cd0 100644 --- a/tests/polynomial_test.rs +++ b/tests/polynomial_test.rs @@ -2,16 +2,12 @@ mod tests { use ark_bn254::Fr; use ark_std::One; - use rust_kzg_bn254::{ - blob::Blob, - errors::PolynomialError, - polynomial::{Polynomial, PolynomialFormat}, - }; + use rust_kzg_bn254::{blob::Blob, errors::PolynomialError, polynomial::Polynomial}; 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(); #[test] fn test_errors() { - let polynomial_empty = Polynomial::new(&vec![], 2, PolynomialFormat::InCoefficientForm); + let polynomial_empty = Polynomial::new(&vec![], 2); assert_eq!( polynomial_empty, Err(PolynomialError::GenericError( @@ -19,8 +15,7 @@ mod tests { )) ); - let polynomial_non_empty = - Polynomial::new(&vec![Fr::one()], 2, PolynomialFormat::InCoefficientForm); + let polynomial_non_empty = Polynomial::new(&vec![Fr::one()], 2); assert!(!polynomial_non_empty.unwrap().is_empty()); } @@ -33,9 +28,7 @@ mod tests { ] .as_slice(), ); - let poly = blob - .to_polynomial(PolynomialFormat::InCoefficientForm) - .unwrap(); + let poly = blob.to_polynomial().unwrap(); assert_eq!( poly.to_bytes_be(), blob.get_blob_data(), @@ -53,9 +46,7 @@ mod tests { ); let mut long_blob = Blob::from_bytes_and_pad(GETTYSBURG_ADDRESS_BYTES); - let long_poly = long_blob - .to_polynomial(PolynomialFormat::InCoefficientForm) - .unwrap(); + let long_poly = long_blob.to_polynomial().unwrap(); // let ga_converted_fr = to_fr_array(&ga_converted); assert_eq!( long_blob.get_blob_data(), @@ -69,105 +60,4 @@ mod tests { "should be deserialized properly" ); } - - #[test] - fn test_transform_form() { - let mut blob = Blob::from_bytes_and_pad( - vec![ - 42, 212, 238, 227, 192, 237, 178, 128, 19, 108, 50, 204, 87, 81, 63, 120, 232, 27, - 116, 108, 74, 168, 109, 84, 89, 9, 6, 233, 144, 200, 125, 40, - ] - .as_slice(), - ); - let mut poly = blob - .to_polynomial(PolynomialFormat::InCoefficientForm) - .unwrap(); - // assert form is in coefficient form - assert_eq!( - poly.get_form(), - PolynomialFormat::InCoefficientForm, - "should be in coefficient form" - ); - - poly.transform_to_form(PolynomialFormat::InEvaluationForm) - .unwrap(); - // assert form is in evaluation form - assert_eq!( - poly.get_form(), - PolynomialFormat::InEvaluationForm, - "should be in evaluation form" - ); - - poly.transform_to_form(PolynomialFormat::InCoefficientForm) - .unwrap(); - // assert form is in coefficient form - assert_eq!( - poly.get_form(), - PolynomialFormat::InCoefficientForm, - "should be in coefficient form" - ); - assert_eq!( - poly.to_bytes_be(), - blob.get_blob_data(), - "start and finish bytes should be the same" - ); - - let mut long_blob = Blob::from_bytes_and_pad(GETTYSBURG_ADDRESS_BYTES); - let mut long_poly = long_blob - .to_polynomial(PolynomialFormat::InCoefficientForm) - .unwrap(); - // assert form is in coefficient form - assert_eq!( - long_poly.get_form(), - PolynomialFormat::InCoefficientForm, - "should be in coefficient form" - ); - long_poly - .transform_to_form(PolynomialFormat::InEvaluationForm) - .unwrap(); - // assert form is in evaluation form - assert_eq!( - long_poly.get_form(), - PolynomialFormat::InEvaluationForm, - "should be in evaluation form" - ); - long_poly - .transform_to_form(PolynomialFormat::InCoefficientForm) - .unwrap(); - // assert form is in coefficient form - assert_eq!( - long_poly.get_form(), - PolynomialFormat::InCoefficientForm, - "should be in coefficient form" - ); - - assert_eq!( - long_blob.get_blob_data(), - long_poly.to_bytes_be(), - "start and finish bytes should be the same" - ); - } - - #[test] - fn test_transform_form_errors() { - let mut poly = - Polynomial::new(&vec![Fr::one()], 2, PolynomialFormat::InEvaluationForm).unwrap(); - assert_eq!( - poly.transform_to_form(PolynomialFormat::InEvaluationForm), - Err(PolynomialError::IncorrectFormError( - "Polynomial is already in the given form".to_string() - )), - "should throw an error" - ); - - let mut poly = - Polynomial::new(&vec![Fr::one()], 2, PolynomialFormat::InCoefficientForm).unwrap(); - assert_eq!( - poly.transform_to_form(PolynomialFormat::InCoefficientForm), - Err(PolynomialError::IncorrectFormError( - "Polynomial is already in the given form".to_string() - )), - "should throw an error" - ); - } }