arnaucube
arnaucube/ethdos-foldPublic Self-hosted repository
ethdos-fold/src/fcircuit.rs
src/fcircuit.rsRaw
  1//! This file contains the FCircuit (Sonobe's trait) implementation for the ETHdos logic.
  2use ark_crypto_primitives::sponge::{
  3    constraints::CryptographicSpongeVar,
  4    poseidon::{constraints::PoseidonSpongeVar, PoseidonConfig},
  5    Absorb,
  6};
  7use ark_ec::CurveGroup;
  8use ark_ff::{Field, PrimeField};
  9use ark_r1cs_std::prelude::CurveVar;
 10use ark_r1cs_std::{
 11    boolean::Boolean,
 12    eq::EqGadget,
 13    fields::{fp::FpVar, FieldVar},
 14};
 15use ark_relations::r1cs::{ConstraintSystemRef, SynthesisError};
 16use ark_std::marker::PhantomData;
 17use std::fmt::Debug;
 18
 19use arkeddsa::constraints::verify;
 20use folding_schemes::{frontend::FCircuit, Error};
 21
 22use crate::signature::{SigPk, SigPkVar};
 23
 24pub type CF<C> = <<C as CurveGroup>::BaseField as Field>::BasePrimeField;
 25
 26/// Test circuit to be folded
 27#[derive(Clone, Debug)]
 28pub struct EthDosCircuit<F: PrimeField, C: CurveGroup, GC: CurveVar<C, F>> {
 29    _c: PhantomData<C>,
 30    _gc: PhantomData<GC>,
 31    config: PoseidonConfig<F>,
 32}
 33impl<F: PrimeField, C: CurveGroup, GC: CurveVar<C, F>> FCircuit<F> for EthDosCircuit<F, C, GC>
 34where
 35    F: Absorb,
 36    C: CurveGroup<BaseField = F>,
 37{
 38    type Params = PoseidonConfig<F>;
 39    type ExternalInputs = SigPk<C>;
 40    type ExternalInputsVar = SigPkVar<C, GC>;
 41
 42    fn new(config: Self::Params) -> Result<Self, Error> {
 43        Ok(Self {
 44            _c: PhantomData,
 45            _gc: PhantomData,
 46            config,
 47        })
 48    }
 49    fn state_len(&self) -> usize {
 50        5
 51    }
 52    // This method defines the logic that is done in-circuit at each folding step
 53    fn generate_step_constraints(
 54        &self,
 55        cs: ConstraintSystemRef<F>,
 56        _i: usize,
 57        z_i: Vec<FpVar<F>>,
 58        external_inputs: Self::ExternalInputsVar,
 59    ) -> Result<Vec<FpVar<F>>, SynthesisError> {
 60        // get the values from the state, where: state = [ pk_0, pk_i, i]
 61        let pk_0_x = z_i[0].clone();
 62        let pk_0_y = z_i[1].clone();
 63        let pk_i_x = z_i[2].clone();
 64        let pk_i_y = z_i[3].clone();
 65        let mut degree = z_i[4].clone();
 66
 67        // get the 'pk_i_hashed' value, which is the hash of the pk_i, and is the value that has
 68        // been signed by the new public key (pk_i+1)
 69        let mut poseidon = PoseidonSpongeVar::new(cs.clone(), &self.config);
 70        poseidon.absorb(&vec![pk_i_x, pk_i_y])?;
 71        let h = poseidon.squeeze_field_elements(1)?;
 72        let pk_i_hashed = h
 73            .first()
 74            .ok_or(ark_relations::r1cs::SynthesisError::Unsatisfiable)?;
 75
 76        // check that the last signer's public key (pk_i) hashed (=pk_i_hashed) is signed by the
 77        // new signer public key (pk_i+1)
 78        let res = verify::<C, GC>(
 79            cs.clone(),
 80            self.config.clone(),
 81            external_inputs.pk.clone(), // pk_{i+1}
 82            (external_inputs.sig_r, external_inputs.sig_s),
 83            pk_i_hashed.clone(),
 84        )?;
 85        res.enforce_equal(&Boolean::<F>::TRUE)?;
 86
 87        // increment the degree
 88        degree = degree.clone() + FpVar::<F>::one();
 89
 90        // return the new IVC state, where we place the pk_{i+1} at the place where previously had
 91        // the pk_i, together with the new updated degree of distance value
 92        let pk_i1_xy = external_inputs.pk.to_constraint_field()?;
 93        Ok([vec![pk_0_x, pk_0_y], pk_i1_xy, vec![degree]].concat())
 94    }
 95}
 96
 97#[cfg(test)]
 98pub mod tests {
 99    use super::*;
100    use ark_bn254::Fr;
101    use ark_ec::AffineRepr;
102    use ark_r1cs_std::{alloc::AllocVar, R1CSVar};
103    use ark_relations::r1cs::ConstraintSystem;
104    use ark_std::Zero;
105    use rand::rngs::OsRng;
106
107    use crate::signature::{gen_signatures, hash_pk};
108    use arkeddsa::ed_on_bn254_twist::{constraints::EdwardsVar, EdwardsProjective};
109    use folding_schemes::transcript::poseidon::poseidon_canonical_config;
110
111    #[test]
112    fn test_sig() {
113        let mut rng = OsRng;
114        let poseidon_config = poseidon_canonical_config::<Fr>();
115
116        const N: usize = 1;
117        let ext_inps = gen_signatures::<OsRng, EdwardsProjective>(&mut rng, &poseidon_config, 1);
118        let e = ext_inps[0].clone();
119
120        let msg = hash_pk(&poseidon_config, e.pk);
121
122        e.pk.verify(&poseidon_config, &msg, &e.sig).unwrap();
123    }
124
125    fn ensure_fcircuit_trait<FC: FCircuit<Fr>>(params: FC::Params) {
126        let _ = FC::new(params);
127    }
128
129    // test to check that the Sha256FCircuit computes the same values inside and outside the circuit
130    #[test]
131    fn test_fcircuit() {
132        let mut rng = rand::rngs::OsRng;
133        let poseidon_config = poseidon_canonical_config::<Fr>();
134
135        let pks_sigs = gen_signatures::<OsRng, EdwardsProjective>(&mut rng, &poseidon_config, 1);
136
137        // here `Fr` is the BN254::G1::Fr = ed_on_bn254_twist::EdwardsProjective::Fq
138        let cs = ConstraintSystem::<Fr>::new_ref();
139
140        type FC = EthDosCircuit<Fr, EdwardsProjective, EdwardsVar>;
141        ensure_fcircuit_trait::<FC>(poseidon_config.clone());
142
143        let circuit = FC::new(poseidon_config).unwrap();
144        let xy: (Fr, Fr) = pks_sigs[0].pk.0.xy().unwrap();
145        let pk0 = vec![xy.0, xy.1];
146        let z_i: Vec<Fr> = vec![pk0.clone(), pk0, vec![Fr::zero()]].concat();
147
148        let external_inputs_var =
149            SigPkVar::<EdwardsProjective, EdwardsVar>::new_witness(cs.clone(), || Ok(pks_sigs[0]))
150                .unwrap();
151
152        let z_iVar = Vec::<FpVar<Fr>>::new_witness(cs.clone(), || Ok(z_i)).unwrap();
153        let computed_z_i1Var = circuit
154            .generate_step_constraints(cs.clone(), 0, z_iVar.clone(), external_inputs_var)
155            .unwrap();
156        // check that the degree (in the last state) is 1, the amount of signatures verified
157        assert_eq!(computed_z_i1Var.value().unwrap()[4], Fr::from(1_u32));
158        assert!(cs.is_satisfied().unwrap());
159        dbg!(cs.num_constraints());
160        dbg!(&computed_z_i1Var.value().unwrap());
161    }
162}