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
use crate::{
    circuit::{
        cs::{RCS, WitnessCS, CS, Gate},
        lc::{Index}
    },
    core::signal::Signal,
    ff_uint::{Num, PrimeField},
};

use bit_vec::BitVec;

use bellman::{ConstraintSystem, SynthesisError};

#[cfg(feature = "borsh_support")]
use borsh::{BorshSerialize, BorshDeserialize};
#[cfg(feature = "serde_support")]
use serde::{Serialize, Deserialize};

use bellman::pairing::{CurveAffine, RawEncodable};
use std::{io::Cursor, marker::PhantomData};

pub mod engines;
#[cfg(feature = "rand_support")]
pub mod osrng;
pub mod prover;
#[cfg(feature = "rand_support")]
pub mod setup;
pub mod verifier;

pub trait Engine {
    type BE: bellman::pairing::Engine;
    type Fq: PrimeField;
    type Fr: PrimeField;
}

#[repr(transparent)]
struct BellmanCS<E: Engine, C:CS<Fr=E::Fr>>(RCS<C>, PhantomData<E>);

impl<E: Engine, C:CS<Fr=E::Fr>> BellmanCS<E,C> {
    fn new(inner:RCS<C>) -> Self {
        Self(inner, PhantomData)
    }
}

pub fn convert_lc<E: Engine>(
    lc: &[(Num<E::Fr>, Index)],
    variables_input: &[bellman::Variable],
    variables_aux: &[bellman::Variable],    
) -> bellman::LinearCombination<E::BE> {
    let mut res = Vec::with_capacity(lc.len());

    for e in lc.iter() {
        let k = num_to_bellman_fp(e.0);
        let v = match e.1 {
            Index::Input(i)=>variables_input[i],
            Index::Aux(i)=>variables_aux[i]
        };
        res.push((v, k));
    }
    bellman::LinearCombination::new(res)
}

impl<E: Engine, C:CS<Fr=E::Fr>> bellman::Circuit<E::BE> for BellmanCS<E, C> {
    fn synthesize<BCS: ConstraintSystem<E::BE>>(
        self,
        bellman_cs: &mut BCS,
    ) -> Result<(), SynthesisError> {
        let rcs = self.0;
        let cs = rcs.borrow();
        let num_input = cs.num_input();
        let num_aux = cs.num_aux();
        let num_gates = cs.num_gates();

        let mut variables_input = Vec::with_capacity(num_input);
        let mut variables_aux = Vec::with_capacity(num_aux);

        variables_input.push(BCS::one());
        for i in 1..num_input {
            let v = bellman_cs.alloc_input(
                || format!("input_{}", i),
                || cs.get_value(Index::Input(i)).map(num_to_bellman_fp).ok_or(SynthesisError::AssignmentMissing)
            ).unwrap();
            variables_input.push(v);
        }

        for i in 0..num_aux {
            let v = bellman_cs.alloc(
                || format!("aux_{}", i),
                || cs.get_value(Index::Aux(i)).map(num_to_bellman_fp).ok_or(SynthesisError::AssignmentMissing)
            ).unwrap();
            variables_aux.push(v);
        }

        
        
        for i in 0..num_gates {
            let g = cs.get_gate(i);
            bellman_cs.enforce(
                || format!("constraint {}", i),
                |_| convert_lc::<E>(&g.0, &variables_input, &variables_aux),
                |_| convert_lc::<E>(&g.1, &variables_input, &variables_aux),
                |_| convert_lc::<E>(&g.2, &variables_input, &variables_aux),
            );
        }
        Ok(())
    }
}


pub fn num_to_bellman_fp<Fx: PrimeField, Fy: bellman::pairing::ff::PrimeField>(
    from: Num<Fx>,
) -> Fy {
    let buff = from.as_mont_uint().as_inner().as_ref();

    let mut to = Fy::char();
    let to_ref = to.as_mut();

    assert!(buff.len() == to_ref.len());

    to_ref
        .iter_mut()
        .zip(buff.iter())
        .for_each(|(a, b)| *a = *b);
    Fy::from_raw_repr(to).unwrap()
}

