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
use ff::PrimeFieldBits;
use halo2_proofs::{
circuit::{AssignedCell, Region, Value},
plonk::{Advice, Column, ConstraintSystem, Constraints, Error, Selector},
poly::Rotation,
};
use super::range_check;
use pasta_curves::arithmetic::FieldExt;
use std::marker::PhantomData;
#[derive(Debug)]
pub struct RunningSum<F: FieldExt + PrimeFieldBits>(Vec<AssignedCell<F, F>>);
impl<F: FieldExt + PrimeFieldBits> std::ops::Deref for RunningSum<F> {
type Target = Vec<AssignedCell<F, F>>;
fn deref(&self) -> &Vec<AssignedCell<F, F>> {
&self.0
}
}
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub struct RunningSumConfig<F: FieldExt + PrimeFieldBits, const WINDOW_NUM_BITS: usize> {
q_range_check: Selector,
z: Column<Advice>,
_marker: PhantomData<F>,
}
impl<F: FieldExt + PrimeFieldBits, const WINDOW_NUM_BITS: usize>
RunningSumConfig<F, WINDOW_NUM_BITS>
{
pub(crate) fn q_range_check(&self) -> Selector {
self.q_range_check
}
pub fn configure(
meta: &mut ConstraintSystem<F>,
q_range_check: Selector,
z: Column<Advice>,
) -> Self {
assert!(WINDOW_NUM_BITS <= 3);
meta.enable_equality(z);
let config = Self {
q_range_check,
z,
_marker: PhantomData,
};
meta.create_gate("range check", |meta| {
let q_range_check = meta.query_selector(config.q_range_check);
let z_cur = meta.query_advice(config.z, Rotation::cur());
let z_next = meta.query_advice(config.z, Rotation::next());
let word = z_cur - z_next * F::from(1 << WINDOW_NUM_BITS);
Constraints::with_selector(q_range_check, Some(range_check(word, 1 << WINDOW_NUM_BITS)))
});
config
}
pub fn witness_decompose(
&self,
region: &mut Region<'_, F>,
offset: usize,
alpha: Value<F>,
strict: bool,
word_num_bits: usize,
num_windows: usize,
) -> Result<RunningSum<F>, Error> {
let z_0 = region.assign_advice(|| "z_0 = alpha", self.z, offset, || alpha)?;
self.decompose(region, offset, z_0, strict, word_num_bits, num_windows)
}
pub fn copy_decompose(
&self,
region: &mut Region<'_, F>,
offset: usize,
alpha: AssignedCell<F, F>,
strict: bool,
word_num_bits: usize,
num_windows: usize,
) -> Result<RunningSum<F>, Error> {
let z_0 = alpha.copy_advice(|| "copy z_0 = alpha", region, self.z, offset)?;
self.decompose(region, offset, z_0, strict, word_num_bits, num_windows)
}
fn decompose(
&self,
region: &mut Region<'_, F>,
offset: usize,
z_0: AssignedCell<F, F>,
strict: bool,
word_num_bits: usize,
num_windows: usize,
) -> Result<RunningSum<F>, Error> {
assert!(WINDOW_NUM_BITS * num_windows < word_num_bits + WINDOW_NUM_BITS);
for idx in 0..num_windows {
self.q_range_check.enable(region, offset + idx)?;
}
let words = z_0
.value()
.map(|word| super::decompose_word::<F>(word, word_num_bits, WINDOW_NUM_BITS))
.transpose_vec(num_windows);
let mut zs: Vec<AssignedCell<F, F>> = vec![z_0.clone()];
let mut z = z_0;
let two_pow_k_inv = Value::known(F::from(1 << WINDOW_NUM_BITS as u64).invert().unwrap());
for (i, word) in words.iter().enumerate() {
let z_next = {
let z_cur_val = z.value().copied();
let word = word.map(|word| F::from(word as u64));
let z_next_val = (z_cur_val - word) * two_pow_k_inv;
region.assign_advice(
|| format!("z_{:?}", i + 1),
self.z,
offset + i + 1,
|| z_next_val,
)?
};
z = z_next;
zs.push(z.clone());
}
assert_eq!(zs.len(), num_windows + 1);
if strict {
region.constrain_constant(zs.last().unwrap().cell(), F::zero())?;
}
Ok(RunningSum(zs))
}
}
#[cfg(test)]
mod tests {
use super::*;
use group::ff::{Field, PrimeField};
use halo2_proofs::{
circuit::{Layouter, SimpleFloorPlanner},
dev::{FailureLocation, MockProver, VerifyFailure},
plonk::{Any, Circuit, ConstraintSystem, Error},
};
use pasta_curves::{arithmetic::FieldExt, pallas};
use rand::rngs::OsRng;
use crate::ecc::chip::{
FIXED_BASE_WINDOW_SIZE, L_SCALAR_SHORT as L_SHORT, NUM_WINDOWS, NUM_WINDOWS_SHORT,
};
const L_BASE: usize = pallas::Base::NUM_BITS as usize;
#[test]
fn test_running_sum() {
struct MyCircuit<
F: FieldExt + PrimeFieldBits,
const WORD_NUM_BITS: usize,
const WINDOW_NUM_BITS: usize,
const NUM_WINDOWS: usize,
> {
alpha: Value<F>,
strict: bool,
}
impl<
F: FieldExt + PrimeFieldBits,
const WORD_NUM_BITS: usize,
const WINDOW_NUM_BITS: usize,
const NUM_WINDOWS: usize,
> Circuit<F> for MyCircuit<F, WORD_NUM_BITS, WINDOW_NUM_BITS, NUM_WINDOWS>
{
type Config = RunningSumConfig<F, WINDOW_NUM_BITS>;
type FloorPlanner = SimpleFloorPlanner;
fn without_witnesses(&self) -> Self {
Self {
alpha: Value::unknown(),
strict: self.strict,
}
}
fn configure(meta: &mut ConstraintSystem<F>) -> Self::Config {
let z = meta.advice_column();
let q_range_check = meta.selector();
let constants = meta.fixed_column();
meta.enable_constant(constants);
RunningSumConfig::<F, WINDOW_NUM_BITS>::configure(meta, q_range_check, z)
}
fn synthesize(
&self,
config: Self::Config,
mut layouter: impl Layouter<F>,
) -> Result<(), Error> {
layouter.assign_region(
|| "decompose",
|mut region| {
let offset = 0;
let zs = config.witness_decompose(
&mut region,
offset,
self.alpha,
self.strict,
WORD_NUM_BITS,
NUM_WINDOWS,
)?;
let alpha = zs[0].clone();
let offset = offset + NUM_WINDOWS + 1;
config.copy_decompose(
&mut region,
offset,
alpha,
self.strict,
WORD_NUM_BITS,
NUM_WINDOWS,
)?;
Ok(())
},
)
}
}
{
let alpha = pallas::Base::random(OsRng);
let circuit: MyCircuit<pallas::Base, L_BASE, FIXED_BASE_WINDOW_SIZE, { NUM_WINDOWS }> =
MyCircuit {
alpha: Value::known(alpha),
strict: true,
};
let prover = MockProver::<pallas::Base>::run(8, &circuit, vec![]).unwrap();
assert_eq!(prover.verify(), Ok(()));
}
{
let alpha = pallas::Base::from(rand::random::<u64>());
let circuit: MyCircuit<
pallas::Base,
L_SHORT,
FIXED_BASE_WINDOW_SIZE,
{ NUM_WINDOWS_SHORT },
> = MyCircuit {
alpha: Value::known(alpha),
strict: true,
};
let prover = MockProver::<pallas::Base>::run(8, &circuit, vec![]).unwrap();
assert_eq!(prover.verify(), Ok(()));
}
{
let alpha = pallas::Base::from_u128(1 << 66);
let circuit: MyCircuit<
pallas::Base,
L_SHORT,
FIXED_BASE_WINDOW_SIZE,
{ NUM_WINDOWS_SHORT },
> = MyCircuit {
alpha: Value::known(alpha),
strict: true,
};
let prover = MockProver::<pallas::Base>::run(8, &circuit, vec![]).unwrap();
assert_eq!(
prover.verify(),
Err(vec![
VerifyFailure::Permutation {
column: (Any::Fixed, 0).into(),
location: FailureLocation::OutsideRegion { row: 0 },
},
VerifyFailure::Permutation {
column: (Any::Fixed, 0).into(),
location: FailureLocation::OutsideRegion { row: 1 },
},
VerifyFailure::Permutation {
column: (Any::Advice, 0).into(),
location: FailureLocation::InRegion {
region: (0, "decompose").into(),
offset: 22,
},
},
VerifyFailure::Permutation {
column: (Any::Advice, 0).into(),
location: FailureLocation::InRegion {
region: (0, "decompose").into(),
offset: 45,
},
},
])
);
let circuit: MyCircuit<
pallas::Base,
{ L_SHORT },
FIXED_BASE_WINDOW_SIZE,
{ NUM_WINDOWS_SHORT },
> = MyCircuit {
alpha: Value::known(alpha),
strict: false,
};
let prover = MockProver::<pallas::Base>::run(8, &circuit, vec![]).unwrap();
assert_eq!(prover.verify(), Ok(()));
}
}
}