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
350
351
352
353
use p3_bn254_fr::Bn254Fr;
use sp1_recursion_compiler::{
    config::OuterConfig,
    ir::{Builder, Config, Ext, Felt, Var, Witness},
};
use sp1_recursion_core::stark::config::{
    BabyBearPoseidon2Outer, OuterBatchOpening, OuterChallenge, OuterCommitPhaseStep, OuterDigest,
    OuterFriProof, OuterPcsProof, OuterQueryProof, OuterVal,
};
use sp1_stark::{
    AirOpenedValues, ChipOpenedValues, ShardCommitment, ShardOpenedValues, ShardProof,
};

use crate::types::{
    AirOpenedValuesVariable, BatchOpeningVariable, ChipOpenedValuesVariable,
    FriCommitPhaseProofStepVariable, FriProofVariable, FriQueryProofVariable, OuterDigestVariable,
    RecursionShardOpenedValuesVariable, RecursionShardProofVariable, TwoAdicPcsProofVariable,
};

pub trait Witnessable<C: Config> {
    type WitnessVariable;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable;

    fn write(&self, witness: &mut Witness<C>);
}

type C = OuterConfig;

impl Witnessable<C> for Bn254Fr {
    type WitnessVariable = Var<Bn254Fr>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        builder.witness_var()
    }

    fn write(&self, witness: &mut Witness<C>) {
        witness.vars.push(*self);
    }
}

impl Witnessable<C> for OuterVal {
    type WitnessVariable = Felt<OuterVal>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        builder.witness_felt()
    }

    fn write(&self, witness: &mut Witness<C>) {
        witness.felts.push(*self);
    }
}

impl Witnessable<C> for OuterChallenge {
    type WitnessVariable = Ext<OuterVal, OuterChallenge>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        builder.witness_ext()
    }

    fn write(&self, witness: &mut Witness<C>) {
        witness.exts.push(*self);
    }
}

trait VectorWitnessable<C: Config>: Witnessable<C> {}
impl VectorWitnessable<C> for Bn254Fr {}
impl VectorWitnessable<C> for OuterVal {}
impl VectorWitnessable<C> for OuterChallenge {}
impl VectorWitnessable<C> for Vec<OuterVal> {}
impl VectorWitnessable<C> for Vec<OuterChallenge> {}
impl VectorWitnessable<C> for Vec<Vec<OuterVal>> {}

impl<I: VectorWitnessable<C>> Witnessable<C> for Vec<I> {
    type WitnessVariable = Vec<I::WitnessVariable>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        self.iter().map(|x| x.read(builder)).collect()
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.iter().for_each(|x| x.write(witness));
    }
}

impl Witnessable<C> for OuterDigest {
    type WitnessVariable = OuterDigestVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        [builder.witness_var()]
    }

    fn write(&self, witness: &mut Witness<C>) {
        witness.vars.push(self[0]);
    }
}
impl VectorWitnessable<C> for OuterDigest {}

impl Witnessable<C> for ShardCommitment<OuterDigest> {
    type WitnessVariable = ShardCommitment<OuterDigestVariable<C>>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let main_commit = self.main_commit.read(builder);
        let permutation_commit = self.permutation_commit.read(builder);
        let quotient_commit = self.quotient_commit.read(builder);
        ShardCommitment { main_commit, permutation_commit, quotient_commit }
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.main_commit.write(witness);
        self.permutation_commit.write(witness);
        self.quotient_commit.write(witness);
    }
}

impl Witnessable<C> for AirOpenedValues<OuterChallenge> {
    type WitnessVariable = AirOpenedValuesVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let local = self.local.read(builder);
        let next = self.next.read(builder);
        AirOpenedValuesVariable { local, next }
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.local.write(witness);
        self.next.write(witness);
    }
}

impl Witnessable<C> for ChipOpenedValues<OuterChallenge> {
    type WitnessVariable = ChipOpenedValuesVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let preprocessed = self.preprocessed.read(builder);
        let main = self.main.read(builder);
        let permutation = self.permutation.read(builder);
        let quotient = self.quotient.read(builder);
        let cumulative_sum = self.cumulative_sum.read(builder);
        let log_degree = self.log_degree;
        ChipOpenedValuesVariable {
            preprocessed,
            main,
            permutation,
            quotient,
            cumulative_sum,
            log_degree,
        }
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.preprocessed.write(witness);
        self.main.write(witness);
        self.permutation.write(witness);
        self.quotient.write(witness);
        self.cumulative_sum.write(witness);
    }
}
impl VectorWitnessable<C> for ChipOpenedValues<OuterChallenge> {}

impl Witnessable<C> for ShardOpenedValues<OuterChallenge> {
    type WitnessVariable = RecursionShardOpenedValuesVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let chips = self.chips.read(builder);
        RecursionShardOpenedValuesVariable { chips }
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.chips.write(witness);
    }
}

impl Witnessable<C> for OuterBatchOpening {
    type WitnessVariable = BatchOpeningVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let opened_values = self
            .opened_values
            .read(builder)
            .into_iter()
            .map(|a| a.into_iter().map(|b| vec![b]).collect())
            .collect();
        let opening_proof = self.opening_proof.read(builder);
        BatchOpeningVariable { opened_values, opening_proof }
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.opened_values.write(witness);
        self.opening_proof.write(witness);
    }
}
impl VectorWitnessable<C> for OuterBatchOpening {}
impl VectorWitnessable<C> for Vec<OuterBatchOpening> {}

