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
/// Provides definition of plonkish language related instance,
/// witness, and tools to work with them. The IVC is specialized for
/// exactly the plonkish language.
use ark_ff::{FftField, Field, One};
use ark_poly::{Evaluations, Radix2EvaluationDomain as R2D};
use folding::{instance_witness::Foldable, Alphas, Instance, Witness};
use itertools::Itertools;
use kimchi::{self, circuits::berkeley_columns::BerkeleyChallengeTerm};
use kimchi_msm::{columns::Column, witness::Witness as GenericWitness};
use mina_poseidon::FqSponge;
use poly_commitment::{
    commitment::{absorb_commitment, CommitmentCurve},
    PolyComm, SRS,
};
use rayon::iter::{IntoParallelIterator as _, ParallelIterator as _};
use std::ops::Index;
use strum_macros::{EnumCount as EnumCountMacro, EnumIter};

/// Vector field over F. Something like a vector.
pub trait CombinableEvals<F: Field>: PartialEq {
    fn e_as_slice(&self) -> &[F];
    fn e_as_mut_slice(&mut self) -> &mut [F];
}

impl<F: FftField> CombinableEvals<F> for Evaluations<F, R2D<F>> {
    fn e_as_slice(&self) -> &[F] {
        self.evals.as_slice()
    }
    fn e_as_mut_slice(&mut self) -> &mut [F] {
        self.evals.as_mut_slice()
    }
}

impl<F: FftField> CombinableEvals<F> for Vec<F> {
    fn e_as_slice(&self) -> &[F] {
        self.as_slice()
    }
    fn e_as_mut_slice(&mut self) -> &mut [F] {
        self.as_mut_slice()
    }
}

#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct PlonkishWitnessGeneric<const N_COL: usize, const N_FSEL: usize, F: Field, Evals> {
    pub witness: GenericWitness<N_COL, Evals>,
    // This does not have to be part of the witness... can be a static
    // precompiled object.
    pub fixed_selectors: GenericWitness<N_FSEL, Evals>,
    pub phantom: std::marker::PhantomData<F>,
}

pub type PlonkishWitness<const N_COL: usize, const N_FSEL: usize, F> =
    PlonkishWitnessGeneric<N_COL, N_FSEL, F, Evaluations<F, R2D<F>>>;

impl<const N_COL: usize, const N_FSEL: usize, F: Field, Evals: CombinableEvals<F>> Foldable<F>
    for PlonkishWitnessGeneric<N_COL, N_FSEL, F, Evals>
{
    fn combine(mut a: Self, b: Self, challenge: F) -> Self {
        for (a, b) in (*a.witness.cols).iter_mut().zip(*(b.witness.cols)) {
            for (a, b) in (a.e_as_mut_slice()).iter_mut().zip(b.e_as_slice()) {
                *a += *b * challenge;
            }
        }
        assert!(a.fixed_selectors == b.fixed_selectors);
        a
    }
}

impl<
        const N_COL: usize,
        const N_FSEL: usize,
        Curve: CommitmentCurve,
        Evals: CombinableEvals<Curve::ScalarField>,
    > Witness<Curve> for PlonkishWitnessGeneric<N_COL, N_FSEL, Curve::ScalarField, Evals>
{
}

impl<const N_COL: usize, const N_FSEL: usize, F: FftField, Evals: CombinableEvals<F>> Index<Column>
    for PlonkishWitnessGeneric<N_COL, N_FSEL, F, Evals>
{
    type Output = [F];

    /// Map a column alias to the corresponding witness column.
    fn index(&self, index: Column) -> &Self::Output {
        match index {
            Column::Relation(i) => self.witness.cols[i].e_as_slice(),
            Column::FixedSelector(i) => self.fixed_selectors[i].e_as_slice(),
            other => panic!("Invalid column index: {other:?}"),
        }
    }
}

// for selectors, () in this case as we have none
impl<const N_COL: usize, const N_FSEL: usize, F: FftField> Index<()>
    for PlonkishWitness<N_COL, N_FSEL, F>
{
    type Output = [F];

    fn index(&self, _index: ()) -> &Self::Output {
        unreachable!()
    }
}

#[derive(PartialEq, Eq, Clone, Debug)]
pub struct PlonkishInstance<
    G: CommitmentCurve,
    const N_COL: usize,
    const N_CHALS: usize,
    const N_ALPHAS: usize,
> {
    pub commitments: [G; N_COL],
    pub challenges: [G::ScalarField; N_CHALS],
    pub alphas: Alphas<G::ScalarField>,
    pub blinder: G::ScalarField,
}

impl<G: CommitmentCurve, const N_COL: usize, const N_CHALS: usize, const N_ALPHAS: usize>
    Foldable<G::ScalarField> for PlonkishInstance<G, N_COL, N_CHALS, N_ALPHAS>
{
    fn combine(a: Self, b: Self, challenge: G::ScalarField) -> Self {
        Self {
            commitments: std::array::from_fn(|i| {
                (a.commitments[i] + b.commitments[i].mul(challenge)).into()
            }),
            challenges: std::array::from_fn(|i| a.challenges[i] + challenge * b.challenges[i]),
            alphas: Alphas::combine(a.alphas, b.alphas, challenge),
            blinder: a.blinder + challenge * b.blinder,
        }
    }
}

