snark_verifier/pcs/kzg/multiopen/
bdfg21.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
use crate::{
    cost::{Cost, CostEstimation},
    loader::{LoadedScalar, Loader, ScalarLoader},
    pcs::{
        kzg::{KzgAccumulator, KzgAs, KzgSuccinctVerifyingKey},
        PolynomialCommitmentScheme, Query,
    },
    util::{
        arithmetic::{CurveAffine, Fraction, MultiMillerLoop, PrimeField, Rotation},
        msm::Msm,
        transcript::TranscriptRead,
        Itertools,
    },
    Error,
};
use std::{
    collections::{BTreeMap, BTreeSet},
    marker::PhantomData,
};

/// Verifier of multi-open KZG. It is for the SHPLONK implementation
/// in [`halo2_proofs`](crate::halo2_proofs).
/// Notations are following <https://eprint.iacr.org/2020/081>.
#[derive(Clone, Debug)]
pub struct Bdfg21;

impl<M, L> PolynomialCommitmentScheme<M::G1Affine, L> for KzgAs<M, Bdfg21>
where
    M: MultiMillerLoop,
    M::G1Affine: CurveAffine<ScalarExt = M::Fr, CurveExt = M::G1>,
    M::Fr: Ord,
    L: Loader<M::G1Affine>,
{
    type VerifyingKey = KzgSuccinctVerifyingKey<M::G1Affine>;
    type Proof = Bdfg21Proof<M::G1Affine, L>;
    type Output = KzgAccumulator<M::G1Affine, L>;

    fn read_proof<T>(
        _: &KzgSuccinctVerifyingKey<M::G1Affine>,
        _: &[Query<Rotation>],
        transcript: &mut T,
    ) -> Result<Bdfg21Proof<M::G1Affine, L>, Error>
    where
        T: TranscriptRead<M::G1Affine, L>,
    {
        Bdfg21Proof::read(transcript)
    }

    fn verify(
        svk: &KzgSuccinctVerifyingKey<M::G1Affine>,
        commitments: &[Msm<M::G1Affine, L>],
        z: &L::LoadedScalar,
        queries: &[Query<Rotation, L::LoadedScalar>],
        proof: &Bdfg21Proof<M::G1Affine, L>,
    ) -> Result<Self::Output, Error> {
        let sets = query_sets(queries);
        let f = {
            let coeffs = query_set_coeffs(&sets, z, &proof.z_prime);

            let powers_of_mu =
                proof.mu.powers(sets.iter().map(|set| set.polys.len()).max().unwrap());
            let msms = sets
                .iter()
                .zip(coeffs.iter())
                .map(|(set, coeff)| set.msm(coeff, commitments, &powers_of_mu));

            msms.zip(proof.gamma.powers(sets.len()))
                .map(|(msm, power_of_gamma)| msm * &power_of_gamma)
                .sum::<Msm<_, _>>()
                - Msm::base(&proof.w) * &coeffs[0].z_s
        };

        let rhs = Msm::base(&proof.w_prime);
        let lhs = f + rhs.clone() * &proof.z_prime;

        Ok(KzgAccumulator::new(lhs.evaluate(Some(svk.g)), rhs.evaluate(Some(svk.g))))
    }
}

/// Structured proof of [`Bdfg21`].
#[derive(Clone, Debug)]
pub struct Bdfg21Proof<C, L>
where
    C: CurveAffine,
    L: Loader<C>,
{
    mu: L::LoadedScalar,
    gamma: L::LoadedScalar,
    w: L::LoadedEcPoint,
    z_prime: L::LoadedScalar,
    w_prime: L::LoadedEcPoint,
}

impl<C, L> Bdfg21Proof<C, L>
where
    C: CurveAffine,
    L: Loader<C>,
{
    fn read<T: TranscriptRead<C, L>>(transcript: &mut T) -> Result<Self, Error> {
        let mu = transcript.squeeze_challenge();
        let gamma = transcript.squeeze_challenge();
        let w = transcript.read_ec_point()?;
        let z_prime = transcript.squeeze_challenge();
        let w_prime = transcript.read_ec_point()?;
        Ok(Bdfg21Proof { mu, gamma, w, z_prime, w_prime })
    }
}