pub fn bellman_fp_to_num<Fx: PrimeField, Fy: bellman::pairing::ff::PrimeField>(
    from: Fy,
) -> Num<Fx> {
    let from_raw = from.into_raw_repr();
    let buff = from_raw.as_ref();

    let mut to = Num::ZERO;
    let to_inner: &mut <Fx::Inner as ff_uint::Uint>::Inner = to.as_mont_uint_mut().as_inner_mut();
    let to_ref = to_inner.as_mut();
    assert!(buff.len() == to_ref.len());
    to_ref
        .iter_mut()
        .zip(buff.iter())
        .for_each(|(a, b)| *a = *b);
    to
}

pub struct Parameters<E: Engine>(bellman::groth16::Parameters<E::BE>, Vec<Gate<E::Fr>>, BitVec);

impl<E: Engine> Parameters<E> {
    pub fn get_vk(&self) -> verifier::VK<E> {
        verifier::VK::from_bellman(&self.0.vk)
    }

    pub fn get_witness_rcs(&self)->RCS<WitnessCS<E::Fr>> {
        WitnessCS::rc_new(&self.1, &self.2)
    }
}

#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct G1Point<E: Engine>(Num<E::Fq>, Num<E::Fq>);

#[cfg(feature = "borsh_support")]
impl<E: Engine> BorshSerialize for G1Point<E> {
    fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
        BorshSerialize::serialize(&self.0, writer)?;
        BorshSerialize::serialize(&self.1, writer)
    }
}

#[cfg(feature = "borsh_support")]
impl<E: Engine> BorshDeserialize for G1Point<E> {
    fn deserialize(buf: &mut &[u8]) -> std::io::Result<Self> {
        let x = BorshDeserialize::deserialize(buf)?;
        let y = BorshDeserialize::deserialize(buf)?;
        Ok(Self(x, y))
    }
}

#[cfg(feature = "borsh_support")]
impl<E: Engine> BorshSerialize for G2Point<E> {
    fn serialize<W: std::io::Write>(&self, writer: &mut W) -> std::io::Result<()> {
        BorshSerialize::serialize(&self.0.0, writer)?;
        BorshSerialize::serialize(&self.0.1, writer)?;
        BorshSerialize::serialize(&self.1.0, writer)?;
        BorshSerialize::serialize(&self.1.1, writer)
    }
}

#[cfg(feature = "borsh_support")]
impl<E: Engine> BorshDeserialize for G2Point<E> {
    fn deserialize(buf: &mut &[u8]) -> std::io::Result<Self> {
        let x_re = BorshDeserialize::deserialize(buf)?;
        let x_im = BorshDeserialize::deserialize(buf)?;
        let y_re = BorshDeserialize::deserialize(buf)?;
        let y_im = BorshDeserialize::deserialize(buf)?;
        Ok(Self((x_re, x_im), (y_re, y_im)))
    }
}

impl<E: Engine> G1Point<E> {
    pub fn to_bellman(&self) -> <E::BE as bellman::pairing::Engine>::G1Affine {
        if self.0 == Num::ZERO && self.1 == Num::ZERO {
            <E::BE as bellman::pairing::Engine>::G1Affine::zero()
        } else {
            let mut buf =
                <E::BE as bellman::pairing::Engine>::G1Affine::zero().into_raw_uncompressed_le();
            {
                let mut cur = Cursor::new(buf.as_mut());
                BorshSerialize::serialize(&self.0.to_mont_uint(), &mut cur).unwrap();
                BorshSerialize::serialize(&self.1.to_mont_uint(), &mut cur).unwrap();
            }
            <E::BE as bellman::pairing::Engine>::G1Affine::from_raw_uncompressed_le(&buf, false)
                .unwrap()
        }
    }

    pub fn from_bellman(g1: &<E::BE as bellman::pairing::Engine>::G1Affine) -> Self {
        if g1.is_zero() {
            Self(Num::ZERO, Num::ZERO)
        } else {
            let buf = g1.into_raw_uncompressed_le();
            let mut cur = buf.as_ref();
            let x = Num::from_mont_uint_unchecked(BorshDeserialize::deserialize(&mut cur).unwrap());
            let y = Num::from_mont_uint_unchecked(BorshDeserialize::deserialize(&mut cur).unwrap());
            Self(x, y)
        }
    }
}

