-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathconstraints.rs
308 lines (278 loc) · 9.56 KB
/
constraints.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
use ark_r1cs_std::prelude::*;
use ark_relations::r1cs::{Namespace, SynthesisError};
use crate::encryption::elgamal::{
Ciphertext, ElGamal, Parameters, Plaintext, PublicKey, Randomness,
};
use crate::encryption::AsymmetricEncryptionGadget;
use ark_ec::CurveGroup;
use ark_ff::{
fields::{Field, PrimeField},
Zero,
};
use ark_serialize::CanonicalSerialize;
use ark_std::{borrow::Borrow, marker::PhantomData, vec::Vec};
pub type ConstraintF<C> = <<C as CurveGroup>::BaseField as Field>::BasePrimeField;
#[derive(Clone, Debug)]
pub struct RandomnessVar<F: Field>(Vec<UInt8<F>>);
impl<C, F> AllocVar<Randomness<C>, F> for RandomnessVar<F>
where
C: CurveGroup,
F: PrimeField,
{
fn new_variable<T: Borrow<Randomness<C>>>(
cs: impl Into<Namespace<F>>,
f: impl FnOnce() -> Result<T, SynthesisError>,
mode: AllocationMode,
) -> Result<Self, SynthesisError> {
let mut r = Vec::new();
let _ = &f()
.map(|b| b.borrow().0)
.unwrap_or(C::ScalarField::zero())
.serialize_compressed(&mut r)
.unwrap();
match mode {
AllocationMode::Constant => Ok(Self(UInt8::constant_vec(&r))),
AllocationMode::Input => UInt8::new_input_vec(cs, &r).map(Self),
AllocationMode::Witness => UInt8::new_witness_vec(cs, &r).map(Self),
}
}
}
#[derive(Derivative)]
#[derivative(Clone(bound = "C: CurveGroup, GG: CurveVar<C, ConstraintF<C>>"))]
pub struct ParametersVar<C: CurveGroup, GG: CurveVar<C, ConstraintF<C>>>
where
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
{
generator: GG,
#[doc(hidden)]
_curve: PhantomData<C>,
}
impl<C, GG> AllocVar<Parameters<C>, ConstraintF<C>> for ParametersVar<C, GG>
where
C: CurveGroup,
GG: CurveVar<C, ConstraintF<C>>,
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
{
fn new_variable<T: Borrow<Parameters<C>>>(
cs: impl Into<Namespace<ConstraintF<C>>>,
f: impl FnOnce() -> Result<T, SynthesisError>,
mode: AllocationMode,
) -> Result<Self, SynthesisError> {
let generator = GG::new_variable(cs, || f().map(|g| g.borrow().generator), mode)?;
Ok(Self {
generator,
_curve: PhantomData,
})
}
}
#[derive(Derivative)]
#[derivative(Clone(bound = "C: CurveGroup, GG: CurveVar<C, ConstraintF<C>>"))]
pub struct PlaintextVar<C: CurveGroup, GG: CurveVar<C, ConstraintF<C>>>
where
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
{
pub plaintext: GG,
#[doc(hidden)]
_curve: PhantomData<C>,
}
impl<C, GG> AllocVar<Plaintext<C>, ConstraintF<C>> for PlaintextVar<C, GG>
where
C: CurveGroup,
GG: CurveVar<C, ConstraintF<C>>,
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
{
fn new_variable<T: Borrow<Plaintext<C>>>(
cs: impl Into<Namespace<ConstraintF<C>>>,
f: impl FnOnce() -> Result<T, SynthesisError>,
mode: AllocationMode,
) -> Result<Self, SynthesisError> {
let plaintext = GG::new_variable(cs, f, mode)?;
Ok(Self {
plaintext,
_curve: PhantomData,
})
}
}
#[derive(Derivative)]
#[derivative(Clone(bound = "C: CurveGroup, GG: CurveVar<C, ConstraintF<C>>"))]
pub struct PublicKeyVar<C: CurveGroup, GG: CurveVar<C, ConstraintF<C>>>
where
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
{
pub pk: GG,
#[doc(hidden)]
_curve: PhantomData<C>,
}
impl<C, GG> AllocVar<PublicKey<C>, ConstraintF<C>> for PublicKeyVar<C, GG>
where
C: CurveGroup,
GG: CurveVar<C, ConstraintF<C>>,
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
{
fn new_variable<T: Borrow<PublicKey<C>>>(
cs: impl Into<Namespace<ConstraintF<C>>>,
f: impl FnOnce() -> Result<T, SynthesisError>,
mode: AllocationMode,
) -> Result<Self, SynthesisError> {
let pk = GG::new_variable(cs, f, mode)?;
Ok(Self {
pk,
_curve: PhantomData,
})
}
}
#[derive(Derivative, Debug)]
#[derivative(Clone(bound = "C: CurveGroup, GG: CurveVar<C, ConstraintF<C>>"))]
pub struct OutputVar<C: CurveGroup, GG: CurveVar<C, ConstraintF<C>>>
where
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
{
pub c1: GG,
pub c2: GG,
#[doc(hidden)]
_curve: PhantomData<C>,
}
impl<C, GG> AllocVar<Ciphertext<C>, ConstraintF<C>> for OutputVar<C, GG>
where
C: CurveGroup,
GG: CurveVar<C, ConstraintF<C>>,
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
{
fn new_variable<T: Borrow<Ciphertext<C>>>(
cs: impl Into<Namespace<ConstraintF<C>>>,
f: impl FnOnce() -> Result<T, SynthesisError>,
mode: AllocationMode,
) -> Result<Self, SynthesisError> {
let ns = cs.into();
let cs = ns.cs();
let prep = f().map(|g| *g.borrow());
let c1 = GG::new_variable(cs.clone(), || prep.map(|g| g.borrow().0), mode)?;
let c2 = GG::new_variable(cs.clone(), || prep.map(|g| g.borrow().1), mode)?;
Ok(Self {
c1,
c2,
_curve: PhantomData,
})
}
}
impl<C, GC> EqGadget<ConstraintF<C>> for OutputVar<C, GC>
where
C: CurveGroup,
GC: CurveVar<C, ConstraintF<C>>,
for<'a> &'a GC: GroupOpsBounds<'a, C, GC>,
{
#[inline]
fn is_eq(&self, other: &Self) -> Result<Boolean<ConstraintF<C>>, SynthesisError> {
self.c1.is_eq(&other.c1)?.and(&self.c2.is_eq(&other.c2)?)
}
}
pub struct ElGamalEncGadget<C: CurveGroup, GG: CurveVar<C, ConstraintF<C>>>
where
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
{
#[doc(hidden)]
_curve: PhantomData<*const C>,
_group_var: PhantomData<*const GG>,
}
impl<C, GG> AsymmetricEncryptionGadget<ElGamal<C>, ConstraintF<C>> for ElGamalEncGadget<C, GG>
where
C: CurveGroup,
GG: CurveVar<C, ConstraintF<C>>,
for<'a> &'a GG: GroupOpsBounds<'a, C, GG>,
ConstraintF<C>: PrimeField,
{
type OutputVar = OutputVar<C, GG>;
type ParametersVar = ParametersVar<C, GG>;
type PlaintextVar = PlaintextVar<C, GG>;
type PublicKeyVar = PublicKeyVar<C, GG>;
type RandomnessVar = RandomnessVar<ConstraintF<C>>;
fn encrypt(
parameters: &Self::ParametersVar,
message: &Self::PlaintextVar,
randomness: &Self::RandomnessVar,
public_key: &Self::PublicKeyVar,
) -> Result<Self::OutputVar, SynthesisError> {
// flatten randomness to little-endian bit vector
let randomness = randomness
.0
.iter()
.flat_map(|b| b.to_bits_le().unwrap())
.collect::<Vec<_>>();
// compute s = randomness*pk
let s = public_key.pk.clone().scalar_mul_le(randomness.iter())?;
// compute c1 = randomness*generator
let c1 = parameters
.generator
.clone()
.scalar_mul_le(randomness.iter())?;
// compute c2 = m + s
let c2 = message.plaintext.clone() + s;
Ok(Self::OutputVar {
c1,
c2,
_curve: PhantomData,
})
}
}
#[cfg(test)]
mod test {
use crate::encryption::constraints::AsymmetricEncryptionGadget;
use ark_std::{test_rng, UniformRand};
use ark_ed_on_bls12_381::{constraints::EdwardsVar, EdwardsProjective as JubJub, Fq};
use crate::encryption::elgamal::{constraints::ElGamalEncGadget, ElGamal, Randomness};
use crate::encryption::AsymmetricEncryptionScheme;
use ark_r1cs_std::prelude::*;
use ark_relations::r1cs::ConstraintSystem;
#[test]
fn test_elgamal_gadget() {
let rng = &mut test_rng();
type MyEnc = ElGamal<JubJub>;
type MyGadget = ElGamalEncGadget<JubJub, EdwardsVar>;
// compute primitive result
let parameters = MyEnc::setup(rng).unwrap();
let (pk, _) = MyEnc::keygen(¶meters, rng).unwrap();
let msg = JubJub::rand(rng).into();
let randomness = Randomness::rand(rng);
let primitive_result = MyEnc::encrypt(¶meters, &pk, &msg, &randomness).unwrap();
// construct constraint system
let cs = ConstraintSystem::<Fq>::new_ref();
let randomness_var =
<MyGadget as AsymmetricEncryptionGadget<MyEnc, Fq>>::RandomnessVar::new_witness(
ark_relations::ns!(cs, "gadget_randomness"),
|| Ok(&randomness),
)
.unwrap();
let parameters_var =
<MyGadget as AsymmetricEncryptionGadget<MyEnc, Fq>>::ParametersVar::new_constant(
ark_relations::ns!(cs, "gadget_parameters"),
¶meters,
)
.unwrap();
let msg_var =
<MyGadget as AsymmetricEncryptionGadget<MyEnc, Fq>>::PlaintextVar::new_witness(
ark_relations::ns!(cs, "gadget_message"),
|| Ok(&msg),
)
.unwrap();
let pk_var =
<MyGadget as AsymmetricEncryptionGadget<MyEnc, Fq>>::PublicKeyVar::new_witness(
ark_relations::ns!(cs, "gadget_public_key"),
|| Ok(&pk),
)
.unwrap();
// use gadget
let result_var =
MyGadget::encrypt(¶meters_var, &msg_var, &randomness_var, &pk_var).unwrap();
// check that result equals expected ciphertext in the constraint system
let expected_var =
<MyGadget as AsymmetricEncryptionGadget<MyEnc, Fq>>::OutputVar::new_input(
ark_relations::ns!(cs, "gadget_expected"),
|| Ok(&primitive_result),
)
.unwrap();
expected_var.enforce_equal(&result_var).unwrap();
assert_eq!(primitive_result.0, result_var.c1.value().unwrap());
assert_eq!(primitive_result.1, result_var.c2.value().unwrap());
assert!(cs.is_satisfied().unwrap());
}
}