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
use crate::{
    lookups::{Lookup, LookupTableIDs},
    mips::{
        column::{
            ColumnAlias as MIPSColumn, MIPS_BYTE_COUNTER_OFF, MIPS_CHUNK_BYTES_LEN,
            MIPS_END_OF_PREIMAGE_OFF, MIPS_HASH_COUNTER_OFF, MIPS_HAS_N_BYTES_OFF,
            MIPS_LENGTH_BYTES_OFF, MIPS_NUM_BYTES_READ_OFF, MIPS_PREIMAGE_BYTES_OFF,
            MIPS_PREIMAGE_CHUNK_OFF, MIPS_PREIMAGE_KEY,
        },
        interpreter::InterpreterEnv,
    },
    E,
};
use ark_ff::Field;
use kimchi::circuits::{
    expr::{ConstantExpr, ConstantTerm::Literal, Expr, ExprInner, Operations, Variable},
    gate::CurrOrNext,
};
use kimchi_msm::columns::{Column, ColumnIndexer as _};
use std::array;

/// The environment keeping the constraints between the different polynomials
pub struct Env<Fp> {
    pub scratch_state_idx: usize,
    /// A list of constraints, which are multi-variate polynomials over a field,
    /// represented using the expression framework of `kimchi`.
    pub constraints: Vec<E<Fp>>,
    pub lookups: Vec<Lookup<E<Fp>>>,
}

impl<Fp: Field> Default for Env<Fp> {
    fn default() -> Self {
        Self {
            scratch_state_idx: 0,
            constraints: Vec::new(),
            lookups: Vec::new(),
        }
    }
}

impl<Fp: Field> InterpreterEnv for Env<Fp> {
    /// In the concrete implementation for the constraints, the interpreter will
    /// work over columns. The position in this case can be seen as a new
    /// variable/input of our circuit.
    type Position = MIPSColumn;

    // Use one of the available columns. It won't create a new column every time
    // this function is called. The number of columns is defined upfront by
    // crate::mips::witness::SCRATCH_SIZE.
    fn alloc_scratch(&mut self) -> Self::Position {
        // All columns are implemented using a simple index, and a name is given
        // to the index. See crate::SCRATCH_SIZE for the maximum number of
        // columns the circuit can use.
        let scratch_idx = self.scratch_state_idx;
        self.scratch_state_idx += 1;
        MIPSColumn::ScratchState(scratch_idx)
    }

    type Variable = Expr<ConstantExpr<Fp>, Column>;

    fn variable(&self, column: Self::Position) -> Self::Variable {
        Expr::Atom(ExprInner::Cell(Variable {
            col: column.to_column(),
            row: CurrOrNext::Curr,
        }))
    }

    fn add_constraint(&mut self, assert_equals_zero: Self::Variable) {
        self.constraints.push(assert_equals_zero)
    }

    fn check_is_zero(_assert_equals_zero: &Self::Variable) {
        // No-op, witness only
    }

    fn check_equal(_x: &Self::Variable, _y: &Self::Variable) {
        // No-op, witness only
    }

    fn check_boolean(_x: &Self::Variable) {
        // No-op, witness only
    }

    fn add_lookup(&mut self, lookup: Lookup<Self::Variable>) {
        self.lookups.push(lookup);
    }

    fn instruction_counter(&self) -> Self::Variable {
        self.variable(MIPSColumn::InstructionCounter)
    }

    fn increase_instruction_counter(&mut self) {
        // No-op, witness only
    }

    unsafe fn fetch_register(
        &mut self,
        _idx: &Self::Variable,
        output: Self::Position,
    ) -> Self::Variable {
        self.variable(output)
    }

    unsafe fn push_register_if(
        &mut self,
        _idx: &Self::Variable,
        _value: Self::Variable,
        _if_is_true: &Self::Variable,
    ) {
        // No-op, witness only
    }

    unsafe fn fetch_register_access(
        &mut self,
        _idx: &Self::Variable,
        output: Self::Position,
    ) -> Self::Variable {
        self.variable(output)
    }

    unsafe fn push_register_access_if(
        &mut self,
        _idx: &Self::Variable,
        _value: Self::Variable,
        _if_is_true: &Self::Variable,
    ) {
        // No-op, witness only
    }

    unsafe fn fetch_memory(
        &mut self,
        _addr: &Self::Variable,
        output: Self::Position,
    ) -> Self::Variable {
        self.variable(output)
    }

    unsafe fn push_memory(&mut self, _addr: &Self::Variable, _value: Self::Variable) {
        // No-op, witness only
    }