fn query_sets<S: PartialEq + Ord + Copy, T: Clone>(queries: &[Query<S, T>]) -> Vec<QuerySet<S, T>> {
    let poly_shifts =
        queries.iter().fold(Vec::<(usize, Vec<_>, Vec<&T>)>::new(), |mut poly_shifts, query| {
            if let Some(pos) = poly_shifts.iter().position(|(poly, _, _)| *poly == query.poly) {
                let (_, shifts, evals) = &mut poly_shifts[pos];
                if !shifts.iter().map(|(shift, _)| shift).contains(&query.shift) {
                    shifts.push((query.shift, query.loaded_shift.clone()));
                    evals.push(&query.eval);
                }
            } else {
                poly_shifts.push((
                    query.poly,
                    vec![(query.shift, query.loaded_shift.clone())],
                    vec![&query.eval],
                ));
            }
            poly_shifts
        });

    poly_shifts.into_iter().fold(Vec::<QuerySet<_, T>>::new(), |mut sets, (poly, shifts, evals)| {
        if let Some(pos) = sets.iter().position(|set| {
            BTreeSet::from_iter(set.shifts.iter().map(|(shift, _)| shift))
                == BTreeSet::from_iter(shifts.iter().map(|(shift, _)| shift))
        }) {
            let set = &mut sets[pos];
            if !set.polys.contains(&poly) {
                set.polys.push(poly);
                set.evals.push(
                    set.shifts
                        .iter()
                        .map(|lhs| {
                            let idx = shifts.iter().position(|rhs| lhs.0 == rhs.0).unwrap();
                            evals[idx]
                        })
                        .collect(),
                );
            }
        } else {
            let set = QuerySet { shifts, polys: vec![poly], evals: vec![evals] };
            sets.push(set);
        }
        sets
    })
}

fn query_set_coeffs<F: PrimeField + Ord, T: LoadedScalar<F>>(
    sets: &[QuerySet<Rotation, T>],
    z: &T,
    z_prime: &T,
) -> Vec<QuerySetCoeff<F, T>> {
    // map of shift => loaded_shift, removing duplicate `shift` values
    // shift is the rotation, not omega^rotation, to ensure BTreeMap does not depend on omega (otherwise ordering can change)
    let superset = BTreeMap::from_iter(sets.iter().flat_map(|set| set.shifts.clone()));

    let size = sets.iter().map(|set| set.shifts.len()).chain(Some(2)).max().unwrap();
    let powers_of_z = z.powers(size);
    let z_prime_minus_z_shift_i = BTreeMap::from_iter(
        superset
            .into_iter()
            .map(|(shift, loaded_shift)| (shift, z_prime.clone() - z.clone() * loaded_shift)),
    );

    let mut z_s_1 = None;
    let mut coeffs = sets
        .iter()
        .map(|set| {
            let coeff = QuerySetCoeff::new(
                &set.shifts,
                &powers_of_z,
                z_prime,
                &z_prime_minus_z_shift_i,
                &z_s_1,
            );
            if z_s_1.is_none() {
                z_s_1 = Some(coeff.z_s.clone());
            };
            coeff
        })
        .collect_vec();

    T::Loader::batch_invert(coeffs.iter_mut().flat_map(QuerySetCoeff::denoms));
    T::Loader::batch_invert(coeffs.iter_mut().flat_map(QuerySetCoeff::denoms));
    coeffs.iter_mut().for_each(QuerySetCoeff::evaluate);

    coeffs
}

#[derive(Clone, Debug)]
struct QuerySet<'a, S, T> {
    shifts: Vec<(S, T)>, // vec of (shift, loaded_shift)
    polys: Vec<usize>,
    evals: Vec<Vec<&'a T>>,
}

