Skip to content

Commit

Permalink
feat: something about shuffle and msp
Browse files Browse the repository at this point in the history
!! cannot run
  • Loading branch information
0oyun committed Aug 28, 2024
1 parent 4dca26b commit f43a275
Show file tree
Hide file tree
Showing 17 changed files with 784 additions and 13 deletions.
3 changes: 2 additions & 1 deletion halo2-base/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ jemallocator = { version = "=0.5", optional = true }
mimalloc = { version = "=0.1", default-features = false, optional = true }

[features]
default = ["halo2-axiom", "display", "test-utils"]
# default = ["halo2-axiom", "display", "test-utils"]
default = ["halo2-pse", "display", "test-utils"]
asm = ["halo2_proofs_axiom?/asm"]
dev-graph = ["halo2_proofs?/dev-graph", "plotters"] # only works with halo2-pse for now
halo2-pse = ["halo2_proofs/circuit-params"]
Expand Down
2 changes: 1 addition & 1 deletion halo2-base/src/gates/circuit/builder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -302,7 +302,7 @@ impl<F: ScalarField> BaseCircuitBuilder<F> {
let copy_manager = self.core.copy_manager.lock().unwrap();
let cell =
copy_manager.assigned_advices.get(&cell).expect("instance not assigned");
layouter.constrain_instance(*cell, *instance_col, i);
let _ = layouter.constrain_instance(*cell, *instance_col, i);
}
}
}
Expand Down
14 changes: 14 additions & 0 deletions halo2-base/src/gates/circuit/mod.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
// use proptest::strategy::W;
use serde::{Deserialize, Serialize};

use crate::utils::ScalarField;
Expand All @@ -13,6 +14,7 @@ use self::builder::BaseCircuitBuilder;

use super::flex_gate::{FlexGateConfig, FlexGateConfigParams};
use super::range::RangeConfig;
// use super::shuffle::ShuffleConfig;

/// Module that helps auto-build circuits
pub mod builder;
Expand Down Expand Up @@ -67,6 +69,15 @@ pub enum MaybeRangeConfig<F: ScalarField> {
WithRange(RangeConfig<F>),
}


// #[derive(Clone, Debug)]
// pub enum MaybeShuffleConfig<F: ScalarField> {
// /// Config for a circuit that does not use range checks
// WithoutShuffle(FlexGateConfig<F>),
// /// Config for a circuit that does use range checks
// WithShuffle(ShuffleConfig<F>),
// }

