-
Notifications
You must be signed in to change notification settings - Fork 152
/
mod.rs
2115 lines (1953 loc) · 79.6 KB
/
mod.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
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use super::util::{
constraint_builder::BaseConstraintBuilder,
eth_types::Field,
expression::{and, not, select, Expr},
};
use crate::{
halo2_proofs::{
circuit::{Layouter, Region, Value},
halo2curves::ff::PrimeField,
plonk::{
Advice, Challenge, Column, ConstraintSystem, Error, Expression, Fixed, SecondPhase,
TableColumn, VirtualCells,
},
poly::Rotation,
},
util::expression::sum,
};
use halo2_base::halo2_proofs::{circuit::AssignedCell, plonk::Assigned};
use itertools::Itertools;
use log::{debug, info};
use rayon::prelude::{IntoParallelRefIterator, ParallelIterator};
use std::marker::PhantomData;
#[cfg(test)]
mod tests;
pub mod util;
use util::{
field_xor, get_absorb_positions, get_num_bits_per_lookup, into_bits, load_lookup_table,
load_normalize_table, load_pack_table, pack, pack_u64, pack_with_base, rotate, scatter,
target_part_sizes, to_bytes, unpack, CHI_BASE_LOOKUP_TABLE, NUM_BYTES_PER_WORD, NUM_ROUNDS,
NUM_WORDS_TO_ABSORB, NUM_WORDS_TO_SQUEEZE, RATE, RATE_IN_BITS, RHO_MATRIX, ROUND_CST,
};
const MAX_DEGREE: usize = 3;
const ABSORB_LOOKUP_RANGE: usize = 3;
const THETA_C_LOOKUP_RANGE: usize = 6;
const RHO_PI_LOOKUP_RANGE: usize = 4;
const CHI_BASE_LOOKUP_RANGE: usize = 5;
fn get_num_bits_per_absorb_lookup(k: u32) -> usize {
get_num_bits_per_lookup(ABSORB_LOOKUP_RANGE, k)
}
fn get_num_bits_per_theta_c_lookup(k: u32) -> usize {
get_num_bits_per_lookup(THETA_C_LOOKUP_RANGE, k)
}
fn get_num_bits_per_rho_pi_lookup(k: u32) -> usize {
get_num_bits_per_lookup(CHI_BASE_LOOKUP_RANGE.max(RHO_PI_LOOKUP_RANGE), k)
}
fn get_num_bits_per_base_chi_lookup(k: u32) -> usize {
get_num_bits_per_lookup(CHI_BASE_LOOKUP_RANGE.max(RHO_PI_LOOKUP_RANGE), k)
}
/// The number of keccak_f's that can be done in this circuit
///
/// `num_rows` should be number of usable rows without blinding factors
pub fn get_keccak_capacity(num_rows: usize, rows_per_round: usize) -> usize {
// - 1 because we have a dummy round at the very beginning of multi_keccak
// - NUM_WORDS_TO_ABSORB because `absorb_data_next` and `absorb_result_next` query `NUM_WORDS_TO_ABSORB * num_rows_per_round` beyond any row where `q_absorb == 1`
(num_rows / rows_per_round - 1 - NUM_WORDS_TO_ABSORB) / (NUM_ROUNDS + 1)
}
pub fn get_num_keccak_f(byte_length: usize) -> usize {
// ceil( (byte_length + 1) / RATE )
byte_length / RATE + 1
}
/// AbsorbData
#[derive(Clone, Default, Debug, PartialEq)]
pub(crate) struct AbsorbData<F: PrimeField> {
from: F,
absorb: F,
result: F,
}
/// SqueezeData
#[derive(Clone, Default, Debug, PartialEq)]
pub(crate) struct SqueezeData<F: PrimeField> {
packed: F,
}
/// KeccakRow
#[derive(Clone, Debug)]
pub struct KeccakRow<F: PrimeField> {
q_enable: bool,
// q_enable_row: bool,
q_round: bool,
q_absorb: bool,
q_round_last: bool,
q_padding: bool,
q_padding_last: bool,
round_cst: F,
is_final: bool,
cell_values: Vec<F>,
length: usize,
// SecondPhase values will be assigned separately
// data_rlc: Value<F>,
// hash_rlc: Value<F>,
}
impl<F: PrimeField> KeccakRow<F> {
pub fn dummy_rows(num_rows: usize) -> Vec<Self> {
(0..num_rows)
.map(|idx| KeccakRow {
q_enable: idx == 0,
q_round: false,
q_absorb: idx == 0,
q_round_last: false,
q_padding: false,
q_padding_last: false,
round_cst: F::ZERO,
is_final: false,
length: 0usize,
cell_values: Vec::new(),
})
.collect()
}
}
/// Part
#[derive(Clone, Debug)]
pub(crate) struct Part<F: PrimeField> {
cell: Cell<F>,
expr: Expression<F>,
num_bits: usize,
}
/// Part Value
#[derive(Clone, Copy, Debug)]
pub(crate) struct PartValue<F: PrimeField> {
value: F,
rot: i32,
num_bits: usize,
}
#[derive(Clone, Debug)]
pub(crate) struct KeccakRegion<F> {
pub(crate) rows: Vec<Vec<F>>,
}
impl<F: PrimeField> KeccakRegion<F> {
pub(crate) fn new() -> Self {
Self { rows: Vec::new() }
}
pub(crate) fn assign(&mut self, column: usize, offset: usize, value: F) {
while offset >= self.rows.len() {
self.rows.push(Vec::new());
}
let row = &mut self.rows[offset];
while column >= row.len() {
row.push(F::ZERO);
}
row[column] = value;
}
}
#[derive(Clone, Debug)]
pub(crate) struct Cell<F> {
expression: Expression<F>,
column_expression: Expression<F>,
column: Option<Column<Advice>>,
column_idx: usize,
rotation: i32,
}
impl<F: PrimeField> Cell<F> {
pub(crate) fn new(
meta: &mut VirtualCells<F>,
column: Column<Advice>,
column_idx: usize,
rotation: i32,
) -> Self {
Self {
expression: meta.query_advice(column, Rotation(rotation)),
column_expression: meta.query_advice(column, Rotation::cur()),
column: Some(column),
column_idx,
rotation,
}
}
pub(crate) fn new_value(column_idx: usize, rotation: i32) -> Self {
Self {
expression: 0.expr(),
column_expression: 0.expr(),
column: None,
column_idx,
rotation,
}
}
pub(crate) fn at_offset(&self, meta: &mut ConstraintSystem<F>, offset: i32) -> Self {
let mut expression = 0.expr();
meta.create_gate("Query cell", |meta| {
expression = meta.query_advice(self.column.unwrap(), Rotation(self.rotation + offset));
vec![0.expr()]
});
Self {
expression,
column_expression: self.column_expression.clone(),
column: self.column,
column_idx: self.column_idx,
rotation: self.rotation + offset,
}
}
pub(crate) fn assign(&self, region: &mut KeccakRegion<F>, offset: i32, value: F) {
region.assign(self.column_idx, (offset + self.rotation) as usize, value);
}
}
impl<F: PrimeField> Expr<F> for Cell<F> {
fn expr(&self) -> Expression<F> {
self.expression.clone()
}
}
impl<F: PrimeField> Expr<F> for &Cell<F> {
fn expr(&self) -> Expression<F> {
self.expression.clone()
}
}
/// CellColumn
#[derive(Clone, Debug)]
pub(crate) struct CellColumn<F> {
advice: Column<Advice>,
expr: Expression<F>,
}
/// CellManager
#[derive(Clone, Debug)]
pub(crate) struct CellManager<F> {
height: usize,
width: usize,
current_row: usize,
columns: Vec<CellColumn<F>>,
// rows[i] gives the number of columns already used in row `i`
rows: Vec<usize>,
num_unused_cells: usize,
}
impl<F: PrimeField> CellManager<F> {
pub(crate) fn new(height: usize) -> Self {
Self {
height,
width: 0,
current_row: 0,
columns: Vec::new(),
rows: vec![0; height],
num_unused_cells: 0,
}
}
pub(crate) fn query_cell(&mut self, meta: &mut ConstraintSystem<F>) -> Cell<F> {
let (row_idx, column_idx) = self.get_position();
self.query_cell_at_pos(meta, row_idx as i32, column_idx)
}
pub(crate) fn query_cell_at_row(
&mut self,
meta: &mut ConstraintSystem<F>,
row_idx: i32,
) -> Cell<F> {
let column_idx = self.rows[row_idx as usize];
self.rows[row_idx as usize] += 1;
self.width = self.width.max(column_idx + 1);
self.current_row = (row_idx as usize + 1) % self.height;
self.query_cell_at_pos(meta, row_idx, column_idx)
}
pub(crate) fn query_cell_at_pos(
&mut self,
meta: &mut ConstraintSystem<F>,
row_idx: i32,
column_idx: usize,
) -> Cell<F> {
let column = if column_idx < self.columns.len() {
self.columns[column_idx].advice
} else {
assert!(column_idx == self.columns.len());
let advice = meta.advice_column();
let mut expr = 0.expr();
meta.create_gate("Query column", |meta| {
expr = meta.query_advice(advice, Rotation::cur());
vec![0.expr()]
});
self.columns.push(CellColumn { advice, expr });
advice
};
let mut cells = Vec::new();
meta.create_gate("Query cell", |meta| {
cells.push(Cell::new(meta, column, column_idx, row_idx));
vec![0.expr()]
});
cells[0].clone()
}
pub(crate) fn query_cell_value(&mut self) -> Cell<F> {
let (row_idx, column_idx) = self.get_position();
self.query_cell_value_at_pos(row_idx as i32, column_idx)
}
pub(crate) fn query_cell_value_at_row(&mut self, row_idx: i32) -> Cell<F> {
let column_idx = self.rows[row_idx as usize];
self.rows[row_idx as usize] += 1;
self.width = self.width.max(column_idx + 1);
self.current_row = (row_idx as usize + 1) % self.height;
self.query_cell_value_at_pos(row_idx, column_idx)
}
pub(crate) fn query_cell_value_at_pos(&mut self, row_idx: i32, column_idx: usize) -> Cell<F> {
Cell::new_value(column_idx, row_idx)
}
fn get_position(&mut self) -> (usize, usize) {
let best_row_idx = self.current_row;
let best_row_pos = self.rows[best_row_idx];
self.rows[best_row_idx] += 1;
self.width = self.width.max(best_row_pos + 1);
self.current_row = (best_row_idx + 1) % self.height;
(best_row_idx, best_row_pos)
}
pub(crate) fn get_width(&self) -> usize {
self.width
}
pub(crate) fn start_region(&mut self) -> usize {
// Make sure all rows start at the same column
let width = self.get_width();
#[cfg(debug_assertions)]
for row in self.rows.iter() {
self.num_unused_cells += width - *row;
}
self.rows = vec![width; self.height];
width
}
pub(crate) fn columns(&self) -> &[CellColumn<F>] {
&self.columns
}
pub(crate) fn get_num_unused_cells(&self) -> usize {
self.num_unused_cells
}
}
/// Keccak Table, used to verify keccak hashing from RLC'ed input.
#[derive(Clone, Debug)]
pub struct KeccakTable {
/// True when the row is enabled
pub is_enabled: Column<Advice>,
/// Byte array input as `RLC(reversed(input))`
pub input_rlc: Column<Advice>, // RLC of input bytes
// Byte array input length
pub input_len: Column<Advice>,
/// RLC of the hash result
pub output_rlc: Column<Advice>, // RLC of hash of input bytes
}
impl KeccakTable {
/// Construct a new KeccakTable
pub fn construct<F: Field>(meta: &mut ConstraintSystem<F>) -> Self {
let input_len = meta.advice_column();
let input_rlc = meta.advice_column_in(SecondPhase);
let output_rlc = meta.advice_column_in(SecondPhase);
meta.enable_equality(input_len);
meta.enable_equality(input_rlc);
meta.enable_equality(output_rlc);
Self { is_enabled: meta.advice_column(), input_rlc, input_len, output_rlc }
}
}
#[cfg(feature = "halo2-axiom")]
type KeccakAssignedValue<'v, F> = AssignedCell<&'v Assigned<F>, F>;
#[cfg(not(feature = "halo2-axiom"))]
type KeccakAssignedValue<'v, F> = AssignedCell<F, F>;
pub fn assign_advice_custom<'v, F: Field>(
region: &mut Region<F>,
column: Column<Advice>,
offset: usize,
value: Value<F>,
) -> KeccakAssignedValue<'v, F> {
#[cfg(feature = "halo2-axiom")]
{
region.assign_advice(column, offset, value)
}
#[cfg(feature = "halo2-pse")]
{
region
.assign_advice(|| format!("assign advice {}", offset), column, offset, || value)
.unwrap()
}
}
pub fn assign_fixed_custom<F: Field>(
region: &mut Region<F>,
column: Column<Fixed>,
offset: usize,
value: F,
) {
#[cfg(feature = "halo2-axiom")]
{
region.assign_fixed(column, offset, value);
}
#[cfg(feature = "halo2-pse")]
{
region
.assign_fixed(
|| format!("assign fixed {}", offset),
column,
offset,
|| Value::known(value),
)
.unwrap();
}
}
/// Recombines parts back together
mod decode {
use super::util::BIT_COUNT;
use super::{Expr, Part, PartValue, PrimeField};
use crate::halo2_proofs::plonk::Expression;
pub(crate) fn expr<F: PrimeField>(parts: Vec<Part<F>>) -> Expression<F> {
parts.iter().rev().fold(0.expr(), |acc, part| {
acc * F::from(1u64 << (BIT_COUNT * part.num_bits)) + part.expr.clone()
})
}
pub(crate) fn value<F: PrimeField>(parts: Vec<PartValue<F>>) -> F {
parts.iter().rev().fold(F::ZERO, |acc, part| {
acc * F::from(1u64 << (BIT_COUNT * part.num_bits)) + part.value
})
}
}
/// Splits a word into parts
mod split {
use super::util::{pack, pack_part, unpack, WordParts};
use super::{
decode, BaseConstraintBuilder, CellManager, Expr, Field, KeccakRegion, Part, PartValue,
PrimeField,
};
use crate::halo2_proofs::plonk::{ConstraintSystem, Expression};
#[allow(clippy::too_many_arguments)]
pub(crate) fn expr<F: PrimeField>(
meta: &mut ConstraintSystem<F>,
cell_manager: &mut CellManager<F>,
cb: &mut BaseConstraintBuilder<F>,
input: Expression<F>,
rot: usize,
target_part_size: usize,
normalize: bool,
row: Option<usize>,
) -> Vec<Part<F>> {
let word = WordParts::new(target_part_size, rot, normalize);
let mut parts = Vec::with_capacity(word.parts.len());
for word_part in word.parts {
let cell = if let Some(row) = row {
cell_manager.query_cell_at_row(meta, row as i32)
} else {
cell_manager.query_cell(meta)
};
parts.push(Part {
num_bits: word_part.bits.len(),
cell: cell.clone(),
expr: cell.expr(),
});
}
// Input parts need to equal original input expression
cb.require_equal("split", decode::expr(parts.clone()), input);
parts
}
pub(crate) fn value<F: Field>(
cell_manager: &mut CellManager<F>,
region: &mut KeccakRegion<F>,
input: F,
rot: usize,
target_part_size: usize,
normalize: bool,
row: Option<usize>,
) -> Vec<PartValue<F>> {
let input_bits = unpack(input);
debug_assert_eq!(pack::<F>(&input_bits), input);
let word = WordParts::new(target_part_size, rot, normalize);
let mut parts = Vec::with_capacity(word.parts.len());
for word_part in word.parts {
let value = pack_part(&input_bits, &word_part);
let cell = if let Some(row) = row {
cell_manager.query_cell_value_at_row(row as i32)
} else {
cell_manager.query_cell_value()
};
cell.assign(region, 0, F::from(value));
parts.push(PartValue {
num_bits: word_part.bits.len(),
rot: cell.rotation,
value: F::from(value),
});
}
debug_assert_eq!(decode::value(parts.clone()), input);
parts
}
}
// Split into parts, but storing the parts in a specific way to have the same
// table layout in `output_cells` regardless of rotation.
mod split_uniform {
use super::{
decode, target_part_sizes,
util::{pack, pack_part, rotate, rotate_rev, unpack, WordParts, BIT_SIZE},
BaseConstraintBuilder, Cell, CellManager, Expr, KeccakRegion, Part, PartValue, PrimeField,
};
use crate::halo2_proofs::plonk::{ConstraintSystem, Expression};
use crate::util::eth_types::Field;
#[allow(clippy::too_many_arguments)]
pub(crate) fn expr<F: PrimeField>(
meta: &mut ConstraintSystem<F>,
output_cells: &[Cell<F>],
cell_manager: &mut CellManager<F>,
cb: &mut BaseConstraintBuilder<F>,
input: Expression<F>,
rot: usize,
target_part_size: usize,
normalize: bool,
) -> Vec<Part<F>> {
let mut input_parts = Vec::new();
let mut output_parts = Vec::new();
let word = WordParts::new(target_part_size, rot, normalize);
let word = rotate(word.parts, rot, target_part_size);
let target_sizes = target_part_sizes(target_part_size);
let mut word_iter = word.iter();
let mut counter = 0;
while let Some(word_part) = word_iter.next() {
if word_part.bits.len() == target_sizes[counter] {
// Input and output part are the same
let part = Part {
num_bits: target_sizes[counter],
cell: output_cells[counter].clone(),
expr: output_cells[counter].expr(),
};
input_parts.push(part.clone());
output_parts.push(part);
counter += 1;
} else if let Some(extra_part) = word_iter.next() {
// The two parts combined need to have the expected combined length
debug_assert_eq!(
word_part.bits.len() + extra_part.bits.len(),
target_sizes[counter]
);
// Needs two cells here to store the parts
// These still need to be range checked elsewhere!
let part_a = cell_manager.query_cell(meta);
let part_b = cell_manager.query_cell(meta);
// Make sure the parts combined equal the value in the uniform output
let expr = part_a.expr()
+ part_b.expr()
* F::from((BIT_SIZE as u32).pow(word_part.bits.len() as u32) as u64);
cb.require_equal("rot part", expr, output_cells[counter].expr());
// Input needs the two parts because it needs to be able to undo the rotation
input_parts.push(Part {
num_bits: word_part.bits.len(),
cell: part_a.clone(),
expr: part_a.expr(),
});
input_parts.push(Part {
num_bits: extra_part.bits.len(),
cell: part_b.clone(),
expr: part_b.expr(),
});
// Output only has the combined cell
output_parts.push(Part {
num_bits: target_sizes[counter],
cell: output_cells[counter].clone(),
expr: output_cells[counter].expr(),
});
counter += 1;
} else {
unreachable!();
}
}
let input_parts = rotate_rev(input_parts, rot, target_part_size);
// Input parts need to equal original input expression
cb.require_equal("split", decode::expr(input_parts), input);
// Uniform output
output_parts
}
pub(crate) fn value<F: Field>(
output_cells: &[Cell<F>],
cell_manager: &mut CellManager<F>,
region: &mut KeccakRegion<F>,
input: F,
rot: usize,
target_part_size: usize,
normalize: bool,
) -> Vec<PartValue<F>> {
let input_bits = unpack(input);
debug_assert_eq!(pack::<F>(&input_bits), input);
let mut input_parts = Vec::new();
let mut output_parts = Vec::new();
let word = WordParts::new(target_part_size, rot, normalize);
let word = rotate(word.parts, rot, target_part_size);
let target_sizes = target_part_sizes(target_part_size);
let mut word_iter = word.iter();
let mut counter = 0;
while let Some(word_part) = word_iter.next() {
if word_part.bits.len() == target_sizes[counter] {
let value = pack_part(&input_bits, word_part);
output_cells[counter].assign(region, 0, F::from(value));
input_parts.push(PartValue {
num_bits: word_part.bits.len(),
rot: output_cells[counter].rotation,
value: F::from(value),
});
output_parts.push(PartValue {
num_bits: word_part.bits.len(),
rot: output_cells[counter].rotation,
value: F::from(value),
});
counter += 1;
} else if let Some(extra_part) = word_iter.next() {
debug_assert_eq!(
word_part.bits.len() + extra_part.bits.len(),
target_sizes[counter]
);
let part_a = cell_manager.query_cell_value();
let part_b = cell_manager.query_cell_value();
let value_a = pack_part(&input_bits, word_part);
let value_b = pack_part(&input_bits, extra_part);
part_a.assign(region, 0, F::from(value_a));
part_b.assign(region, 0, F::from(value_b));
let value = value_a + value_b * (BIT_SIZE as u64).pow(word_part.bits.len() as u32);
output_cells[counter].assign(region, 0, F::from(value));
input_parts.push(PartValue {
num_bits: word_part.bits.len(),
value: F::from(value_a),
rot: part_a.rotation,
});
input_parts.push(PartValue {
num_bits: extra_part.bits.len(),
value: F::from(value_b),
rot: part_b.rotation,
});
output_parts.push(PartValue {
num_bits: target_sizes[counter],
value: F::from(value),
rot: output_cells[counter].rotation,
});
counter += 1;
} else {
unreachable!();
}
}
let input_parts = rotate_rev(input_parts, rot, target_part_size);
debug_assert_eq!(decode::value(input_parts), input);
output_parts
}
}
// Transform values using a lookup table
mod transform {
use super::{transform_to, CellManager, Field, KeccakRegion, Part, PartValue, PrimeField};
use crate::halo2_proofs::plonk::{ConstraintSystem, TableColumn};
use itertools::Itertools;
#[allow(clippy::too_many_arguments)]
pub(crate) fn expr<F: PrimeField>(
name: &'static str,
meta: &mut ConstraintSystem<F>,
cell_manager: &mut CellManager<F>,
lookup_counter: &mut usize,
input: Vec<Part<F>>,
transform_table: [TableColumn; 2],
uniform_lookup: bool,
) -> Vec<Part<F>> {
let cells = input
.iter()
.map(|input_part| {
if uniform_lookup {
cell_manager.query_cell_at_row(meta, input_part.cell.rotation)
} else {
cell_manager.query_cell(meta)
}
})
.collect_vec();
transform_to::expr(
name,
meta,
&cells,
lookup_counter,
input,
transform_table,
uniform_lookup,
)
}
pub(crate) fn value<F: Field>(
cell_manager: &mut CellManager<F>,
region: &mut KeccakRegion<F>,
input: Vec<PartValue<F>>,
do_packing: bool,
f: fn(&u8) -> u8,
uniform_lookup: bool,
) -> Vec<PartValue<F>> {
let cells = input
.iter()
.map(|input_part| {
if uniform_lookup {
cell_manager.query_cell_value_at_row(input_part.rot)
} else {
cell_manager.query_cell_value()
}
})
.collect_vec();
transform_to::value(&cells, region, input, do_packing, f)
}
}
// Transfroms values to cells
mod transform_to {
use super::util::{pack, to_bytes, unpack};
use super::{Cell, Expr, Field, KeccakRegion, Part, PartValue, PrimeField};
use crate::halo2_proofs::plonk::{ConstraintSystem, TableColumn};
#[allow(clippy::too_many_arguments)]
pub(crate) fn expr<F: PrimeField>(
name: &'static str,
meta: &mut ConstraintSystem<F>,
cells: &[Cell<F>],
lookup_counter: &mut usize,
input: Vec<Part<F>>,
transform_table: [TableColumn; 2],
uniform_lookup: bool,
) -> Vec<Part<F>> {
let mut output = Vec::with_capacity(input.len());
for (idx, input_part) in input.iter().enumerate() {
let output_part = cells[idx].clone();
if !uniform_lookup || input_part.cell.rotation == 0 {
meta.lookup(name, |_| {
vec![
(input_part.expr.clone(), transform_table[0]),
(output_part.expr(), transform_table[1]),
]
});
*lookup_counter += 1;
}
output.push(Part {
num_bits: input_part.num_bits,
cell: output_part.clone(),
expr: output_part.expr(),
});
}
output
}
pub(crate) fn value<F: Field>(
cells: &[Cell<F>],
region: &mut KeccakRegion<F>,
input: Vec<PartValue<F>>,
do_packing: bool,
f: fn(&u8) -> u8,
) -> Vec<PartValue<F>> {
let mut output = Vec::new();
for (idx, input_part) in input.iter().enumerate() {
let input_bits = &unpack(input_part.value)[0..input_part.num_bits];
let output_bits = input_bits.iter().map(f).collect::<Vec<_>>();
let value = if do_packing {
pack(&output_bits)
} else {
F::from(to_bytes::value(&output_bits)[0] as u64)
};
let output_part = cells[idx].clone();
output_part.assign(region, 0, value);
output.push(PartValue {
num_bits: input_part.num_bits,
rot: output_part.rotation,
value,
});
}
output
}
}
/// Configuration parameters to define [`KeccakCircuitConfig`]
#[derive(Copy, Clone, Debug, Default)]
pub struct KeccakConfigParams {
/// The circuit degree, i.e., circuit has 2<sup>k</sup> rows
pub k: u32,
/// The number of rows to use for each round in the keccak_f permutation
pub rows_per_round: usize,
}
/// KeccakConfig
#[derive(Clone, Debug)]
pub struct KeccakCircuitConfig<F> {
challenge: Challenge,
q_enable: Column<Fixed>,
q_first: Column<Fixed>,
q_round: Column<Fixed>,
q_absorb: Column<Fixed>,
q_round_last: Column<Fixed>,
q_padding: Column<Fixed>,
q_padding_last: Column<Fixed>,
pub keccak_table: KeccakTable,
cell_manager: CellManager<F>,
round_cst: Column<Fixed>,
normalize_3: [TableColumn; 2],
normalize_4: [TableColumn; 2],
normalize_6: [TableColumn; 2],
chi_base_table: [TableColumn; 2],
pack_table: [TableColumn; 2],
// config parameters for convenience
pub parameters: KeccakConfigParams,
_marker: PhantomData<F>,
}
impl<F: Field> KeccakCircuitConfig<F> {
pub fn challenge(&self) -> Challenge {
self.challenge
}
/// Return a new KeccakCircuitConfig
pub fn new(
meta: &mut ConstraintSystem<F>,
challenge: Challenge,
parameters: KeccakConfigParams,
) -> Self {
let k = parameters.k;
let num_rows_per_round = parameters.rows_per_round;
let q_enable = meta.fixed_column();
// let q_enable_row = meta.fixed_column();
let q_first = meta.fixed_column();
let q_round = meta.fixed_column();
let q_absorb = meta.fixed_column();
let q_round_last = meta.fixed_column();
let q_padding = meta.fixed_column();
let q_padding_last = meta.fixed_column();
let round_cst = meta.fixed_column();
let keccak_table = KeccakTable::construct(meta);
let is_final = keccak_table.is_enabled;
let input_len = keccak_table.input_len;
let data_rlc = keccak_table.input_rlc;
let hash_rlc = keccak_table.output_rlc;
let normalize_3 = array_init::array_init(|_| meta.lookup_table_column());
let normalize_4 = array_init::array_init(|_| meta.lookup_table_column());
let normalize_6 = array_init::array_init(|_| meta.lookup_table_column());
let chi_base_table = array_init::array_init(|_| meta.lookup_table_column());
let pack_table = array_init::array_init(|_| meta.lookup_table_column());
let mut cell_manager = CellManager::new(num_rows_per_round);
let mut cb = BaseConstraintBuilder::new(MAX_DEGREE);
let mut total_lookup_counter = 0;
let start_new_hash = |meta: &mut VirtualCells<F>, rot| {
// A new hash is started when the previous hash is done or on the first row
meta.query_fixed(q_first, rot) + meta.query_advice(is_final, rot)
};
// Round constant
let mut round_cst_expr = 0.expr();
meta.create_gate("Query round cst", |meta| {
round_cst_expr = meta.query_fixed(round_cst, Rotation::cur());
vec![0u64.expr()]
});
// State data
let mut s = vec![vec![0u64.expr(); 5]; 5];
let mut s_next = vec![vec![0u64.expr(); 5]; 5];
for i in 0..5 {
for j in 0..5 {
let cell = cell_manager.query_cell(meta);
s[i][j] = cell.expr();
s_next[i][j] = cell.at_offset(meta, num_rows_per_round as i32).expr();
}
}
// Absorb data
let absorb_from = cell_manager.query_cell(meta);
let absorb_data = cell_manager.query_cell(meta);
let absorb_result = cell_manager.query_cell(meta);
let mut absorb_from_next = vec![0u64.expr(); NUM_WORDS_TO_ABSORB];
let mut absorb_data_next = vec![0u64.expr(); NUM_WORDS_TO_ABSORB];
let mut absorb_result_next = vec![0u64.expr(); NUM_WORDS_TO_ABSORB];
for i in 0..NUM_WORDS_TO_ABSORB {
let rot = ((i + 1) * num_rows_per_round) as i32;
absorb_from_next[i] = absorb_from.at_offset(meta, rot).expr();
absorb_data_next[i] = absorb_data.at_offset(meta, rot).expr();
absorb_result_next[i] = absorb_result.at_offset(meta, rot).expr();
}
// Store the pre-state
let pre_s = s.clone();
// Absorb
// The absorption happening at the start of the 24 rounds is done spread out
// over those 24 rounds. In a single round (in 17 of the 24 rounds) a
// single word is absorbed so the work is spread out. The absorption is
// done simply by doing state + data and then normalizing the result to [0,1].
// We also need to convert the input data into bytes to calculate the input data
// rlc.
cell_manager.start_region();
let mut lookup_counter = 0;
let part_size = get_num_bits_per_absorb_lookup(k);
let input = absorb_from.expr() + absorb_data.expr();
let absorb_fat =
split::expr(meta, &mut cell_manager, &mut cb, input, 0, part_size, false, None);
cell_manager.start_region();
let absorb_res = transform::expr(
"absorb",
meta,
&mut cell_manager,
&mut lookup_counter,
absorb_fat,
normalize_3,
true,
);
cb.require_equal("absorb result", decode::expr(absorb_res), absorb_result.expr());
info!("- Post absorb:");
info!("Lookups: {}", lookup_counter);
info!("Columns: {}", cell_manager.get_width());
total_lookup_counter += lookup_counter;
// Squeeze
// The squeezing happening at the end of the 24 rounds is done spread out
// over those 24 rounds. In a single round (in 4 of the 24 rounds) a
// single word is converted to bytes.
cell_manager.start_region();
let mut lookup_counter = 0;
// Potential optimization: could do multiple bytes per lookup
let packed_parts =
split::expr(meta, &mut cell_manager, &mut cb, absorb_data.expr(), 0, 8, false, None);
cell_manager.start_region();
// input_bytes.len() = packed_parts.len() = 64 / 8 = 8 = NUM_BYTES_PER_WORD
let input_bytes = transform::expr(
"squeeze unpack",
meta,
&mut cell_manager,
&mut lookup_counter,
packed_parts,
pack_table.into_iter().rev().collect::<Vec<_>>().try_into().unwrap(),
true,
);
debug_assert_eq!(input_bytes.len(), NUM_BYTES_PER_WORD);
// Padding data
cell_manager.start_region();
let is_paddings = input_bytes.iter().map(|_| cell_manager.query_cell(meta)).collect_vec();
info!("- Post padding:");
info!("Lookups: {}", lookup_counter);
info!("Columns: {}", cell_manager.get_width());
total_lookup_counter += lookup_counter;
// Theta
// Calculate
// - `c[i] = s[i][0] + s[i][1] + s[i][2] + s[i][3] + s[i][4]`
// - `bc[i] = normalize(c)`.
// - `t[i] = bc[(i + 4) % 5] + rot(bc[(i + 1)% 5], 1)`
// This is done by splitting the bc values in parts in a way
// that allows us to also calculate the rotated value "for free".
cell_manager.start_region();
let mut lookup_counter = 0;
let part_size_c = get_num_bits_per_theta_c_lookup(k);
let mut c_parts = Vec::new();
for s in s.iter() {
// Calculate c and split into parts
let c = s[0].clone() + s[1].clone() + s[2].clone() + s[3].clone() + s[4].clone();
c_parts.push(split::expr(
meta,
&mut cell_manager,