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 super::{bool_check, ternary, UtilitiesInstructions};
use halo2_proofs::{
circuit::{AssignedCell, Chip, Layouter},
plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Selector},
poly::Rotation,
};
use pasta_curves::arithmetic::FieldExt;
use std::marker::PhantomData;
pub trait CondSwapInstructions<F: FieldExt>: UtilitiesInstructions<F> {
#[allow(clippy::type_complexity)]
fn swap(
&self,
layouter: impl Layouter<F>,
pair: (Self::Var, Option<F>),
swap: Option<bool>,
) -> Result<(Self::Var, Self::Var), Error>;
}
#[derive(Clone, Debug)]
pub struct CondSwapChip<F> {
config: CondSwapConfig,
_marker: PhantomData<F>,
}
impl<F: FieldExt> Chip<F> for CondSwapChip<F> {
type Config = CondSwapConfig;
type Loaded = ();
fn config(&self) -> &Self::Config {
&self.config
}
fn loaded(&self) -> &Self::Loaded {
&()
}
}
#[derive(Clone, Debug)]
pub struct CondSwapConfig {
q_swap: Selector,
a: Column<Advice>,
b: Column<Advice>,
a_swapped: Column<Advice>,
b_swapped: Column<Advice>,
swap: Column<Advice>,
}
#[cfg(test)]
impl CondSwapConfig {
pub(crate) fn a(&self) -> Column<Advice> {
self.a
}
}
impl<F: FieldExt> UtilitiesInstructions<F> for CondSwapChip<F> {
type Var = AssignedCell<F, F>;
}
impl<F: FieldExt> CondSwapInstructions<F> for CondSwapChip<F> {
#[allow(clippy::type_complexity)]
fn swap(
&self,
mut layouter: impl Layouter<F>,
pair: (Self::Var, Option<F>),
swap: Option<bool>,
) -> Result<(Self::Var, Self::Var), Error> {
let config = self.config();
layouter.assign_region(
|| "swap",
|mut region| {
config.q_swap.enable(&mut region, 0)?;
let a = pair.0.copy_advice(|| "copy a", &mut region, config.a, 0)?;
let b = region.assign_advice(
|| "witness b",
config.b,
0,
|| pair.1.ok_or(Error::Synthesis),
)?;
let swap_val = swap.map(|swap| F::from(swap as u64));
region.assign_advice(
|| "swap",
config.swap,
0,
|| swap_val.ok_or(Error::Synthesis),
)?;
let a_swapped = {
let a_swapped = a
.value()
.zip(b.value())
.zip(swap)
.map(|((a, b), swap)| if swap { b } else { a })
.cloned();
region.assign_advice(
|| "a_swapped",
config.a_swapped,
0,
|| a_swapped.ok_or(Error::Synthesis),
)?
};
let b_swapped = {
let b_swapped = a
.value()
.zip(b.value())
.zip(swap)
.map(|((a, b), swap)| if swap { a } else { b })
.cloned();
region.assign_advice(
|| "b_swapped",
config.b_swapped,
0,
|| b_swapped.ok_or(Error::Synthesis),
)?
};
Ok((a_swapped, b_swapped))
},
)
}
}
impl<F: FieldExt> CondSwapChip<F> {
pub fn configure(
meta: &mut ConstraintSystem<F>,
advices: [Column<Advice>; 5],
) -> CondSwapConfig {
let a = advices[0];
meta.enable_equality(a);
let q_swap = meta.selector();
let config = CondSwapConfig {
q_swap,
a,
b: advices[1],
a_swapped: advices[2],
b_swapped: advices[3],
swap: advices[4],
};
meta.create_gate("a' = b ⋅ swap + a ⋅ (1-swap)", |meta| {
let q_swap = meta.query_selector(q_swap);
let a = meta.query_advice(config.a, Rotation::cur());
let b = meta.query_advice(config.b, Rotation::cur());
let a_swapped = meta.query_advice(config.a_swapped, Rotation::cur());
let b_swapped = meta.query_advice(config.b_swapped, Rotation::cur());
let swap = meta.query_advice(config.swap, Rotation::cur());
let a_check = a_swapped - ternary(swap.clone(), b.clone(), a.clone());
let b_check = b_swapped - ternary(swap.clone(), a, b);
let bool_check = bool_check(swap);
Constraints::with_selector(
q_swap,
[
("a check", a_check),
("b check", b_check),
("swap is bool", bool_check),
],
)
});
config
}
pub fn construct(config: CondSwapConfig) -> Self {
CondSwapChip {
config,
_marker: PhantomData,
}
}
}
#[cfg(test)]
mod tests {
use super::super::UtilitiesInstructions;
use super::{CondSwapChip, CondSwapConfig, CondSwapInstructions};
use group::ff::Field;
use halo2_proofs::{
circuit::{Layouter, SimpleFloorPlanner},
dev::MockProver,
plonk::{Circuit, ConstraintSystem, Error},
};
use pasta_curves::{arithmetic::FieldExt, pallas::Base};
use rand::rngs::OsRng;
#[test]
fn cond_swap() {
#[derive(Default)]
struct MyCircuit<F: FieldExt> {
a: Option<F>,
b: Option<F>,
swap: Option<bool>,
}
impl<F: FieldExt> Circuit<F> for MyCircuit<F> {
type Config = CondSwapConfig;
type FloorPlanner = SimpleFloorPlanner;
fn without_witnesses(&self) -> Self {
Self::default()
}
fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
let advices = [
meta.advice_column(),
meta.advice_column(),
meta.advice_column(),
meta.advice_column(),
meta.advice_column(),
];
CondSwapChip::<F>::configure(meta, advices)
}
fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<F>,
) -> Result<(), Error> {
let chip = CondSwapChip::<F>::construct(config.clone());
let a = chip.load_private(layouter.namespace(|| "a"), config.a, self.a)?;
let swapped_pair = chip.swap(
layouter.namespace(|| "swap"),
(a.clone(), self.b),
self.swap,
)?;
if let Some(swap) = self.swap {
if swap {
assert_eq!(swapped_pair.0.value().unwrap(), &self.b.unwrap());
assert_eq!(swapped_pair.1.value().unwrap(), a.value().unwrap());
} else {
assert_eq!(swapped_pair.0.value().unwrap(), a.value().unwrap());
assert_eq!(swapped_pair.1.value().unwrap(), &self.b.unwrap());
}
}
Ok(())
}
}
let rng = OsRng;
{
let circuit: MyCircuit<Base> = MyCircuit {
a: Some(Base::random(rng)),
b: Some(Base::random(rng)),
swap: Some(true),
};
let prover = MockProver::<Base>::run(3, &circuit, vec![]).unwrap();
assert_eq!(prover.verify(), Ok(()));
}
{
let circuit: MyCircuit<Base> = MyCircuit {
a: Some(Base::random(rng)),
b: Some(Base::random(rng)),
swap: Some(false),
};
let prover = MockProver::<Base>::run(3, &circuit, vec![]).unwrap();
assert_eq!(prover.verify(), Ok(()));
}
}
}