Skip to content

Commit

Permalink
modify root of unity and clean code
Browse files Browse the repository at this point in the history
  • Loading branch information
dongliangCai committed Mar 21, 2024
1 parent 9c7bf63 commit 38d5279
Show file tree
Hide file tree
Showing 8 changed files with 56 additions and 66 deletions.
13 changes: 7 additions & 6 deletions aggregator/src/aggregation/circuit.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
use ark_std::{end_timer, start_timer};
use eth_types::{Field, ToLittleEndian, U256};
use eth_types::{Field, ToLittleEndian};
use halo2_proofs::{
circuit::{Layouter, Region, SimpleFloorPlanner, Value}, halo2curves::bn256::{Bn256, Fr, G1Affine}, plonk::{Circuit, ConstraintSystem, Error, Selector}, poly::{commitment::ParamsProver, kzg::commitment::ParamsKZG}
circuit::{Layouter, SimpleFloorPlanner, Value}, halo2curves::bn256::{Bn256, Fr, G1Affine}, plonk::{Circuit, ConstraintSystem, Error, Selector}, poly::{commitment::ParamsProver, kzg::commitment::ParamsKZG}
};
use itertools::Itertools;
use rand::Rng;
use std::{env, fs::File, result};
use std::{env, fs::File};
use bls12_381::Scalar as Fp;
#[cfg(not(feature = "disable_proof_aggregation"))]
use snark_verifier::loader::halo2::halo2_ecc::halo2_base;
Expand All @@ -24,7 +24,9 @@ use snark_verifier_sdk::{CircuitExt, Snark, SnarkWitness};
use zkevm_circuits::util::Challenges;

use crate::{
batch::BatchHash, constants::{ACC_LEN, DIGEST_LEN, MAX_AGG_SNARKS, BLOB_POINT_LEN}, core::{assign_batch_hashes, extract_proof_and_instances_with_pairing_check}, util::parse_hash_digest_cells, ConfigParams, BITS, CHALLENGE_POINT_LEN, LIMBS
batch::BatchHash, constants::{ACC_LEN, DIGEST_LEN, MAX_AGG_SNARKS},
core::{assign_batch_hashes, extract_proof_and_instances_with_pairing_check},
util::parse_hash_digest_cells, ConfigParams, BITS, LIMBS
};

use super::AggregationConfig;
Expand Down Expand Up @@ -254,14 +256,13 @@ impl Circuit<Fr> for AggregationCircuit {
Ok(blob_result)
},
)?;
let blob_cells = blob_result.iter().map(|x| x.cell()).collect::<Vec<_>>();

assert_eq!(
blob_result.len(),
3 * (self.batch_hash.number_of_valid_chunks + 1),
"error blob result len"
);


// ==============================================
// step 2: public input aggregation circuit
// ==============================================
Expand Down
10 changes: 1 addition & 9 deletions aggregator/src/batch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,15 +256,7 @@ impl BatchHash {
.map(|&x| F::from(x as u64))
.collect()]
}

pub(crate) fn instance_for_blob<F: Field>(&self) -> (Vec<F>,Vec<F>) {
let cp_fe = Fp::from_bytes(&self.challenge_point.to_le_bytes()).unwrap();
let challenge_point = decompose_biguint::<F>(&fe_to_biguint(&cp_fe), 3, 88);
let pr_fe = Fp::from_bytes(&self.result.to_le_bytes()).unwrap();
let result = decompose_biguint::<F>(&fe_to_biguint(&pr_fe), 3, 88);
(challenge_point, result)
}