    unsafe fn fetch_memory_access(
        &mut self,
        _addr: &Self::Variable,
        output: Self::Position,
    ) -> Self::Variable {
        self.variable(output)
    }

    unsafe fn push_memory_access(&mut self, _addr: &Self::Variable, _value: Self::Variable) {
        // No-op, witness only
    }

    fn constant(x: u32) -> Self::Variable {
        Self::Variable::constant(Operations::from(Literal(Fp::from(x))))
    }

    unsafe fn bitmask(
        &mut self,
        _x: &Self::Variable,
        _highest_bit: u32,
        _lowest_bit: u32,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn shift_left(
        &mut self,
        _x: &Self::Variable,
        _by: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn shift_right(
        &mut self,
        _x: &Self::Variable,
        _by: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn shift_right_arithmetic(
        &mut self,
        _x: &Self::Variable,
        _by: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn test_zero(
        &mut self,
        _x: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn inverse_or_zero(
        &mut self,
        _x: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    fn equal(&mut self, x: &Self::Variable, y: &Self::Variable) -> Self::Variable {
        self.is_zero(&(x.clone() - y.clone()))
    }

    unsafe fn test_less_than(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn test_less_than_signed(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn and_witness(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn nor_witness(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn or_witness(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn xor_witness(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn add_witness(
        &mut self,
        _y: &Self::Variable,
        _x: &Self::Variable,
        out_position: Self::Position,
        overflow_position: Self::Position,
    ) -> (Self::Variable, Self::Variable) {
        (
            self.variable(out_position),
            self.variable(overflow_position),
        )
    }

    unsafe fn sub_witness(
        &mut self,
        _y: &Self::Variable,
        _x: &Self::Variable,
        out_position: Self::Position,
        underflow_position: Self::Position,
    ) -> (Self::Variable, Self::Variable) {
        (
            self.variable(out_position),
            self.variable(underflow_position),
        )
    }

    unsafe fn mul_signed_witness(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn mul_hi_lo_signed(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position_hi: Self::Position,
        position_lo: Self::Position,
    ) -> (Self::Variable, Self::Variable) {
        (self.variable(position_hi), self.variable(position_lo))
    }

    unsafe fn mul_hi_lo(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position_hi: Self::Position,
        position_lo: Self::Position,
    ) -> (Self::Variable, Self::Variable) {
        (self.variable(position_hi), self.variable(position_lo))
    }

    unsafe fn divmod_signed(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position_quotient: Self::Position,
        position_remainder: Self::Position,
    ) -> (Self::Variable, Self::Variable) {
        (
            self.variable(position_quotient),
            self.variable(position_remainder),
        )
    }

    unsafe fn divmod(
        &mut self,
        _x: &Self::Variable,
        _y: &Self::Variable,
        position_quotient: Self::Position,
        position_remainder: Self::Position,
    ) -> (Self::Variable, Self::Variable) {
        (
            self.variable(position_quotient),
            self.variable(position_remainder),
        )
    }

    unsafe fn count_leading_zeros(
        &mut self,
        _x: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    unsafe fn count_leading_ones(
        &mut self,
        _x: &Self::Variable,
        position: Self::Position,
    ) -> Self::Variable {
        self.variable(position)
    }

    fn copy(&mut self, x: &Self::Variable, position: Self::Position) -> Self::Variable {
        let res = self.variable(position);
        self.constraints.push(x.clone() - res.clone());
        res
    }

    fn set_halted(&mut self, _flag: Self::Variable) {
        // TODO
    }

    fn report_exit(&mut self, _exit_code: &Self::Variable) {}

    /// This function checks that the preimage is read correctly.
    /// It adds 13 constraints, and 5 lookups for the communication channel.
    /// In particular, at every step it writes the bytes of the preimage into
    /// the channel (excluding the length bytes) and it reads the hash digest
    /// from the channel when the preimage is fully read.
    /// The output is the actual number of bytes that have been read.
    fn request_preimage_write(
        &mut self,
        _addr: &Self::Variable,
        len: &Self::Variable,
        pos: Self::Position,
    ) -> Self::Variable {
        // How many hashes have been performed so far in the circuit
        let hash_counter = self.variable(Self::Position::ScratchState(MIPS_HASH_COUNTER_OFF));

        // How many bytes have been read from the preimage so far
        let byte_counter = self.variable(Self::Position::ScratchState(MIPS_BYTE_COUNTER_OFF));

        // Whether this is the last step of the preimage or not (boolean)
        let end_of_preimage = self.variable(Self::Position::ScratchState(MIPS_END_OF_PREIMAGE_OFF));

        // How many preimage bytes are being processed in this instruction
        // FIXME: need to connect this to REGISTER_PREIMAGE_OFFSET or pos?
        let num_preimage_bytes_read =
            self.variable(Self::Position::ScratchState(MIPS_NUM_BYTES_READ_OFF));

        // The chunk of at most 4 bytes that is being processed from the
        // preimage in this instruction
        let this_chunk = self.variable(Self::Position::ScratchState(MIPS_PREIMAGE_CHUNK_OFF));

        // The preimage key composed of 248 bits
        let preimage_key = self.variable(Self::Position::ScratchState(MIPS_PREIMAGE_KEY));

        // The (at most) 4 bytes that are being processed from the preimage
        let bytes: [_; MIPS_CHUNK_BYTES_LEN] = array::from_fn(|i| {
            self.variable(Self::Position::ScratchState(MIPS_PREIMAGE_BYTES_OFF + i))
        });

        // The (at most) 4 bytes that are being read from the bytelength
        let length_bytes: [_; MIPS_CHUNK_BYTES_LEN] = array::from_fn(|i| {
            self.variable(Self::Position::ScratchState(MIPS_LENGTH_BYTES_OFF + i))
        });

        // Whether the preimage chunk read has at least n bytes (1, 2, 3, or 4).
        // It will be all zero when the syscall reads the bytelength prefix.
        let has_n_bytes: [_; MIPS_CHUNK_BYTES_LEN] = array::from_fn(|i| {
            self.variable(Self::Position::ScratchState(MIPS_HAS_N_BYTES_OFF + i))
        });

        // The actual number of bytes read in this instruction, will be 0 <= x <= len <= 4
        let actual_read_bytes = self.variable(pos);

        // EXTRA 13 CONSTRAINTS

        // 5 Booleanity constraints
        {
            for var in has_n_bytes.iter() {
                self.assert_boolean(var.clone());
            }
            self.assert_boolean(end_of_preimage.clone());
        }

        // + 4 constraints
        {
            // Expressions that are nonzero when the exact corresponding number
            // of preimage bytes are read (case 0 bytes used when bytelength is read)
            // TODO: embed any more complex logic to know how many bytes are read
            //       depending on the address and length as in the witness?
            // FIXME: use the lines below when the issue with `equal` is solved
            //        that will bring the number of constraints from 23 to 31
            //        (meaning the unit test needs to be manually adapted)
            // let preimage_1 = self.equal(&num_preimage_bytes_read, &Expr::from(1));
            // let preimage_2 = self.equal(&num_preimage_bytes_read, &Expr::from(2));
            // let preimage_3 = self.equal(&num_preimage_bytes_read, &Expr::from(3));
            // let preimage_4 = self.equal(&num_preimage_bytes_read, &Expr::from(4));

            let preimage_1 = (num_preimage_bytes_read.clone())
                * (num_preimage_bytes_read.clone() - Expr::from(2))
                * (num_preimage_bytes_read.clone() - Expr::from(3))
                * (num_preimage_bytes_read.clone() - Expr::from(4));
            let preimage_2 = (num_preimage_bytes_read.clone())
                * (num_preimage_bytes_read.clone() - Expr::from(1))
                * (num_preimage_bytes_read.clone() - Expr::from(3))
                * (num_preimage_bytes_read.clone() - Expr::from(4));
            let preimage_3 = (num_preimage_bytes_read.clone())
                * (num_preimage_bytes_read.clone() - Expr::from(1))
                * (num_preimage_bytes_read.clone() - Expr::from(2))
                * (num_preimage_bytes_read.clone() - Expr::from(4));
            let preimage_4 = (num_preimage_bytes_read.clone())
                * (num_preimage_bytes_read.clone() - Expr::from(1))
                * (num_preimage_bytes_read.clone() - Expr::from(2))
                * (num_preimage_bytes_read.clone() - Expr::from(3));

            // Constrain the byte decomposition of the preimage chunk
            // NOTE: these constraints also hold when 0 preimage bytes are read
            {
                // When only 1 preimage byte is read, the chunk equals byte[0]
                self.add_constraint(preimage_1 * (this_chunk.clone() - bytes[0].clone()));
                // When 2 bytes are read, the chunk is equal to the
                // byte[0] * 2^8 + byte[1]
                self.add_constraint(
                    preimage_2
                        * (this_chunk.clone()
                            - (bytes[0].clone() * Expr::from(2u64.pow(8)) + bytes[1].clone())),
                );
                // When 3 bytes are read, the chunk is equal to
                // byte[0] * 2^16 + byte[1] * 2^8 + byte[2]
                self.add_constraint(
                    preimage_3
                        * (this_chunk.clone()
                            - (bytes[0].clone() * Expr::from(2u64.pow(16))
                                + bytes[1].clone() * Expr::from(2u64.pow(8))
                                + bytes[2].clone())),
                );
                // When all 4 bytes are read, the chunk is equal to
                // byte[0] * 2^24 + byte[1] * 2^16 + byte[2] * 2^8 + byte[3]
                self.add_constraint(
                    preimage_4
                        * (this_chunk.clone()
                            - (bytes[0].clone() * Expr::from(2u64.pow(24))
                                + bytes[1].clone() * Expr::from(2u64.pow(16))
                                + bytes[2].clone() * Expr::from(2u64.pow(8))
                                + bytes[3].clone())),
                );
            }

            // +4 constraints
            // Constrain the bytes flags depending on the number of preimage
            // bytes read in this row
            {
                // When at least has_1_byte, then any number of bytes can be
                // read <=> Check that you can only read 1, 2, 3 or 4 bytes
                self.add_constraint(
                    has_n_bytes[0].clone()
                        * (num_preimage_bytes_read.clone() - Expr::from(1))
                        * (num_preimage_bytes_read.clone() - Expr::from(2))
                        * (num_preimage_bytes_read.clone() - Expr::from(3))
                        * (num_preimage_bytes_read.clone() - Expr::from(4)),
                );

                // When at least has_2_byte, then any number of bytes can be
                // read from the preimage except 1
                self.add_constraint(
                    has_n_bytes[1].clone()
                        * (num_preimage_bytes_read.clone() - Expr::from(2))
                        * (num_preimage_bytes_read.clone() - Expr::from(3))
                        * (num_preimage_bytes_read.clone() - Expr::from(4)),
                );
                // When at least has_3_byte, then any number of bytes can be
                // read from the preimage except 1 nor 2
                self.add_constraint(
                    has_n_bytes[2].clone()
                        * (num_preimage_bytes_read.clone() - Expr::from(3))
                        * (num_preimage_bytes_read.clone() - Expr::from(4)),
                );

                // When has_4_byte, then only can read 4 preimage bytes
                self.add_constraint(
                    has_n_bytes[3].clone() * (num_preimage_bytes_read.clone() - Expr::from(4)),
                );
            }
        }

        // FIXED LOOKUPS

        // Byte checks with lookups: both preimage and length bytes are checked
        // TODO: think of a way to merge these together to perform 4 lookups
        // instead of 8 per row
        // FIXME: understand if length bytes can ever be read together with
        // preimage bytes. If not, then we can merge the lookups and just run
        // 4 lookups per row for the byte checks. AKA: does the oracle always
        // read the length bytes first and then the preimage bytes, with no
        // overlapping?
        for byte in bytes.iter() {
            self.add_lookup(Lookup::read_one(
                LookupTableIDs::ByteLookup,
                vec![byte.clone()],
            ));
        }
        for b in length_bytes.iter() {
            self.add_lookup(Lookup::read_one(
                LookupTableIDs::ByteLookup,
                vec![b.clone()],
            ));
        }

        // Check that 0 <= preimage read <= actual read <= len <= 4
        self.lookup_2bits(len);
        self.lookup_2bits(&actual_read_bytes);
        self.lookup_2bits(&num_preimage_bytes_read);
        self.lookup_2bits(&(len.clone() - actual_read_bytes.clone()));
        self.lookup_2bits(&(actual_read_bytes.clone() - num_preimage_bytes_read.clone()));

        // COMMUNICATION CHANNEL: Write preimage chunk (1, 2, 3, or 4 bytes)
        for i in 0..MIPS_CHUNK_BYTES_LEN {
            self.add_lookup(Lookup::write_if(
                has_n_bytes[i].clone(),
                LookupTableIDs::SyscallLookup,
                vec![
                    hash_counter.clone(),
                    byte_counter.clone() + Expr::from(i as u64),
                    bytes[i].clone(),
                ],
            ));
        }

        // COMMUNICATION CHANNEL: Read hash output
        // If no more bytes left to be read, then the end of the preimage is
        // true.
        // TODO: keep track of counter to diminish the number of bytes at
        // each step and check it is zero at the end?
        self.add_lookup(Lookup::read_if(
            end_of_preimage,
            LookupTableIDs::SyscallLookup,
            vec![hash_counter.clone(), preimage_key],
        ));

        // Return actual length read as variable, stored in `pos`
        actual_read_bytes
    }

    fn request_hint_write(&mut self, _addr: &Self::Variable, _len: &Self::Variable) {
        // No-op, witness only
    }
}