Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ ark-ec = { version = "0.6", default-features = false }
ark-poly = { version = "0.6", default-features = false }
ark-serialize = { version = "0.6", default-features = false, features = ["derive"] }
w3f-pcs = { version = "0.0.7", default-features = false }
w3f-plonk-common = { version = "0.0.9", default-features = false }
w3f-plonk-common = { version = "0.0.10", path = "w3f-plonk-common", default-features = false }
rayon = { version = "1", default-features = false }
ark-transcript = { version = "0.0.6", default-features = false }
blake2 = { version = "0.10", default-features = false }
Expand All @@ -24,3 +24,4 @@ ark-ed-on-bls12-381-bandersnatch = { version = "0.6", default-features = false }
criterion = { version = "0.7", features = ["html_reports"] }
getrandom_or_panic = { version = "0.0.3", default-features = false }
rand_core = "0.6"
subtle = { version = "2.6", default-features = false, features = ["const-generics"] }
3 changes: 2 additions & 1 deletion w3f-plonk-common/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "w3f-plonk-common"
version = "0.0.9"
version = "0.0.10"
edition = "2021"
authors = ["Sergey Vasilyev <swasilyev@gmail.com>"]
license = "MIT/Apache-2.0"
Expand All @@ -18,6 +18,7 @@ w3f-pcs.workspace = true
rayon = { workspace = true, optional = true }
getrandom_or_panic.workspace = true
rand_core.workspace = true
subtle.workspace = true

[dev-dependencies]
ark-ed-on-bls12-381-bandersnatch.workspace = true
Expand Down
118 changes: 86 additions & 32 deletions w3f-plonk-common/src/cond_select.rs
Original file line number Diff line number Diff line change
@@ -1,63 +1,117 @@
//! Branch-free handling of secret witness bits (the prover's ring position
//! and the blinding scalar bits). These helpers keep secret-dependent
//! branches and memory indexing out of witness generation. They are defense
//! in depth, not a complete side-channel countermeasure: later pipeline
//! stages (in particular the polynomial commitment MSMs) still process the
//! witness in variable time.
//! Constant-time handling of secret witness bits (the prover's ring
//! position and the blinding scalar bits). The secret bit is wrapped
//! into a `subtle::Choice` (an optimization barrier) on entry and
//! selection is limb-wise on the raw Montgomery representation, so no
//! field arithmetic -- and none of arkworks' data-dependent conditional
//! reductions -- ever touches the bits. Defense in depth, not a complete
//! countermeasure: the unconditional point additions run variable-time
//! arkworks field arithmetic on secret-derived accumulator values, and
//! the column FFTs and polynomial commitment MSMs downstream still
//! process the witness in variable time.

use ark_ec::short_weierstrass::{Projective as SwProjective, SWCurveConfig};
use ark_ec::twisted_edwards::{Projective as TeProjective, TECurveConfig};
use ark_ff::Field;
use ark_ff::{BigInt, Field, Fp, FpConfig};
use ark_std::marker::PhantomData;
use subtle::ConditionallySelectable;

pub use subtle::Choice;

/// Conversion into [`Choice`]. The `bool` impl applies subtle's
/// optimization barrier, preventing the compiler from branching on the
/// bit later. (`From<bool> for Choice` does not exist upstream, hence
/// this local trait.)
pub trait IntoChoice {
fn into_choice(self) -> Choice;
}

impl IntoChoice for Choice {
fn into_choice(self) -> Choice {
self
}
}

impl IntoChoice for bool {
fn into_choice(self) -> Choice {
Choice::from(self as u8)
}
}