//decompose cp and result to Fr be bytes
pub(crate) fn decompose_cp_result(challenge_point: U256, result: U256) -> (Vec<[u8; 32]>,Vec<[u8; 32]>) {
let cp_fe = Fp::from_bytes(&challenge_point.to_le_bytes()).unwrap();
let cp = decompose_biguint::<Fr>(&fe_to_biguint(&cp_fe), 3, 88);
Expand Down
3 changes: 1 addition & 2 deletions aggregator/src/chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,6 @@ impl ChunkHash {
/// Sample a chunk hash from random (for testing)
#[cfg(test)]
pub(crate) fn mock_random_chunk_hash_for_testing<R: rand::RngCore>(r: &mut R) -> Self {
use halo2_proofs::plonk::Challenge;

let mut prev_state_root = [0u8; 32];
r.fill_bytes(&mut prev_state_root);
Expand All @@ -128,7 +127,7 @@ impl ChunkHash {

let mut buf1 = [0u8; 64];
r.fill_bytes(&mut buf1);
let mut partial_result = Fp::from_bytes_wide(&buf1).to_bytes();
let partial_result = Fp::from_bytes_wide(&buf1).to_bytes();

// r.fill_bytes(&mut partial_result);
Self {
Expand Down
8 changes: 1 addition & 7 deletions aggregator/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,7 @@ pub(crate) const LOG_DEGREE: u32 = 19;
// - prev_state_root 32 bytes
// - post_state_root 32 bytes
// - withdraw_root 32 bytes
// - chunk_data_hash 32 bytes

// - batch_data_hash 32 bytes
// - chunk_data_hash or batch_data_hash 32 bytes
// - challenge_point 32*3 bytes
// - result 32*3 bytes
pub(crate) const PREV_STATE_ROOT_INDEX: usize = 8;
Expand All @@ -44,10 +42,6 @@ pub(crate) const RESULT_INDEX: usize = 232;
/// An decomposed accumulator consists of 12 field elements
pub(crate) const ACC_LEN: usize = 12;

/// Blob information consists of 6 field elements
pub(crate) const BLOB_POINT_LEN: usize = CHALLENGE_POINT_LEN + RESULT_LEN;
pub(crate) const CHALLENGE_POINT_LEN: usize = 3;
pub(crate) const RESULT_LEN: usize = 3;
/// number of limbs when decomposing a field element in the ECC chip
pub(crate) const LIMBS: usize = 3;
/// number of bits in each limb in the ECC chip
Expand Down
2 changes: 1 addition & 1 deletion aggregator/src/tests/mock_chunk.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use snark_verifier_sdk::CircuitExt;
use zkevm_circuits::util::Challenges;

use crate::{
constants::{ACC_LEN, DIGEST_LEN}, ChunkHash, RlcConfig, BLOB_POINT_LEN, LOG_DEGREE
constants::{ACC_LEN, DIGEST_LEN}, ChunkHash, RlcConfig, LOG_DEGREE
};

/// This config is used to compute RLCs for bytes.
Expand Down
42 changes: 13 additions & 29 deletions zkevm-circuits/src/blob_circuit.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
use ethers_core::types::TxpoolStatus;
use halo2_base::{
Context,
utils::{
ScalarField, fe_to_biguint, modulus, decompose_biguint,},
ScalarField, fe_to_biguint, modulus,},
gates::GateInstructions, AssignedValue,
};

use halo2_ecc::{fields::{fp::{FpConfig, FpStrategy}, FieldChip}, bigint::CRTInteger};
use halo2_proofs::{
circuit::{Layouter, Value, Cell},
plonk::{ConstraintSystem, Error, Expression, Column, Instance, Assigned},
plonk::{ConstraintSystem, Error, Expression, Assigned},
};

use bls12_381::{Scalar as Fp};
use bls12_381::Scalar as Fp;
use itertools::Itertools;
use crate::{util::{SubCircuit, Challenges, SubCircuitConfig}, witness::{Block, Transaction, CircuitBlob}, evm_circuit::util::rlc};
use std::{io::Read, marker::PhantomData};
use eth_types::{Field, ToBigEndian, ToLittleEndian, ToScalar, H256};
use crate::{util::{SubCircuit, Challenges, SubCircuitConfig}, witness::{Block, CircuitBlob},};
use std::marker::PhantomData;
use eth_types::{Field, U256};

pub mod util;
mod test;
Expand Down Expand Up @@ -137,8 +136,7 @@ impl<F: Field> BlobCircuit<F>{
) -> Result<Vec<AssignedValue<F>>, Error> {
let one = ScalarFieldElement::constant(Fp::one());
let blob_width = ScalarFieldElement::constant(u64::try_from(BLOB_WIDTH).unwrap().into());
let blob_width_th_root_of_unity =
Fp::from(123).pow(&[(FP_S - BLOB_WIDTH_BITS) as u64, 0, 0, 0]);
let blob_width_th_root_of_unity = blob_width_th_root_of_unity();
let roots_of_unity: Vec<_> = (0..BLOB_WIDTH)
.map(|i| blob_width_th_root_of_unity.pow(&[i as u64, 0, 0, 0]))
.collect();
Expand Down Expand Up @@ -244,10 +242,12 @@ impl<F: Field> BlobCircuit<F>{
// let challenge_point_fp = cross_field_load_private(ctx, &fp_chip, &fp_chip.range, &cp_lo, &cp_hi);

// loading roots of unity to fp_chip as constants

let blob_width_th_root_of_unity =
Fp::from(123).pow(&[(FP_S - BLOB_WIDTH_BITS) as u64, 0, 0, 0]);
// let blob_width_th_root_of_unity = get_omega(4, 2);

let blob_width_th_root_of_unity = blob_width_th_root_of_unity();

// let blob_width_th_root_of_unity =
// Fp::from(123).pow(&[(FP_S - BLOB_WIDTH_BITS) as u64, 0, 0, 0]);

let roots_of_unity: Vec<_> = (0..BLOB_WIDTH)
.map(|i| blob_width_th_root_of_unity.pow(&[i as u64, 0, 0, 0]))
.collect();
Expand Down Expand Up @@ -383,18 +383,6 @@ impl<F: Field> SubCircuit<F> for BlobCircuit<F>{

/// Compute the public inputs for this circuit.
fn instance(&self) -> Vec<Vec<F>> {

// let omega = Fp::from(123).pow(&[(FP_S - 12) as u64, 0, 0, 0]);

// let result = poly_eval_partial(self.partial_blob.clone(), self.challenge_point, omega, self.index);

// let mut public_inputs = decompose_biguint(&fe_to_biguint(&self.challenge_point), NUM_LIMBS, LIMB_BITS);

// public_inputs.extend(decompose_biguint::<F>(&fe_to_biguint(&result), NUM_LIMBS, LIMB_BITS));

// println!("compute blob public input {:?}", public_inputs);

// vec![public_inputs]
vec![]
}

Expand Down Expand Up @@ -429,10 +417,6 @@ impl<F: Field> SubCircuit<F> for BlobCircuit<F>{

self.exports.borrow_mut().replace(export);

// for (i, v) in result_limbs.iter().enumerate() {
// layouter.constrain_instance(v.cell(), config.instance, i)?;
// }

Ok(())
}
}
30 changes: 18 additions & 12 deletions zkevm-circuits/src/blob_circuit/test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use halo2_proofs::{
arithmetic::Field as HaloField, circuit, dev::MockProver, halo2curves::{
bn256::Fr,
group::Curve,
secp256k1::{self, Secp256k1Affine},
secp256k1::{self, Secp256k1Affine}, FieldExt,
}
};
use rand::{Rng, RngCore};
Expand All @@ -29,8 +29,7 @@ fn test_blob_consistency(){

println!("blob:{:?}",blob);

// let omega = get_omega(4, 2);
let omega = Fp::from(123).pow(&[(FP_S - 12) as u64, 0, 0, 0]);
let omega = blob_width_th_root_of_unity();
println!("omega:{}", omega);
let result = poly_eval(blob.clone(), challenge_point, omega);

Expand Down Expand Up @@ -60,8 +59,6 @@ fn test_blob_consistency(){

#[test]
fn test_partial_blob_consistency(){
let batch_commit = Fr::random(OsRng);

let blob: Vec<Fp> = (0..51)
.map(|_| Fp::random(OsRng))
.collect();
Expand All @@ -70,14 +67,10 @@ fn test_partial_blob_consistency(){
log::trace!("blob:{:?}", blob);

let index = 50;
let omega = Fp::from(123).pow(&[(FP_S - 12) as u64, 0, 0, 0]);
let roots_of_unity: Vec<_> = (0..4096)
.map(|i| omega.pow(&[i as u64, 0, 0, 0]))
.collect();
let roots_of_unity_brp = bit_reversal_permutation(roots_of_unity);
let omega = blob_width_th_root_of_unity();

let challenge_point = roots_of_unity_brp[0];
//let challenge_point = Fp::random(OsRng);
// let challenge_point = roots_of_unity_brp[0];
let challenge_point = Fp::random(OsRng);
// let challenge_point = Fp::from(128);

let result = poly_eval_partial(blob.clone(), challenge_point, omega, index);
Expand Down Expand Up @@ -115,4 +108,17 @@ fn test_zero_blob(){
log::trace!("partial blob: {:?} len: {:?}", result, result.len());
}

#[test]
fn test_root_of_unity(){

let modulus = U256::from_str_radix(Fp::MODULUS, 16).unwrap();

let exponent = (modulus - U256::one()) / U256::from(4096);

let primitive_root_of_unity = Fp::from(7);

let root_of_unity = primitive_root_of_unity.pow(&exponent.0);

println!("root of unity= {:?}", root_of_unity);
}

14 changes: 14 additions & 0 deletions zkevm-circuits/src/blob_circuit/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -391,3 +391,17 @@ pub fn load_private<F: Field>(fq_chip: &FpConfig<F, Fp>, ctx: &mut Context<F>, a
fq_chip.range_check(ctx, &a_loaded, Fp::NUM_BITS as usize);
a_loaded
}
// https://github.com/ethereum/consensus-specs/blob/dev/specs/deneb/polynomial-commitments.md#constants
// https://github.com/ethereum/consensus-specs/blob/dev/specs/deneb/polynomial-commitments.md#compute_roots_of_unity
pub fn blob_width_th_root_of_unity() -> Fp{

let modulus = U256::from_str_radix(Fp::MODULUS, 16).unwrap();

let exponent = (modulus - U256::one()) / U256::from(4096);

let primitive_root_of_unity = Fp::from(7);

let root_of_unity = primitive_root_of_unity.pow(&exponent.0);

root_of_unity
}

0 comments on commit 38d5279

Please sign in to comment.