impl Witnessable<C> for OuterCommitPhaseStep {
    type WitnessVariable = FriCommitPhaseProofStepVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let sibling_value = self.sibling_value.read(builder);
        let opening_proof = self.opening_proof.read(builder);
        FriCommitPhaseProofStepVariable { sibling_value, opening_proof }
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.sibling_value.write(witness);
        self.opening_proof.write(witness);
    }
}
impl VectorWitnessable<C> for OuterCommitPhaseStep {}

impl Witnessable<C> for OuterQueryProof {
    type WitnessVariable = FriQueryProofVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let commit_phase_openings = self.commit_phase_openings.read(builder);
        FriQueryProofVariable { commit_phase_openings }
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.commit_phase_openings.write(witness);
    }
}
impl VectorWitnessable<C> for OuterQueryProof {}

impl Witnessable<C> for OuterFriProof {
    type WitnessVariable = FriProofVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let commit_phase_commits = self
            .commit_phase_commits
            .iter()
            .map(|commit| {
                let commit: OuterDigest = (*commit).into();
                commit.read(builder)
            })
            .collect();
        let query_proofs = self.query_proofs.read(builder);
        let final_poly = self.final_poly.read(builder);
        let pow_witness = self.pow_witness.read(builder);
        FriProofVariable { commit_phase_commits, query_proofs, final_poly, pow_witness }
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.commit_phase_commits.iter().for_each(|commit| {
            let commit: OuterDigest = (*commit).into();
            commit.write(witness)
        });
        self.query_proofs.write(witness);
        self.final_poly.write(witness);
        self.pow_witness.write(witness);
    }
}

impl Witnessable<C> for OuterPcsProof {
    type WitnessVariable = TwoAdicPcsProofVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let fri_proof = self.fri_proof.read(builder);
        let query_openings = self.query_openings.read(builder);
        TwoAdicPcsProofVariable { fri_proof, query_openings }
    }

    fn write(&self, witness: &mut Witness<C>) {
        self.fri_proof.write(witness);
        self.query_openings.write(witness);
    }
}

impl Witnessable<C> for ShardProof<BabyBearPoseidon2Outer> {
    type WitnessVariable = RecursionShardProofVariable<C>;

    fn read(&self, builder: &mut Builder<C>) -> Self::WitnessVariable {
        let main_commit: OuterDigest = self.commitment.main_commit.into();
        let permutation_commit: OuterDigest = self.commitment.permutation_commit.into();
        let quotient_commit: OuterDigest = self.commitment.quotient_commit.into();
        let commitment = ShardCommitment {
            main_commit: main_commit.read(builder),
            permutation_commit: permutation_commit.read(builder),
            quotient_commit: quotient_commit.read(builder),
        };
        let opened_values = self.opened_values.read(builder);
        let opening_proof = self.opening_proof.read(builder);
        let public_values = self.public_values.read(builder);
        let public_values = builder.vec(public_values);

        RecursionShardProofVariable { commitment, opened_values, opening_proof, public_values }
    }

    fn write(&self, witness: &mut Witness<C>) {
        let main_commit: OuterDigest = self.commitment.main_commit.into();
        let permutation_commit: OuterDigest = self.commitment.permutation_commit.into();
        let quotient_commit: OuterDigest = self.commitment.quotient_commit.into();
        main_commit.write(witness);
        permutation_commit.write(witness);
        quotient_commit.write(witness);
        self.opened_values.write(witness);
        self.opening_proof.write(witness);
        self.public_values.write(witness);
    }
}

#[cfg(test)]
mod tests {
    use p3_baby_bear::BabyBear;
    use p3_bn254_fr::Bn254Fr;
    use p3_field::AbstractField;
    use sp1_recursion_compiler::{
        config::OuterConfig,
        constraints::ConstraintCompiler,
        ir::{Builder, ExtConst, Witness},
    };
    use sp1_recursion_core::stark::config::OuterChallenge;
    use sp1_recursion_gnark_ffi::PlonkBn254Prover;

    #[test]
    fn test_witness_simple() {
        let mut builder = Builder::<OuterConfig>::default();
        let a = builder.witness_var();
        let b = builder.witness_var();
        builder.assert_var_eq(a, Bn254Fr::one());
        builder.assert_var_eq(b, Bn254Fr::two());
        builder.print_v(a);
        builder.print_v(b);

        let a = builder.witness_felt();
        let b = builder.witness_felt();
        builder.assert_felt_eq(a, BabyBear::one());
        builder.assert_felt_eq(b, BabyBear::two());
        builder.print_f(a);
        builder.print_f(b);

        let a = builder.witness_ext();
        let b = builder.witness_ext();
        builder.assert_ext_eq(a, OuterChallenge::one().cons());
        builder.assert_ext_eq(b, OuterChallenge::two().cons());
        builder.print_e(a);
        builder.print_e(b);

        let mut backend = ConstraintCompiler::<OuterConfig>::default();
        let constraints = backend.emit(builder.into_operations());
        PlonkBn254Prover::test::<OuterConfig>(
            constraints,
            Witness {
                vars: vec![Bn254Fr::one(), Bn254Fr::two()],
                felts: vec![BabyBear::one(), BabyBear::two()],
                exts: vec![OuterChallenge::one(), OuterChallenge::two()],
                vkey_hash: Bn254Fr::one(),
                commited_values_digest: Bn254Fr::one(),
            },
        );
    }
}