// Complex components are listed in LE notation, X+IY
#[cfg_attr(feature = "serde_support", derive(Serialize, Deserialize))]
pub struct G2Point<E: Engine>((Num<E::Fq>, Num<E::Fq>), (Num<E::Fq>, Num<E::Fq>));

impl<E: Engine> G2Point<E> {
    pub fn to_bellman(&self) -> <E::BE as bellman::pairing::Engine>::G2Affine {
        if self.0 .0 == Num::ZERO
            && self.0 .1 == Num::ZERO
            && self.1 .0 == Num::ZERO
            && self.1 .1 == Num::ZERO
        {
            <E::BE as bellman::pairing::Engine>::G2Affine::zero()
        } else {
            let mut buf =
                <E::BE as bellman::pairing::Engine>::G2Affine::zero().into_raw_uncompressed_le();
            {
                let mut cur = Cursor::new(buf.as_mut());
                BorshSerialize::serialize(&self.0.0.to_mont_uint(), &mut cur).unwrap();
                BorshSerialize::serialize(&self.0.1.to_mont_uint(), &mut cur).unwrap();
                BorshSerialize::serialize(&self.1.0.to_mont_uint(), &mut cur).unwrap();
                BorshSerialize::serialize(&self.1.1.to_mont_uint(), &mut cur).unwrap();
            }
            <E::BE as bellman::pairing::Engine>::G2Affine::from_raw_uncompressed_le(&buf, false)
                .unwrap()
        }
    }

    pub fn from_bellman(g2: &<E::BE as bellman::pairing::Engine>::G2Affine) -> Self {
        if g2.is_zero() {
            Self((Num::ZERO, Num::ZERO), (Num::ZERO, Num::ZERO))
        } else {
            let buf = g2.into_raw_uncompressed_le();
            let mut cur = buf.as_ref();
            let x_re = Num::from_mont_uint_unchecked(BorshDeserialize::deserialize(&mut cur).unwrap());
            let x_im = Num::from_mont_uint_unchecked(BorshDeserialize::deserialize(&mut cur).unwrap());
            let y_re = Num::from_mont_uint_unchecked(BorshDeserialize::deserialize(&mut cur).unwrap());
            let y_im = Num::from_mont_uint_unchecked(BorshDeserialize::deserialize(&mut cur).unwrap());
            Self((x_re, x_im), (y_re, y_im))
        }
    }
}

#[cfg(feature = "heavy_tests")]
#[cfg(test)]
mod bellman_groth16_test {
    use super::engines::Bn256;
    use super::setup::setup;
    use super::*;
    use crate::circuit::num::CNum;
    use crate::circuit::poseidon::{c_poseidon_merkle_proof_root, CMerkleProof};
    use crate::core::signal::Signal;
    use crate::core::sizedvec::SizedVec;
    use crate::engines::bn256::Fr;
    use crate::native::poseidon::{poseidon_merkle_proof_root, MerkleProof, PoseidonParams};
    use crate::rand::{thread_rng, Rng};

    #[test]
    fn test_circuit_poseidon_merkle_root() {
        fn circuit<C:CS>(public: CNum<C>, secret: (CNum<C>, CMerkleProof<C, 32>)) {
            let poseidon_params = PoseidonParams::<C::Fr>::new(3, 8, 53);
            let res = c_poseidon_merkle_proof_root(&secret.0, &secret.1, &poseidon_params);
            res.assert_eq(&public);
        }
        let params = setup::<Bn256, _, _, _>(circuit);

        const PROOF_LENGTH: usize = 32;
        let mut rng = thread_rng();
        let poseidon_params = PoseidonParams::<Fr>::new(3, 8, 53);
        let leaf = rng.gen();
        let sibling = (0..PROOF_LENGTH)
            .map(|_| rng.gen())
            .collect::<SizedVec<_, 32>>();
        let path = (0..PROOF_LENGTH)
            .map(|_| rng.gen())
            .collect::<SizedVec<bool, 32>>();
        let proof = MerkleProof { sibling, path };
        let root = poseidon_merkle_proof_root(leaf, &proof, &poseidon_params);

        println!("BitVec length {}", params.2.len());

        let (inputs, snark_proof) = prover::prove(&params, &root, &(leaf, proof), circuit);

        let res = verifier::verify(&params.get_vk(), &snark_proof, &inputs);
        assert!(res, "Verifier result should be true");
    }
}