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
use std::ops::Index;
use crate::{grain::Grain, matrix::Matrix};
use halo2curves::FieldExt;
#[derive(Clone, Debug, PartialEq)]
pub struct State<F: FieldExt, const T: usize>(pub(crate) [F; T]);
impl<F: FieldExt, const T: usize> Default for State<F, T> {
fn default() -> Self {
let mut state = [F::zero(); T];
state[0] = F::from_u128(1 << 64);
State(state)
}
}
impl<F: FieldExt, const T: usize> State<F, T> {
pub(crate) fn sbox_full(&mut self) {
for e in self.0.iter_mut() {
let tmp = e.mul(*e);
e.mul_assign(tmp);
e.mul_assign(tmp);
}
}
pub(crate) fn sbox_part(&mut self) {
let tmp = self.0[0].mul(self.0[0]);
self.0[0].mul_assign(tmp);
self.0[0].mul_assign(tmp);
}
pub(crate) fn add_constants(&mut self, constants: &[F; T]) {
for (e, constant) in self.0.iter_mut().zip(constants.iter()) {
e.add_assign(constant)
}
}
pub(crate) fn add_constant(&mut self, constant: &F) {
self.0[0].add_assign(constant)
}
pub fn words(&self) -> [F; T] {
self.0
}
pub(crate) fn result(&self) -> F {
self.0[1]
}
}
#[derive(Debug, Clone)]
pub struct Spec<F: FieldExt, const T: usize, const RATE: usize> {
pub(crate) r_f: usize,
pub(crate) mds_matrices: MDSMatrices<F, T, RATE>,
pub(crate) constants: OptimizedConstants<F, T>,
}
impl<F: FieldExt, const T: usize, const RATE: usize> Spec<F, T, RATE> {
pub fn r_f(&self) -> usize {
self.r_f.clone()
}
pub fn mds_matrices(&self) -> &MDSMatrices<F, T, RATE> {
&self.mds_matrices
}
pub fn constants(&self) -> &OptimizedConstants<F, T> {
&self.constants
}
}
#[derive(Debug, Clone)]
pub struct OptimizedConstants<F: FieldExt, const T: usize> {
pub(crate) start: Vec<[F; T]>,
pub(crate) partial: Vec<F>,
pub(crate) end: Vec<[F; T]>,
}
impl<F: FieldExt, const T: usize> OptimizedConstants<F, T> {
pub fn start(&self) -> &Vec<[F; T]> {
&self.start
}
pub fn partial(&self) -> &Vec<F> {
&self.partial
}
pub fn end(&self) -> &Vec<[F; T]> {
&self.end
}
}
#[derive(Debug, Clone)]
pub struct MDSMatrices<F: FieldExt, const T: usize, const RATE: usize> {
pub(crate) mds: MDSMatrix<F, T, RATE>,
pub(crate) pre_sparse_mds: MDSMatrix<F, T, RATE>,
pub(crate) sparse_matrices: Vec<SparseMDSMatrix<F, T, RATE>>,
}
impl<F: FieldExt, const T: usize, const RATE: usize> MDSMatrices<F, T, RATE> {
pub fn mds(&self) -> &MDSMatrix<F, T, RATE> {
&self.mds
}
pub fn pre_sparse_mds(&self) -> &MDSMatrix<F, T, RATE> {
&self.pre_sparse_mds
}
pub fn sparse_matrices(&self) -> &Vec<SparseMDSMatrix<F, T, RATE>> {
&self.sparse_matrices
}
}
#[derive(Clone, Debug)]
pub struct MDSMatrix<F: FieldExt, const T: usize, const RATE: usize>(pub(crate) Matrix<F, T>);
impl<F: FieldExt, const T: usize, const RATE: usize> Index<usize> for MDSMatrix<F, T, RATE> {
type Output = [F; T];
fn index(&self, idx: usize) -> &Self::Output {
&self.0 .0[idx]
}
}
impl<F: FieldExt, const T: usize, const RATE: usize> MDSMatrix<F, T, RATE> {
pub(crate) fn apply(&self, state: &mut State<F, T>) {
state.0 = self.0.mul_vector(&state.0);
}
pub(super) fn cauchy(xs: &[F; T], ys: &[F; T]) -> Self {
let mut m = Matrix::default();
for (i, x) in xs.iter().enumerate() {
for (j, y) in ys.iter().enumerate() {
let sum = *x + *y;
debug_assert!(!sum.is_zero_vartime());
m.set(i, j, sum.invert().unwrap());
}
}
MDSMatrix(m)
}
fn invert(&self) -> Self {
Self(self.0.invert())
}
fn mul_constants(&self, v: &[F; T]) -> [F; T] {
self.0.mul_vector(v)
}
fn mul(&self, other: &Self) -> Self {
Self(self.0.mul(&other.0))
}
fn transpose(&self) -> Self {
Self(self.0.transpose())
}
fn factorise(&self) -> (Self, SparseMDSMatrix<F, T, RATE>) {
let prime = |hat: Matrix<F, RATE>| -> MDSMatrix<F, T, RATE> {
let mut prime = Matrix::identity();
for (prime_row, hat_row) in prime.0.iter_mut().skip(1).zip(hat.0.iter()) {
for (el_prime, el_hat) in prime_row.iter_mut().skip(1).zip(hat_row.iter()) {
*el_prime = *el_hat;
}
}
Self(prime)
};
let prime_prime = |w_hat: [F; RATE]| -> Self {
let mut prime_prime = Matrix::identity();
prime_prime.0[0] = self.0 .0[0];
for (row, w) in prime_prime.0.iter_mut().skip(1).zip(w_hat.iter()) {
row[0] = *w
}
Self(prime_prime)
};
let w = self.0.w();
let m_hat = self.0.sub::<RATE>();
let m_hat_inverse = m_hat.invert();
let w_hat = m_hat_inverse.mul_vector(&w);
(prime(m_hat), prime_prime(w_hat).transpose().into())
}
pub fn rows(&self) -> [[F; T]; T] {
self.0 .0
}
}
#[derive(Debug, Clone)]
pub struct SparseMDSMatrix<F: FieldExt, const T: usize, const RATE: usize> {
pub(crate) row: [F; T],
pub(crate) col_hat: [F; RATE],
}
impl<F: FieldExt, const T: usize, const RATE: usize> SparseMDSMatrix<F, T, RATE> {
pub fn row(&self) -> &[F; T] {
&self.row
}
pub fn col_hat(&self) -> &[F; RATE] {
&self.col_hat
}
pub(crate) fn apply(&self, state: &mut State<F, T>) {
let words = state.words();
state.0[0] = self
.row
.iter()
.zip(words.iter())
.fold(F::zero(), |acc, (e, cell)| acc + (*e * *cell));
for ((new_word, col_el), word) in (state.0)
.iter_mut()
.skip(1)
.zip(self.col_hat.iter())
.zip(words.iter().skip(1))
{
*new_word = *col_el * words[0] + word;
}
}
}
impl<F: FieldExt, const T: usize, const RATE: usize> From<MDSMatrix<F, T, RATE>>
for SparseMDSMatrix<F, T, RATE>
{
fn from(mds: MDSMatrix<F, T, RATE>) -> Self {
let mds = mds.0;
for (i, row) in mds.0.iter().enumerate().skip(1) {
for (j, _) in row.iter().enumerate().skip(1) {
assert_eq!(row[j], if i != j { F::zero() } else { F::one() });
}
}
let (mut row, mut col_hat) = ([F::zero(); T], [F::zero(); RATE]);
for (row_el, el) in row.iter_mut().zip(mds.0[0].iter()) {
*row_el = *el
}
for (col_el, row) in col_hat.iter_mut().zip(mds.0.iter().skip(1)) {
*col_el = row[0]
}
SparseMDSMatrix { row, col_hat }
}
}
impl<F: FieldExt, const T: usize, const RATE: usize> Spec<F, T, RATE> {
pub fn new(r_f: usize, r_p: usize) -> Self {
let (unoptimized_constants, mds) = Grain::generate(r_f, r_p);
let constants = Self::calculate_optimized_constants(r_f, r_p, unoptimized_constants, &mds);
let (sparse_matrices, pre_sparse_mds) = Self::calculate_sparse_matrices(r_p, &mds);
Self {
r_f,
constants,
mds_matrices: MDSMatrices {
mds,
sparse_matrices,
pre_sparse_mds,
},
}
}
fn calculate_optimized_constants(
r_f: usize,
r_p: usize,
constants: Vec<[F; T]>,
mds: &MDSMatrix<F, T, RATE>,
) -> OptimizedConstants<F, T> {
let inverse_mds = mds.invert();
let (number_of_rounds, r_f_half) = (r_f + r_p, r_f / 2);
assert_eq!(constants.len(), number_of_rounds);
let mut constants_start: Vec<[F; T]> = vec![[F::zero(); T]; r_f_half];
constants_start[0] = constants[0].clone();
for (optimized, constants) in constants_start
.iter_mut()
.skip(1)
.zip(constants.iter().skip(1))
{
*optimized = inverse_mds.mul_constants(constants);
}
let mut acc = constants[r_f_half + r_p].clone();
let mut constants_partial = vec![F::zero(); r_p];
for (optimized, constants) in constants_partial
.iter_mut()
.rev()
.zip(constants.iter().skip(r_f_half).rev().skip(r_f_half))
{
let mut tmp = inverse_mds.mul_constants(&acc);
*optimized = tmp[0];
tmp[0] = F::zero();
for ((acc, tmp), constant) in acc
.iter_mut()
.zip(tmp.into_iter())
.zip(constants.into_iter())
{
*acc = tmp + constant
}
}
constants_start.push(inverse_mds.mul_constants(&acc));
let mut constants_end: Vec<[F; T]> = vec![[F::zero(); T]; r_f_half - 1];
for (optimized, constants) in constants_end
.iter_mut()
.zip(constants.iter().skip(r_f_half + r_p + 1))
{
*optimized = inverse_mds.mul_constants(constants);
}
OptimizedConstants {
start: constants_start,
partial: constants_partial,
end: constants_end,
}
}
fn calculate_sparse_matrices(
r_p: usize,
mds: &MDSMatrix<F, T, RATE>,
) -> (Vec<SparseMDSMatrix<F, T, RATE>>, MDSMatrix<F, T, RATE>) {
let mds = mds.transpose();
let mut acc = mds.clone();
let mut sparse_matrices = (0..r_p)
.map(|_| {
let (m_prime, m_prime_prime) = acc.factorise();
acc = mds.mul(&m_prime);
m_prime_prime
})
.collect::<Vec<SparseMDSMatrix<F, T, RATE>>>();
sparse_matrices.reverse();
(sparse_matrices, acc.transpose())
}
}
#[cfg(test)]
pub(super) mod tests {
use halo2curves::FieldExt;
use super::MDSMatrix;
use crate::grain::Grain;
pub(crate) struct SpecRef<F: FieldExt, const T: usize, const RATE: usize> {
pub(crate) r_f: usize,
pub(crate) r_p: usize,
pub(crate) mds: MDSMatrix<F, T, RATE>,
pub(crate) constants: Vec<[F; T]>,
}
impl<F: FieldExt, const T: usize, const RATE: usize> SpecRef<F, T, RATE> {
pub(crate) fn new(r_f: usize, r_p: usize) -> Self {
let (constants, mds) = Grain::generate(r_f, r_p);
SpecRef {
r_f,
r_p,
mds,
constants,
}
}
}
}