impl<'a, S, T> QuerySet<'a, S, T> {
    fn msm<C: CurveAffine, L: Loader<C, LoadedScalar = T>>(
        &self,
        coeff: &QuerySetCoeff<C::Scalar, T>,
        commitments: &[Msm<'a, C, L>],
        powers_of_mu: &[T],
    ) -> Msm<C, L>
    where
        T: LoadedScalar<C::Scalar>,
    {
        self.polys
            .iter()
            .zip(self.evals.iter())
            .zip(powers_of_mu.iter())
            .map(|((poly, evals), power_of_mu)| {
                let loader = power_of_mu.loader();
                let commitment = coeff
                    .commitment_coeff
                    .as_ref()
                    .map(|commitment_coeff| {
                        commitments[*poly].clone() * commitment_coeff.evaluated()
                    })
                    .unwrap_or_else(|| commitments[*poly].clone());
                let r_eval = loader.sum_products(
                    &coeff
                        .eval_coeffs
                        .iter()
                        .zip(evals.iter().cloned())
                        .map(|(coeff, eval)| (coeff.evaluated(), eval))
                        .collect_vec(),
                ) * coeff.r_eval_coeff.as_ref().unwrap().evaluated();
                (commitment - Msm::constant(r_eval)) * power_of_mu
            })
            .sum()
    }
}

#[derive(Clone, Debug)]
struct QuerySetCoeff<F, T> {
    z_s: T,
    eval_coeffs: Vec<Fraction<T>>,
    commitment_coeff: Option<Fraction<T>>,
    r_eval_coeff: Option<Fraction<T>>,
    _marker: PhantomData<F>,
}

impl<F, T> QuerySetCoeff<F, T>
where
    F: PrimeField + Ord,
    T: LoadedScalar<F>,
{
    fn new(
        shifts: &[(Rotation, T)],
        powers_of_z: &[T],
        z_prime: &T,
        z_prime_minus_z_shift_i: &BTreeMap<Rotation, T>,
        z_s_1: &Option<T>,
    ) -> Self {
        let loader = z_prime.loader();

        let normalized_ell_primes = shifts
            .iter()
            .enumerate()
            .map(|(j, shift_j)| {
                shifts
                    .iter()
                    .enumerate()
                    .filter(|&(i, _)| i != j)
                    .map(|(_, shift_i)| (shift_j.1.clone() - &shift_i.1))
                    .reduce(|acc, value| acc * value)
                    .unwrap_or_else(|| loader.load_const(&F::ONE))
            })
            .collect_vec();

        let z = &powers_of_z[1];
        let z_pow_k_minus_one = &powers_of_z[shifts.len() - 1];

        let barycentric_weights = shifts
            .iter()
            .zip(normalized_ell_primes.iter())
            .map(|((_, loaded_shift), normalized_ell_prime)| {
                let tmp = normalized_ell_prime.clone() * z_pow_k_minus_one;
                loader.sum_products(&[(&tmp, z_prime), (&-(tmp.clone() * loaded_shift), z)])
            })
            .map(Fraction::one_over)
            .collect_vec();

        let z_s = loader.product(
            &shifts
                .iter()
                .map(|(shift, _)| z_prime_minus_z_shift_i.get(shift).unwrap())
                .collect_vec(),
        );
        let z_s_1_over_z_s = z_s_1.clone().map(|z_s_1| Fraction::new(z_s_1, z_s.clone()));

        Self {
            z_s,
            eval_coeffs: barycentric_weights,
            commitment_coeff: z_s_1_over_z_s,
            r_eval_coeff: None,
            _marker: PhantomData,
        }
    }

    fn denoms(&mut self) -> impl IntoIterator<Item = &'_ mut T> {
        if self.eval_coeffs.first().unwrap().denom().is_some() {
            return self
                .eval_coeffs
                .iter_mut()
                .chain(self.commitment_coeff.as_mut())
                .filter_map(Fraction::denom_mut)
                .collect_vec();
        }

        if self.r_eval_coeff.is_none() {
            let loader = self.z_s.loader();
            self.eval_coeffs
                .iter_mut()
                .chain(self.commitment_coeff.as_mut())
                .for_each(Fraction::evaluate);
            let barycentric_weights_sum =
                loader.sum(&self.eval_coeffs.iter().map(Fraction::evaluated).collect_vec());
            self.r_eval_coeff = Some(match self.commitment_coeff.as_ref() {
                Some(coeff) => Fraction::new(coeff.evaluated().clone(), barycentric_weights_sum),
                None => Fraction::one_over(barycentric_weights_sum),
            });
            return vec![self.r_eval_coeff.as_mut().unwrap().denom_mut().unwrap()];
        }

        unreachable!()
    }

    fn evaluate(&mut self) {
        self.r_eval_coeff.as_mut().unwrap().evaluate();
    }
}

impl<M> CostEstimation<M::G1Affine> for KzgAs<M, Bdfg21>
where
    M: MultiMillerLoop,
{
    type Input = Vec<Query<Rotation>>;

    fn estimate_cost(_: &Vec<Query<Rotation>>) -> Cost {
        Cost { num_commitment: 2, num_msm: 2, ..Default::default() }
    }
}