jf_plonk/circuit/
transcript.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
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
// Copyright (c) 2022 Espresso Systems (espressosys.com)
// This file is part of the Jellyfish library.

// You should have received a copy of the MIT License
// along with the Jellyfish library. If not, see <https://mit-license.org/>.

//! Implementing *native* circuit for rescue transcript

use super::plonk_verifier::*;
use ark_ec::pairing::Pairing;
use ark_ff::PrimeField;
use ark_std::{string::ToString, vec::Vec};
use core::marker::PhantomData;
use jf_relation::{
    gadgets::{
        ecc::{PointVariable, SWToTEConParam},
        ultraplonk::mod_arith::FpElemVar,
    },
    Circuit,
    CircuitError::{self, ParameterError},
    PlonkCircuit, Variable,
};
use jf_rescue::{gadgets::RescueNativeGadget, RescueParameter, STATE_SIZE};

/// Struct of variables representing a Rescue transcript type, including
/// `STATE_SIZE` variables for the state, and a vector of variables for
/// the transcript.
pub struct RescueTranscriptVar<F: RescueParameter> {
    transcript_var: Vec<Variable>,
    state_var: [Variable; STATE_SIZE],
    _phantom: PhantomData<F>,
}

impl<F> RescueTranscriptVar<F>
where
    F: RescueParameter + SWToTEConParam,
{
    /// create a new RescueTranscriptVar for a given circuit.
    pub(crate) fn new(circuit: &mut PlonkCircuit<F>) -> Self {
        Self {
            transcript_var: Vec::new(),
            state_var: [circuit.zero(); STATE_SIZE],
            _phantom: PhantomData,
        }
    }

    // append the verification key and the public input
    pub(crate) fn append_vk_and_pub_input_vars<E: Pairing<BaseField = F>>(
        &mut self,
        circuit: &mut PlonkCircuit<F>,
        vk_var: &VerifyingKeyVar<E>,
        pub_input: &[FpElemVar<F>],
    ) -> Result<(), CircuitError> {
        // to enable a more efficient verifier circuit, we remove
        // the following messages (c.f. merlin transcript)
        //  - field_size_in_bits
        //  - domain size
        //  - number of inputs
        //  - wire subsets separators

        // selector commitments
        for com in vk_var.selector_comms.iter() {
            // the commitment vars are already in TE form
            self.transcript_var.push(com.get_x());
            self.transcript_var.push(com.get_y());
        }
        // sigma commitments
        for com in vk_var.sigma_comms.iter() {
            // the commitment vars are already in TE form
            self.transcript_var.push(com.get_x());
            self.transcript_var.push(com.get_y());
        }
        // public input
        for e in pub_input {
            let pub_var = e.convert_to_var(circuit)?;
            self.transcript_var.push(pub_var)
        }
        Ok(())
    }

    // Append the variable to the transcript.
    // For efficiency purpose, label is not used for rescue FS.
    pub(crate) fn append_variable(
        &mut self,
        _label: &'static [u8],
        var: &Variable,
    ) -> Result<(), CircuitError> {
        self.transcript_var.push(*var);

        Ok(())
    }

    // Append the message variables to the transcript.
    // For efficiency purpose, label is not used for rescue FS.
    pub(crate) fn append_message_vars(
        &mut self,
        _label: &'static [u8],
        msg_vars: &[Variable],
    ) -> Result<(), CircuitError> {
        for e in msg_vars.iter() {
            self.append_variable(_label, e)?;
        }

        Ok(())
    }

    // Append a commitment variable (in the form of PointVariable) to the
    // transcript. The caller needs to make sure that the commitment is
    // already converted to TE form before generating the variables.
    // For efficiency purpose, label is not used for rescue FS.
    pub(crate) fn append_commitment_var(
        &mut self,
        _label: &'static [u8],
        poly_comm_var: &PointVariable,
    ) -> Result<(), CircuitError> {
        // push the x and y coordinate of comm to the transcript
        self.transcript_var.push(poly_comm_var.get_x());
        self.transcript_var.push(poly_comm_var.get_y());

        Ok(())
    }

    // Append  a slice of commitment variables (in the form of PointVariable) to the
    // The caller needs to make sure that the commitment is
    // already converted to TE form before generating the variables.
    // transcript For efficiency purpose, label is not used for rescue FS.
    pub(crate) fn append_commitments_vars(
        &mut self,
        _label: &'static [u8],
        poly_comm_vars: &[PointVariable],
    ) -> Result<(), CircuitError> {
        for poly_comm_var in poly_comm_vars.iter() {
            // push the x and y coordinate of comm to the transcript
            self.transcript_var.push(poly_comm_var.get_x());
            self.transcript_var.push(poly_comm_var.get_y());
        }
        Ok(())
    }

    // Append the proof evaluation to the transcript
    pub(crate) fn append_proof_evaluations_vars(
        &mut self,
        circuit: &mut PlonkCircuit<F>,
        evals: &ProofEvaluationsVar<F>,
    ) -> Result<(), CircuitError> {
        for e in &evals.wires_evals {
            let tmp = e.convert_to_var(circuit)?;
            self.transcript_var.push(tmp);
        }
        for e in &evals.wire_sigma_evals {
            let tmp = e.convert_to_var(circuit)?;
            self.transcript_var.push(tmp);
        }
        let tmp = evals.perm_next_eval.convert_to_var(circuit)?;
        self.transcript_var.push(tmp);
        Ok(())
    }

    // generate the challenge for the current transcript
    // and append it to the transcript
    // For efficiency purpose, label is not used for rescue FS.
    // Note that this function currently only supports bls12-377
    // curve due to its decomposition method.
    //
    // `_label` is omitted for efficiency.
    pub(crate) fn get_challenge_var<E>(
        &mut self,
        _label: &'static [u8],
        circuit: &mut PlonkCircuit<F>,
    ) -> Result<Variable, CircuitError>
    where
        E: Pairing,
    {
        if !circuit.support_lookup() {
            return Err(ParameterError("does not support range table".to_string()));
        }

        if E::ScalarField::MODULUS_BIT_SIZE != 253 || E::BaseField::MODULUS_BIT_SIZE != 377 {
            return Err(ParameterError(
                "Curve Parameter does not support for rescue transcript circuit".to_string(),
            ));
        }

        // ==================================
        // This algorithm takes in 3 steps
        // 1. state: [F: STATE_SIZE] = hash(state|transcript)
        // 2. challenge = state[0] in Fr
        // 3. transcript = vec![]
        // ==================================

        // step 1. state: [F: STATE_SIZE] = hash(state|transcript)
        let input_var = [self.state_var.as_ref(), self.transcript_var.as_ref()].concat();
        let res_var =
            RescueNativeGadget::<F>::rescue_sponge_with_padding(circuit, &input_var, STATE_SIZE)
                .unwrap();
        let out_var = res_var[0];

        // step 2. challenge = state[0] in Fr
        let challenge_var = circuit.truncate(out_var, 248)?;

        // 3. transcript = vec![challenge]
        // finish and update the states
        self.state_var.copy_from_slice(&res_var[0..STATE_SIZE]);
        self.transcript_var = Vec::new();

        Ok(challenge_var)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        proof_system::structs::VerifyingKey,
        transcript::{PlonkTranscript, RescueTranscript},
    };
    use ark_bls12_377::Bls12_377;
    use ark_ec::{
        short_weierstrass::{Affine, SWCurveConfig},
        AffineRepr, CurveGroup,
    };
    use ark_std::{format, vec, UniformRand};
    use jf_pcs::prelude::{Commitment, UnivariateVerifierParam};
    use jf_relation::gadgets::ecc::TEPoint;
    use jf_utils::{bytes_to_field_elements, field_switching, test_rng};

    const RANGE_BIT_LEN_FOR_TEST: usize = 16;
    #[test]
    fn test_rescue_transcript_challenge_circuit() {
        test_rescue_transcript_challenge_circuit_helper::<Bls12_377, _, _>()
    }
    fn test_rescue_transcript_challenge_circuit_helper<E, F, P>()
    where
        E: Pairing<BaseField = F, G1Affine = Affine<P>>,
        F: RescueParameter + SWToTEConParam,
        P: SWCurveConfig<BaseField = F>,
    {
        let mut circuit = PlonkCircuit::<F>::new_ultra_plonk(RANGE_BIT_LEN_FOR_TEST);

        let label = "testing".as_ref();

        let mut transcript_var = RescueTranscriptVar::new(&mut circuit);
        let mut transcript = RescueTranscript::<F>::new(label);

        for _ in 0..10 {
            for i in 0..10 {
                let msg = format!("message {}", i);
                let vals = bytes_to_field_elements(msg.as_bytes());
                let message_vars: Vec<Variable> = vals
                    .iter()
                    .map(|x| circuit.create_variable(*x).unwrap())
                    .collect();

                transcript.append_message(label, msg.as_bytes()).unwrap();

                transcript_var
                    .append_message_vars(label, &message_vars)
                    .unwrap();
            }

            let challenge = transcript.get_challenge::<E>(label).unwrap();

            let challenge_var = transcript_var
                .get_challenge_var::<E>(label, &mut circuit)
                .unwrap();

            assert_eq!(
                circuit.witness(challenge_var).unwrap().into_bigint(),
                field_switching::<_, F>(&challenge).into_bigint()
            );
        }
    }

    #[test]
    fn test_rescue_transcript_append_vk_and_input_circuit() {
        test_rescue_transcript_append_vk_and_input_circuit_helper::<Bls12_377, _, _>()
    }
    fn test_rescue_transcript_append_vk_and_input_circuit_helper<E, F, P>()
    where
        E: Pairing<BaseField = F, G1Affine = Affine<P>>,
        F: RescueParameter + SWToTEConParam,
        P: SWCurveConfig<BaseField = F>,
    {
        let mut circuit = PlonkCircuit::<F>::new_ultra_plonk(RANGE_BIT_LEN_FOR_TEST);

        let mut rng = test_rng();

        let label = "testing".as_ref();

        let mut transcript_var = RescueTranscriptVar::new(&mut circuit);
        let mut transcript = RescueTranscript::<F>::new(label);

        let g = E::G1Affine::generator();
        let h = E::G2Affine::generator();
        let beta_h = E::G2::rand(&mut rng).into_affine();
        let open_key: UnivariateVerifierParam<E> = UnivariateVerifierParam {
            g,
            h,
            beta_h,
            powers_of_h: vec![h, beta_h],
            powers_of_g: vec![g],
        };

        let dummy_vk = VerifyingKey {
            domain_size: 512,
            num_inputs: 0,
            sigma_comms: Vec::new(),
            selector_comms: Vec::new(),
            k: Vec::new(),
            open_key: open_key.clone(),
            is_merged: false,
            plookup_vk: None,
        };

        let dummy_vk_var = VerifyingKeyVar::new(&mut circuit, &dummy_vk).unwrap();

        // build challenge from transcript and check for correctness
        transcript.append_vk_and_pub_input(&dummy_vk, &[]).unwrap();
        transcript_var
            .append_vk_and_pub_input_vars::<E>(&mut circuit, &dummy_vk_var, &[])
            .unwrap();

        let challenge = transcript.get_challenge::<E>(label).unwrap();

        let challenge_var = transcript_var
            .get_challenge_var::<E>(label, &mut circuit)
            .unwrap();

        assert_eq!(
            circuit.witness(challenge_var).unwrap(),
            field_switching(&challenge)
        );

        for _ in 0..10 {
            // inputs
            let input: Vec<E::ScalarField> =
                (0..16).map(|_| E::ScalarField::rand(&mut rng)).collect();

            // sigma commitments
            let sigma_comms: Vec<Commitment<E>> = (0..42)
                .map(|_| Commitment(E::G1::rand(&mut rng).into_affine()))
                .collect();
            let mut sigma_comms_vars: Vec<PointVariable> = Vec::new();
            for e in sigma_comms.iter() {
                // convert point into TE form
                let p: TEPoint<F> = e.0.into();
                sigma_comms_vars.push(circuit.create_point_variable(p).unwrap());
            }

            // selector commitments
            let selector_comms: Vec<Commitment<E>> = (0..33)
                .map(|_| Commitment(E::G1::rand(&mut rng).into_affine()))
                .collect();
            let mut selector_comms_vars: Vec<PointVariable> = Vec::new();
            for e in selector_comms.iter() {
                // convert point into TE form
                let p: TEPoint<F> = e.0.into();
                selector_comms_vars.push(circuit.create_point_variable(p).unwrap());
            }

            // k
            let k: Vec<E::ScalarField> = (0..5).map(|_| E::ScalarField::rand(&mut rng)).collect();

            let vk = VerifyingKey {
                domain_size: 512,
                num_inputs: input.len(),
                sigma_comms,
                selector_comms,
                k,
                open_key: open_key.clone(),
                is_merged: false,
                plookup_vk: None,
            };
            let vk_var = VerifyingKeyVar::new(&mut circuit, &vk).unwrap();

            // build challenge from transcript and check for correctness
            transcript.append_vk_and_pub_input(&vk, &input).unwrap();
            let m = 128;
            let input_vars: Vec<Variable> = input
                .iter()
                .map(|&x| circuit.create_public_variable(field_switching(&x)).unwrap())
                .collect();

            let input_fp_elem_vars: Vec<FpElemVar<F>> = input_vars
                .iter()
                .map(|&x| FpElemVar::new_unchecked(&mut circuit, x, m, None).unwrap())
                .collect();
            transcript_var
                .append_vk_and_pub_input_vars::<E>(&mut circuit, &vk_var, &input_fp_elem_vars)
                .unwrap();

            let challenge = transcript.get_challenge::<E>(label).unwrap();

            let challenge_var = transcript_var
                .get_challenge_var::<E>(label, &mut circuit)
                .unwrap();

            assert_eq!(
                circuit.witness(challenge_var).unwrap(),
                field_switching(&challenge)
            );
        }
    }
}