impl<F: ScalarField> BaseConfig<F> {
/// Generates a new `BaseConfig` depending on `params`.
/// - It will generate a `RangeConfig` is `params` has `lookup_bits` not None **and** `num_lookup_advice_per_phase` are not all empty or zero (i.e., if `params` indicates that the circuit actually requires a lookup table).
Expand Down Expand Up @@ -170,6 +181,9 @@ impl<F: ScalarField> Circuit<F> for BaseCircuitBuilder<F> {
if let MaybeRangeConfig::WithRange(config) = &config.base {
config.load_lookup_table(&mut layouter).expect("load lookup table should not fail");
}
// if let MaybeShuffleConfig::WithShuffle(config) = &config.base {
// config.load_shuffle(&mut layouter).expect("load shuffle should not fail");
// }
// Only FirstPhase (phase 0)
layouter
.assign_region(
Expand Down
1 change: 1 addition & 0 deletions halo2-base/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
#![warn(clippy::default_numeric_fallback)]
#![warn(missing_docs)]


use getset::CopyGetters;
use itertools::Itertools;
// Different memory allocator options:
Expand Down
2 changes: 1 addition & 1 deletion halo2-base/src/utils/halo2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ pub fn constrain_virtual_equals_external<F: Field + Ord>(
match copy_manager.assigned_advices.entry(ctx_cell) {
Entry::Occupied(acell) => {
// The virtual cell has already been assigned, so we can constrain it to equal the external cell.
region.constrain_equal(*acell.get(), external_cell);
let _ = region.constrain_equal(*acell.get(), external_cell);
}
Entry::Vacant(assigned) => {
// The virtual cell **must** be an external cell
Expand Down
4 changes: 3 additions & 1 deletion halo2-ecc/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ halo2-base = { version = "=0.4.1", path = "../halo2-base", default-features = fa
# plotting circuit layout
plotters = { version = "0.3.0", optional = true }
hex = "0.4.3"
poseidon = {git = "https://github.com/scroll-tech/poseidon"}

[dev-dependencies]
ark-std = { version = "0.3.0", features = ["print-trace"] }
Expand All @@ -38,7 +39,8 @@ test-log = "0.2.12"
env_logger = "0.10.0"

[features]
default = ["jemallocator", "halo2-axiom", "display"]
# default = ["jemallocator", "halo2-axiom", "display"]
default = ["jemallocator", "halo2-pse", "display"]
dev-graph = ["halo2-base/dev-graph", "plotters"]
display = ["halo2-base/display"]
asm = ["halo2-base/asm"]
Expand Down
2 changes: 2 additions & 0 deletions halo2-ecc/configs/bn254/shuffle.config
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
{"strategy":"Simple","degree":14,"num_aggregation":2}
{"strategy":"Simple","degree":15,"num_aggregation":2}
3 changes: 3 additions & 0 deletions halo2-ecc/src/bn254/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ pub mod final_exp;
pub mod pairing;
pub mod merkle_tree;
pub mod combine_bls_mt;
pub mod shuffle;
pub mod msp;
pub mod shuffle2;

#[derive(Clone)]
pub struct MerkleInfo<F: BigPrimeField>{
Expand Down
103 changes: 103 additions & 0 deletions halo2-ecc/src/bn254/msp.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
#![allow(non_snake_case)]

use super::bls_signature::BlsSignatureChip;
use super::pairing::PairingChip;
use super::{Fp12Chip, Fp2Chip, FpChip};
use crate::bigint::ProperCrtUint;
use crate::ecc::{scalar_multiply, EcPoint, EccChip};
use crate::fields::vector::{FieldVector, CRTInteger};
use crate::fields::{fp, fp12, fp2, FieldChip};
use crate::halo2_proofs::halo2curves::bn256::Fq12;
use crate::halo2_proofs::halo2curves::bn256::{G1Affine, G2Affine};
use halo2_base::gates::{GateChip,GateInstructions};
use halo2_base::halo2_proofs::halo2curves::bn256::{Fq, Fq2};
use halo2_base::poseidon::hasher::PoseidonHasher;
use halo2_base::utils::BigPrimeField;
use halo2_base::{AssignedValue, Context};

// To avoid issues with mutably borrowing twice (not allowed in Rust), we only store fp_chip and construct g2_chip and fp12_chip in scope when needed for temporary mutable borrows
pub struct MspChip<'chip, F: BigPrimeField> {
pub bls_signature_chip: &'chip BlsSignatureChip<'chip, F>,
pub poseidon_chip: &'chip PoseidonHasher<F, 3, 2>,
// pub fp_chip: &'chip FpChip<'chip, F>,
}

impl<'chip, F: BigPrimeField> MspChip<'chip, F> {
pub fn new(
bls_signature_chip: &'chip BlsSignatureChip<F>,
poseidon_chip: &'chip PoseidonHasher<F, 3, 2>,
// fp_chip: &'chip FpChip<F>,
) -> Self {
Self {
bls_signature_chip,
poseidon_chip,
// fp_chip,
}
}

pub fn msp_verify(
&self,
ctx: &mut Context<F>,
g1: G1Affine,
signatures: &[G2Affine],
pubkeys: &[G1Affine], // mvk
msghash: G2Affine,
weighting_seed : F,
ivk: G1Affine,
isig: G2Affine, // \mu
) -> AssignedValue<F> {
// TODO: verify proof of possesion

// A: verify BLS signature
let verify_A = self.bls_signature_chip.bls_signature_verify(ctx, g1, signatures, pubkeys, msghash);

// B
let signatures_x_assigned = signatures.iter().map(|pt| {
ctx.load_witness(F::from_bytes_le(&pt.x.c0.to_bytes()))
}).collect::<Vec<_>>();
let gate_chip = GateChip::<F>::default();
let weighting_seed_comp = self.poseidon_chip.hash_fix_len_array(ctx, &gate_chip, &signatures_x_assigned[..]);
let weighting_seed_assigned = ctx.load_witness(weighting_seed);
// B_1 : verify weighting seed
let verify_B_1 = gate_chip.is_equal(ctx, weighting_seed_assigned, weighting_seed_comp);
// e_i = H(i,weighting_seed) for i in 0..n where n is the number of public keys
let e_is = pubkeys.iter().enumerate().map(|(i, _)| {
let i_assigned = ctx.load_witness(F::from(i as u64));
self.poseidon_chip.hash_fix_len_array(ctx, &gate_chip, &[i_assigned, weighting_seed_assigned])
}).collect::<Vec<_>>();

let g1_chip = EccChip::new(self.bls_signature_chip.fp_chip);
let fp2_chip = Fp2Chip::new(self.bls_signature_chip.fp_chip);
let g2_chip = EccChip::new(&fp2_chip);
// B_2 : verify ivk, isig
// ivk = \sum_{i=0}^{n-1} e_i * mvk_i
let ivk_assigned = self.bls_signature_chip.pairing_chip.load_private_g1(ctx, ivk);
let mvks = pubkeys.iter().map(|pt| self.bls_signature_chip.pairing_chip.load_private_g1(ctx, *pt)).collect::<Vec<_>>();
let products = mvks.iter().zip(e_is.iter()).map(|(mvk, e_i)| {
g1_chip.scalar_mult(ctx, mvk.clone(), e_is.clone(),64,12)
}).collect::<Vec<_>>();
let ivk_comp = g1_chip.sum(ctx, products);
let verify_B_2 = g1_chip.is_equal(ctx, ivk_assigned, ivk_comp);
// isig = \sum_{i=0}^{n-1} e_i * sig_i
let isig_assigned = self.bls_signature_chip.pairing_chip.load_private_g2(ctx, isig);
let sigs = signatures.iter().map(|pt| self.bls_signature_chip.pairing_chip.load_private_g2(ctx, *pt)).collect::<Vec<_>>();
let products = sigs.iter().zip(e_is.iter()).map(|(sig, e_i)| {
g2_chip.scalar_mult(ctx, sig.clone(), e_is.clone(),64,12)
}).collect::<Vec<_>>();
let isig_comp = g2_chip.sum(ctx, products);

let verify_B_3 = g2_chip.is_equal(ctx, isig_assigned, isig_comp);

// B_4 : verify e(g1, isig) = e(ivk, H(m))
let verify_B_4 = self.bls_signature_chip.bls_signature_verify(ctx, g1, &[isig], &[ivk], msghash);

// Final result
let result = gate_chip.and(
ctx,
&gate_chip.and(ctx, &verify_A, &verify_B_1),
&gate_chip.and(ctx, &verify_B_2, &gate_chip.and(ctx, &verify_B_3, &verify_B_4)),
);
result

}
}
Loading

0 comments on commit f43a275

Please sign in to comment.