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
use crate::halo2_proofs::{
circuit::{Layouter, Value},
plonk::{Error, TableColumn},
};
use itertools::Itertools;
use std::env::var;
pub mod constraint_builder;
pub mod eth_types;
pub mod expression;
use eth_types::{Field, ToScalar, Word};
pub const NUM_BITS_PER_BYTE: usize = 8;
pub const NUM_BYTES_PER_WORD: usize = 8;
pub const NUM_BITS_PER_WORD: usize = NUM_BYTES_PER_WORD * NUM_BITS_PER_BYTE;
pub const KECCAK_WIDTH: usize = 5 * 5;
pub const KECCAK_WIDTH_IN_BITS: usize = KECCAK_WIDTH * NUM_BITS_PER_WORD;
pub const NUM_ROUNDS: usize = 24;
pub const NUM_WORDS_TO_ABSORB: usize = 17;
pub const NUM_BYTES_TO_ABSORB: usize = NUM_WORDS_TO_ABSORB * NUM_BYTES_PER_WORD;
pub const NUM_WORDS_TO_SQUEEZE: usize = 4;
pub const NUM_BYTES_TO_SQUEEZE: usize = NUM_WORDS_TO_SQUEEZE * NUM_BYTES_PER_WORD;
pub const ABSORB_WIDTH_PER_ROW: usize = NUM_BITS_PER_WORD;
pub const ABSORB_WIDTH_PER_ROW_BYTES: usize = ABSORB_WIDTH_PER_ROW / NUM_BITS_PER_BYTE;
pub const RATE: usize = NUM_WORDS_TO_ABSORB * NUM_BYTES_PER_WORD;
pub const RATE_IN_BITS: usize = RATE * NUM_BITS_PER_BYTE;
pub(crate) const RHO_MATRIX: [[usize; 5]; 5] = [
[0, 36, 3, 41, 18],
[1, 44, 10, 45, 2],
[62, 6, 43, 15, 61],
[28, 55, 25, 21, 56],
[27, 20, 39, 8, 14],
];
pub(crate) const ROUND_CST: [u64; NUM_ROUNDS + 1] = [
0x0000000000000001,
0x0000000000008082,
0x800000000000808a,
0x8000000080008000,
0x000000000000808b,
0x0000000080000001,
0x8000000080008081,
0x8000000000008009,
0x000000000000008a,
0x0000000000000088,
0x0000000080008009,
0x000000008000000a,
0x000000008000808b,
0x800000000000008b,
0x8000000000008089,
0x8000000000008003,
0x8000000000008002,
0x8000000000000080,
0x000000000000800a,
0x800000008000000a,
0x8000000080008081,
0x8000000000008080,
0x0000000080000001,
0x8000000080008008,
0x0000000000000000, ];
pub const BIT_COUNT: usize = 3;
pub const BIT_SIZE: usize = 2usize.pow(BIT_COUNT as u32);
pub(crate) const CHI_BASE_LOOKUP_TABLE: [u8; 5] = [0, 1, 1, 0, 0];
#[derive(Clone, Debug)]
pub struct PartInfo {
pub bits: Vec<usize>,
}
#[derive(Clone, Debug)]
pub struct WordParts {
pub parts: Vec<PartInfo>,
}
pub mod to_bytes {
pub(crate) fn value(bits: &[u8]) -> Vec<u8> {
debug_assert!(bits.len() % 8 == 0, "bits not a multiple of 8");
let mut bytes = Vec::new();
for byte_bits in bits.chunks(8) {
let mut value = 0u8;
for (idx, bit) in byte_bits.iter().enumerate() {
value += *bit << idx;
}
bytes.push(value);
}
bytes
}
}
pub fn rotate<T>(parts: Vec<T>, count: usize, part_size: usize) -> Vec<T> {
let mut rotated_parts = parts;
rotated_parts.rotate_right(get_rotate_count(count, part_size));
rotated_parts
}
pub fn rotate_rev<T>(parts: Vec<T>, count: usize, part_size: usize) -> Vec<T> {
let mut rotated_parts = parts;
rotated_parts.rotate_left(get_rotate_count(count, part_size));
rotated_parts
}
pub fn rotate_left(bits: &[u8], count: usize) -> [u8; NUM_BITS_PER_WORD] {
let mut rotated = bits.to_vec();
rotated.rotate_left(count);
rotated.try_into().unwrap()
}
pub mod scatter {
use super::{eth_types::Field, pack};
use crate::halo2_proofs::plonk::Expression;
pub(crate) fn expr<F: Field>(value: u8, count: usize) -> Expression<F> {
Expression::Constant(pack(&vec![value; count]))
}
}
pub fn get_absorb_positions() -> Vec<(usize, usize)> {
let mut absorb_positions = Vec::new();
for j in 0..5 {
for i in 0..5 {
if i + j * 5 < 17 {
absorb_positions.push((i, j));
}
}
}
absorb_positions
}
pub fn into_bits(bytes: &[u8]) -> Vec<u8> {
let mut bits: Vec<u8> = vec![0; bytes.len() * 8];
for (byte_idx, byte) in bytes.iter().enumerate() {
for idx in 0u64..8 {
bits[byte_idx * 8 + (idx as usize)] = (*byte >> idx) & 1;
}
}
bits
}
pub fn pack<F: Field>(bits: &[u8]) -> F {
pack_with_base(bits, BIT_SIZE)
}
pub fn pack_with_base<F: Field>(bits: &[u8], base: usize) -> F {
let base = F::from(base as u64);
bits.iter().rev().fold(F::zero(), |acc, &bit| acc * base + F::from(bit as u64))
}
pub fn pack_part(bits: &[u8], info: &PartInfo) -> u64 {
info.bits
.iter()
.rev()
.fold(0u64, |acc, &bit_pos| acc * (BIT_SIZE as u64) + (bits[bit_pos] as u64))
}
pub fn unpack<F: Field>(packed: F) -> [u8; NUM_BITS_PER_WORD] {
let mut bits = [0; NUM_BITS_PER_WORD];
let packed = Word::from_little_endian(packed.to_bytes_le().as_ref());
let mask = Word::from(BIT_SIZE - 1);
for (idx, bit) in bits.iter_mut().enumerate() {
*bit = ((packed >> (idx * BIT_COUNT)) & mask).as_u32() as u8;
}
debug_assert_eq!(pack::<F>(&bits), packed.to_scalar().unwrap());
bits
}
pub fn pack_u64<F: Field>(value: u64) -> F {
pack(&((0..NUM_BITS_PER_WORD).map(|i| ((value >> i) & 1) as u8).collect::<Vec<_>>()))
}
pub fn field_xor<F: Field>(a: F, b: F) -> F {
let mut bytes = [0u8; 32];
for (idx, (a, b)) in a.to_bytes_le().into_iter().zip(b.to_bytes_le()).enumerate() {
bytes[idx] = a ^ b;
}
F::from_bytes_le(&bytes)
}
pub fn target_part_sizes(part_size: usize) -> Vec<usize> {
let num_full_chunks = NUM_BITS_PER_WORD / part_size;
let partial_chunk_size = NUM_BITS_PER_WORD % part_size;
let mut part_sizes = vec![part_size; num_full_chunks];
if partial_chunk_size > 0 {
part_sizes.push(partial_chunk_size);
}
part_sizes
}
pub fn get_rotate_count(count: usize, part_size: usize) -> usize {
(count + part_size - 1) / part_size
}
impl WordParts {
pub fn new(part_size: usize, rot: usize, normalize: bool) -> Self {
let mut bits = (0usize..64).collect::<Vec<_>>();
bits.rotate_right(rot);
let mut parts = Vec::new();
let mut rot_idx = 0;
let mut idx = 0;
let target_sizes = if normalize {
target_part_sizes(part_size)
} else {
let num_parts_a = rot / part_size;
let partial_part_a = rot % part_size;
let num_parts_b = (64 - rot) / part_size;
let partial_part_b = (64 - rot) % part_size;
let mut part_sizes = vec![part_size; num_parts_a];
if partial_part_a > 0 {
part_sizes.push(partial_part_a);
}
part_sizes.extend(vec![part_size; num_parts_b]);
if partial_part_b > 0 {
part_sizes.push(partial_part_b);
}
part_sizes
};
for part_size in target_sizes {
let mut num_consumed = 0;
while num_consumed < part_size {
let mut part_bits: Vec<usize> = Vec::new();
while num_consumed < part_size {
if !part_bits.is_empty() && bits[idx] == 0 {
break;
}
if bits[idx] == 0 {
rot_idx = parts.len();
}
part_bits.push(bits[idx]);
idx += 1;
num_consumed += 1;
}
parts.push(PartInfo { bits: part_bits });
}
}
debug_assert_eq!(get_rotate_count(rot, part_size), rot_idx);
parts.rotate_left(rot_idx);
debug_assert_eq!(parts[0].bits[0], 0);
Self { parts }
}
}
pub fn get_degree() -> usize {
var("KECCAK_DEGREE")
.expect("Need to set KECCAK_DEGREE to log_2(rows) of circuit")
.parse()
.expect("Cannot parse KECCAK_DEGREE env var as usize")
}
pub fn get_num_bits_per_lookup(range: usize) -> usize {
let num_unusable_rows = 31;
let degree = get_degree() as u32;
let mut num_bits = 1;
while range.pow(num_bits + 1) + num_unusable_rows <= 2usize.pow(degree) {
num_bits += 1;
}
num_bits as usize
}
pub(crate) fn load_normalize_table<F: Field>(
layouter: &mut impl Layouter<F>,
name: &str,
tables: &[TableColumn; 2],
range: u64,
) -> Result<(), Error> {
let part_size = get_num_bits_per_lookup(range as usize);
layouter.assign_table(
|| format!("{name} table"),
|mut table| {
for (offset, perm) in
(0..part_size).map(|_| 0u64..range).multi_cartesian_product().enumerate()
{
let mut input = 0u64;
let mut output = 0u64;
let mut factor = 1u64;
for input_part in perm.iter() {
input += input_part * factor;
output += (input_part & 1) * factor;
factor *= BIT_SIZE as u64;
}
table.assign_cell(
|| format!("{name} input"),
tables[0],
offset,
|| Value::known(F::from(input)),
)?;
table.assign_cell(
|| format!("{name} output"),
tables[1],
offset,
|| Value::known(F::from(output)),
)?;
}
Ok(())
},
)
}
pub(crate) fn load_pack_table<F: Field>(
layouter: &mut impl Layouter<F>,
tables: &[TableColumn; 2],
) -> Result<(), Error> {
layouter.assign_table(
|| "pack table",
|mut table| {
for (offset, idx) in (0u64..256).enumerate() {
table.assign_cell(
|| "unpacked",
tables[0],
offset,
|| Value::known(F::from(idx)),
)?;
let packed: F = pack(&into_bits(&[idx as u8]));
table.assign_cell(|| "packed", tables[1], offset, || Value::known(packed))?;
}
Ok(())
},
)
}
pub(crate) fn load_lookup_table<F: Field>(
layouter: &mut impl Layouter<F>,
name: &str,
tables: &[TableColumn; 2],
part_size: usize,
lookup_table: &[u8],
) -> Result<(), Error> {
layouter.assign_table(
|| format!("{name} table"),
|mut table| {
for (offset, perm) in (0..part_size)
.map(|_| 0..lookup_table.len() as u64)
.multi_cartesian_product()
.enumerate()
{
let mut input = 0u64;
let mut output = 0u64;
let mut factor = 1u64;
for input_part in perm.iter() {
input += input_part * factor;
output += (lookup_table[*input_part as usize] as u64) * factor;
factor *= BIT_SIZE as u64;
}
table.assign_cell(
|| format!("{name} input"),
tables[0],
offset,
|| Value::known(F::from(input)),
)?;
table.assign_cell(
|| format!("{name} output"),
tables[1],
offset,
|| Value::known(F::from(output)),
)?;
}
Ok(())
},
)
}