/// Lifts a bit to a field element without branching on its value.
///
/// `F::from(bool)` bottoms out in arkworks' `from_bigint`, which returns
/// early for zero; mapping the bit to 1 or 2 first routes both values
/// through the same Montgomery conversion.
pub fn bit_to_field<F: Field>(bit: bool) -> F {
F::from(bit as u64 + 1) - F::one()
pub fn bit_to_field<F: Field + CondSelect>(bit: bool) -> F {
F::select(bit, &F::one(), &F::zero())
}

/// Arithmetic two-way select. `mask` must be 0 or 1.
pub fn field_select<F: Field>(mask: F, if_true: F, if_false: F) -> F {
if_false + mask * (if_true - if_false)
/// Constant-time two-way select.
pub trait CondSelect: Sized {
fn select(bit: impl IntoChoice, if_true: &Self, if_false: &Self) -> Self;
}

/// Coordinate-wise arithmetic select between two curve points.
pub trait PointSelect<F: Field>: Sized {
/// `mask` must be 0 or 1.
fn select(mask: F, if_true: &Self, if_false: &Self) -> Self;
impl<P: FpConfig<N>, const N: usize> CondSelect for Fp<P, N> {
fn select(bit: impl IntoChoice, if_true: &Self, if_false: &Self) -> Self {
let limbs =
<[u64; N]>::conditional_select(&if_false.0 .0, &if_true.0 .0, bit.into_choice());
Fp(BigInt(limbs), PhantomData)
}
}

impl<C: TECurveConfig> PointSelect<C::BaseField> for TeProjective<C> {
fn select(mask: C::BaseField, if_true: &Self, if_false: &Self) -> Self {
impl<C: TECurveConfig> CondSelect for TeProjective<C>
where
C::BaseField: CondSelect,
{
fn select(bit: impl IntoChoice, if_true: &Self, if_false: &Self) -> Self {
let choice = bit.into_choice();
Self::new_unchecked(
field_select(mask, if_true.x, if_false.x),
field_select(mask, if_true.y, if_false.y),
field_select(mask, if_true.t, if_false.t),
field_select(mask, if_true.z, if_false.z),
CondSelect::select(choice, &if_true.x, &if_false.x),
CondSelect::select(choice, &if_true.y, &if_false.y),
CondSelect::select(choice, &if_true.t, &if_false.t),
CondSelect::select(choice, &if_true.z, &if_false.z),
)
}
}

impl<C: SWCurveConfig> PointSelect<C::BaseField> for SwProjective<C> {
fn select(mask: C::BaseField, if_true: &Self, if_false: &Self) -> Self {
impl<C: SWCurveConfig> CondSelect for SwProjective<C>
where
C::BaseField: CondSelect,
{
fn select(bit: impl IntoChoice, if_true: &Self, if_false: &Self) -> Self {
let choice = bit.into_choice();
Self::new_unchecked(
field_select(mask, if_true.x, if_false.x),
field_select(mask, if_true.y, if_false.y),
field_select(mask, if_true.z, if_false.z),
CondSelect::select(choice, &if_true.x, &if_false.x),
CondSelect::select(choice, &if_true.y, &if_false.y),
CondSelect::select(choice, &if_true.z, &if_false.z),
)
}
}

#[cfg(test)]
mod tests {
use super::*;
use ark_ed_on_bls12_381_bandersnatch::Fq;
use ark_ed_on_bls12_381_bandersnatch::{EdwardsProjective, Fq};
use ark_std::{test_rng, UniformRand};

#[test]
fn bit_lift_is_exact() {
assert_eq!(bit_to_field::<Fq>(false), Fq::from(0));
assert_eq!(bit_to_field::<Fq>(true), Fq::from(1));
}

// The selected values feed committed columns, so they are
// consensus-critical: the select must return the operand bit for bit,
// not merely an equivalent representation.
#[test]
fn select_returns_exact_operand() {
let rng = &mut test_rng();
let a = Fq::rand(rng);
let b = Fq::rand(rng);
assert_eq!(Fq::select(true, &a, &b), a);
assert_eq!(Fq::select(false, &a, &b), b);

let p = EdwardsProjective::rand(rng);
let q = EdwardsProjective::rand(rng);
let s = EdwardsProjective::select(true, &p, &q);
assert_eq!((s.x, s.y, s.t, s.z), (p.x, p.y, p.t, p.z));
let s = EdwardsProjective::select(false, &p, &q);
assert_eq!((s.x, s.y, s.t, s.z), (q.x, q.y, q.t, q.z));
}
}
7 changes: 5 additions & 2 deletions w3f-plonk-common/src/gadgets/booleanity.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use ark_poly::{Evaluations, GeneralEvaluationDomain, Polynomial};

use ark_std::{vec, vec::Vec};

use crate::cond_select::bit_to_field;
use crate::cond_select::{bit_to_field, CondSelect};
use crate::domain::Domain;
use crate::gadgets::VerifierGadget;
use crate::{const_evals, Column, FieldColumn};
Expand All @@ -16,7 +16,10 @@ pub struct BitColumn<F: FftField> {
}

impl<F: FftField> BitColumn<F> {
pub fn init(bits: Vec<bool>, domain: &Domain<F>) -> Self {
pub fn init(bits: Vec<bool>, domain: &Domain<F>) -> Self
where
F: CondSelect,
{
let bits_as_field_elements = bits.iter().map(|&bit| bit_to_field(bit)).collect();
let col = domain.column(bits_as_field_elements);
Self { bits, col }
Expand Down
10 changes: 5 additions & 5 deletions w3f-plonk-common/src/gadgets/ec/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::cond_select::{bit_to_field, PointSelect};
use crate::cond_select::CondSelect;
use crate::domain::Domain;
use crate::gadgets::booleanity::BitColumn;
use crate::{Column, FieldColumn};
Expand Down Expand Up @@ -90,7 +90,7 @@ where
domain: &Domain<F>,
) -> Self
where
P::Group: PointSelect<F>,
P::Group: CondSelect,
{
debug_assert_eq!(bitmask.payload_len(), domain.capacity - 1);
debug_assert_eq!(points.payload_len(), domain.capacity - 1);
Expand All @@ -103,7 +103,7 @@ where
.map(|(&bit, point)| {
let mut sum = projective_acc;
sum += point;
projective_acc = P::Group::select(bit_to_field(bit), &sum, &projective_acc);
projective_acc = P::Group::select(bit, &sum, &projective_acc);
projective_acc
})
.collect();
Expand Down Expand Up @@ -166,9 +166,9 @@ mod tests {
// before the hardening were built from.
fn acc_matches_naive_accumulation<F, P>()
where
F: FftField,
F: FftField + CondSelect,
P: AffineRepr<BaseField = F>,
P::Group: PointSelect<F>,
P::Group: CondSelect,
{
let rng = &mut test_rng();
let domain = Domain::test_domain(256, true);
Expand Down
65 changes: 64 additions & 1 deletion w3f-plonk-common/src/gadgets/inner_prod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@ use ark_poly::{Evaluations, GeneralEvaluationDomain};

use ark_std::{vec, vec::Vec};

use crate::cond_select::CondSelect;
use crate::domain::Domain;
use crate::gadgets::booleanity::BitColumn;
use crate::gadgets::{ProverGadget, VerifierGadget};
use crate::{Column, FieldColumn};

Expand Down Expand Up @@ -39,6 +41,27 @@ impl<F: FftField> InnerProd<F> {
}
}

/// Same as `init` with `b` the field representation of `bits`, but the
/// products are computed with a constant-time select, so the
/// accumulation does not branch on the bits.
pub fn init_bits(a: FieldColumn<F>, bits: &BitColumn<F>, domain: &Domain<F>) -> Self
where
F: CondSelect,
{
assert_eq!(a.payload_len(), domain.capacity - 1);
assert_eq!(bits.payload_len(), domain.capacity - 1);
let inner_prods = Self::partial_bit_prods(a.payload(), &bits.bits);
let mut acc = vec![F::zero()];
acc.extend(inner_prods);
let acc = domain.column(acc);
Self {
a,
b: bits.col.clone(),
not_last: domain.not_last_row.clone(),
acc,
}
}

/// Returns a[0]b[0], a[0]b[0] + a[1]b[1], ..., a[0]b[0] + a[1]b[1] + ... + a[n-1]b[n-1]
fn partial_inner_prods(a: &[F], b: &[F]) -> Vec<F> {
assert_eq!(a.len(), b.len());
Expand All @@ -50,6 +73,21 @@ impl<F: FftField> InnerProd<F> {
})
.collect()
}

fn partial_bit_prods(a: &[F], bits: &[bool]) -> Vec<F>
where
F: CondSelect,
{
assert_eq!(a.len(), bits.len());
a.iter()
.zip(bits)
.scan(F::zero(), |state, (&a, &bit)| {
let sum = *state + a;
*state = F::select(bit, &sum, state);

@burdges burdges Aug 14, 2026

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ahh okay so here there is extra work, but this seems tiny compared to the full proof cost.

Some(*state)
})
.collect()
}
}

impl<F: FftField> ProverGadget<F> for InnerProd<F> {
Expand Down Expand Up @@ -92,7 +130,7 @@ mod tests {
use ark_std::test_rng;

use crate::domain::Domain;
use crate::test_helpers::random_vec;
use crate::test_helpers::{random_bitvec, random_vec};

use super::*;

Expand Down Expand Up @@ -131,4 +169,29 @@ mod tests {
_test_inner_prod_gadget(false);
_test_inner_prod_gadget(true);
}

// The acc column is committed, so its values are consensus-critical:
// the branch-free bit accumulation must produce exactly the column the
// naive product accumulation produces. Only the payload rows are
// compared: the trailing zk rows are random per column instance.
#[test]
fn bit_acc_matches_naive_accumulation() {
let rng = &mut test_rng();
let domain = Domain::test_domain(256, true);
let a: Vec<Fq> = random_vec(domain.capacity - 1, rng);
let bits = random_bitvec(domain.capacity - 1, 0.5, rng);

let naive = InnerProd::init(
domain.column(a.clone()),
domain.column(bits.iter().map(|&bit| Fq::from(bit)).collect()),
&domain,
);
let bit_col = BitColumn::init(bits, &domain);
let gadget = InnerProd::init_bits(domain.column(a), &bit_col, &domain);

assert_eq!(
gadget.acc.evals.evals[..domain.capacity],
naive.acc.evals.evals[..domain.capacity]
);
}
}
2 changes: 1 addition & 1 deletion w3f-ring-proof/Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "w3f-ring-proof"
version = "0.0.9"
version = "0.0.10"
edition = "2021"
authors = ["Sergey Vasilyev <swasilyev@gmail.com>"]
license = "MIT/Apache-2.0"
Expand Down
1 change: 1 addition & 0 deletions w3f-ring-proof/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use ark_std::rand::RngCore;
use w3f_pcs::pcs::PCS;

pub use piop::index;
pub use w3f_plonk_common::cond_select::CondSelect;
pub use w3f_plonk_common::domain::Domain;
use w3f_plonk_common::Proof;

Expand Down
12 changes: 8 additions & 4 deletions w3f-ring-proof/src/piop/prover.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use w3f_pcs::pcs::Commitment;
use crate::piop::params::PiopParams;
use crate::piop::FixedColumns;
use crate::piop::{RingCommitments, RingEvaluations};
use w3f_plonk_common::cond_select::PointSelect;
use w3f_plonk_common::cond_select::CondSelect;
use w3f_plonk_common::domain::Domain;
use w3f_plonk_common::gadgets::booleanity::{BitColumn, Booleanity};
use w3f_plonk_common::gadgets::ec::AffineColumn;
Expand Down Expand Up @@ -49,7 +49,8 @@ impl<F: PrimeField, G: AffineRepr<BaseField = F>> PiopProver<F, G> {
secret: G::ScalarField,
) -> Self
where
G::Group: PointSelect<F>,
F: CondSelect,
G::Group: CondSelect,
{
let domain = params.domain.clone();
let FixedColumns {
Expand All @@ -58,7 +59,7 @@ impl<F: PrimeField, G: AffineRepr<BaseField = F>> PiopProver<F, G> {
} = fixed_columns;
let bits = Self::bits_column(&params, prover_index_in_keys, secret);
let booleanity = Booleanity::init(bits.clone());
let inner_prod = InnerProd::init(ring_selector.clone(), bits.col.clone(), &domain);
let inner_prod = InnerProd::init_bits(ring_selector.clone(), &bits, &domain);
let inner_prod_acc = FixedCells::init(inner_prod.acc.clone(), &domain, F::zero(), F::one());
let cond_add = CondAdd::init(bits.clone(), points.clone(), params.seed, &domain);
let (seed_x, seed_y) = params.seed.xy().unwrap();
Expand All @@ -84,7 +85,10 @@ impl<F: PrimeField, G: AffineRepr<BaseField = F>> PiopProver<F, G> {
params: &PiopParams<G>,
index_in_keys: usize,
secret: G::ScalarField,
) -> BitColumn<F> {
) -> BitColumn<F>
where
F: CondSelect,
{
// The index is the prover's ring position: an equality scan avoids the
// secret-index memory write of `keyset_part[index_in_keys] = true`.
let keyset_part: Vec<bool> = (0..params.keyset_part_size)
Expand Down
Loading
Loading