impl<G: CommitmentCurve, const N_COL: usize, const N_CHALS: usize, const N_ALPHAS: usize>
    Instance<G> for PlonkishInstance<G, N_COL, N_CHALS, N_ALPHAS>
{
    fn to_absorb(&self) -> (Vec<G::ScalarField>, Vec<G>) {
        // FIXME: check!!!!
        let mut scalars = Vec::new();
        let mut points = Vec::new();
        points.extend(self.commitments);
        scalars.extend(self.challenges);
        scalars.extend(self.alphas.clone().powers());
        (scalars, points)
    }

    fn get_alphas(&self) -> &Alphas<G::ScalarField> {
        &self.alphas
    }

    fn get_blinder(&self) -> G::ScalarField {
        self.blinder
    }
}

// Implementation for 3 challenges; only for now.
impl<G: CommitmentCurve, const N_COL: usize, const N_ALPHAS: usize>
    PlonkishInstance<G, N_COL, 3, N_ALPHAS>
{
    pub fn from_witness<
        EFqSponge: FqSponge<G::BaseField, G, G::ScalarField>,
        Srs: SRS<G> + std::marker::Sync,
    >(
        w: &GenericWitness<N_COL, Evaluations<G::ScalarField, R2D<G::ScalarField>>>,
        fq_sponge: &mut EFqSponge,
        srs: &Srs,
        domain: R2D<G::ScalarField>,
    ) -> Self {
        let blinder = G::ScalarField::one();

        let commitments: GenericWitness<N_COL, PolyComm<G>> = w
            .into_par_iter()
            .map(|w| {
                let blinder = PolyComm::new(vec![blinder; 1]);
                let unblinded = srs.commit_evaluations_non_hiding(domain, w);
                srs.mask_custom(unblinded, &blinder).unwrap().commitment
            })
            .collect();

        // Absorbing commitments
        (&commitments).into_iter().for_each(|c| {
            assert!(c.len() == 1);
            absorb_commitment(fq_sponge, c)
        });

        let commitments: [G; N_COL] = commitments
            .into_iter()
            .map(|c| c.get_first_chunk())
            .collect_vec()
            .try_into()
            .unwrap();

        let beta = fq_sponge.challenge();
        let gamma = fq_sponge.challenge();
        let joint_combiner = fq_sponge.challenge();
        let challenges = [beta, gamma, joint_combiner];

        let alpha = fq_sponge.challenge();
        let alphas = Alphas::new_sized(alpha, N_ALPHAS);

        Self {
            commitments,
            challenges,
            alphas,
            blinder,
        }
    }

    pub fn verify_from_witness<EFqSponge: FqSponge<G::BaseField, G, G::ScalarField>>(
        &self,
        fq_sponge: &mut EFqSponge,
    ) -> Result<(), String> {
        (self.blinder == G::ScalarField::one())
            .then_some(())
            .ok_or("Blinder must be one")?;

        // Absorbing commitments
        self.commitments
            .iter()
            .for_each(|c| absorb_commitment(fq_sponge, &PolyComm { chunks: vec![*c] }));

        let beta = fq_sponge.challenge();
        let gamma = fq_sponge.challenge();
        let joint_combiner = fq_sponge.challenge();

        (self.challenges == [beta, gamma, joint_combiner])
            .then_some(())
            .ok_or("Challenges do not match the expected result")?;

        let alpha = fq_sponge.challenge();

        (self.alphas == Alphas::new_sized(alpha, N_ALPHAS))
            .then_some(())
            .ok_or("Alphas do not match the expected result")?;

        Ok(())
    }
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, EnumIter, EnumCountMacro)]
pub enum PlonkishChallenge {
    Beta,
    Gamma,
    JointCombiner,
}

impl From<BerkeleyChallengeTerm> for PlonkishChallenge {
    fn from(chal: BerkeleyChallengeTerm) -> Self {
        match chal {
            BerkeleyChallengeTerm::Beta => PlonkishChallenge::Beta,
            BerkeleyChallengeTerm::Gamma => PlonkishChallenge::Gamma,
            BerkeleyChallengeTerm::JointCombiner => PlonkishChallenge::JointCombiner,
            BerkeleyChallengeTerm::Alpha => panic!("Alpha not allowed in folding expressions"),
        }
    }
}

impl<G: CommitmentCurve, const N_COL: usize, const N_ALPHAS: usize> Index<PlonkishChallenge>
    for PlonkishInstance<G, N_COL, 3, N_ALPHAS>
{
    type Output = G::ScalarField;

    fn index(&self, index: PlonkishChallenge) -> &Self::Output {
        match index {
            PlonkishChallenge::Beta => &self.challenges[0],
            PlonkishChallenge::Gamma => &self.challenges[1],
            PlonkishChallenge::JointCombiner => &self.challenges[2],
        }
    }
}