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
use crate::{
    circuit_design::{ColAccessCap, ColWriteCap, DirectWitnessCap, LookupCap},
    serialization::interpreter::limb_decompose_ff,
    test::test_circuit::{
        columns::{TestColumn, N_FSEL_TEST},
        lookups::LookupTable,
    },
    LIMB_BITSIZE, N_LIMBS,
};
use ark_ff::{Field, PrimeField, Zero};

fn fill_limbs_a_b<
    F: PrimeField,
    Ff: PrimeField,
    Env: ColAccessCap<F, TestColumn> + ColWriteCap<F, TestColumn>,
>(
    env: &mut Env,
    a: Ff,
    b: Ff,
) -> ([Env::Variable; N_LIMBS], [Env::Variable; N_LIMBS]) {
    let a_limbs: [Env::Variable; N_LIMBS] =
        limb_decompose_ff::<F, Ff, LIMB_BITSIZE, N_LIMBS>(&a).map(Env::constant);
    let b_limbs: [Env::Variable; N_LIMBS] =
        limb_decompose_ff::<F, Ff, LIMB_BITSIZE, N_LIMBS>(&b).map(Env::constant);
    a_limbs.iter().enumerate().for_each(|(i, var)| {
        env.write_column(TestColumn::A(i), var);
    });
    b_limbs.iter().enumerate().for_each(|(i, var)| {
        env.write_column(TestColumn::B(i), var);
    });
    (a_limbs, b_limbs)
}

/// A constraint function for A + B - C that reads values from limbs A
/// and B, and additionally returns resulting value in C.
pub fn constrain_addition<F: PrimeField, Env: ColAccessCap<F, TestColumn>>(env: &mut Env) {
    let a_limbs: [Env::Variable; N_LIMBS] =
        core::array::from_fn(|i| Env::read_column(env, TestColumn::A(i)));
    let b_limbs: [Env::Variable; N_LIMBS] =
        core::array::from_fn(|i| Env::read_column(env, TestColumn::B(i)));
    // fix cloning
    let c_limbs: [Env::Variable; N_LIMBS] =
        core::array::from_fn(|i| Env::read_column(env, TestColumn::C(i)));
    let equation: [Env::Variable; N_LIMBS] =
        core::array::from_fn(|i| a_limbs[i].clone() * b_limbs[i].clone() - c_limbs[i].clone());
    equation.iter().for_each(|var| {
        env.assert_zero(var.clone());
    });
}

/// Circuit generator function for A + B - C, with D = 0.
pub fn test_addition<
    F: PrimeField,
    Ff: PrimeField,
    Env: ColAccessCap<F, TestColumn> + ColWriteCap<F, TestColumn>,
>(
    env: &mut Env,
    a: Ff,
    b: Ff,
) {
    let (a_limbs, b_limbs) = fill_limbs_a_b(env, a, b);

    (0..N_LIMBS).for_each(|i| {
        env.write_column(TestColumn::C(i), &(a_limbs[i].clone() + b_limbs[i].clone()));
        env.write_column(TestColumn::D(i), &Env::constant(Zero::zero()));
    });

    constrain_addition(env);
}

/// A constraint function for A * B - D that reads values from limbs A
/// and B, and multiplicationally returns resulting value in D.
pub fn constrain_multiplication<F: PrimeField, Env: ColAccessCap<F, TestColumn>>(env: &mut Env) {
    let a_limbs: [Env::Variable; N_LIMBS] =
        core::array::from_fn(|i| Env::read_column(env, TestColumn::A(i)));
    let b_limbs: [Env::Variable; N_LIMBS] =
        core::array::from_fn(|i| Env::read_column(env, TestColumn::B(i)));
    // fix cloning
    let d_limbs: [Env::Variable; N_LIMBS] =
        core::array::from_fn(|i| Env::read_column(env, TestColumn::D(i)));
    let equation: [Env::Variable; N_LIMBS] =
        core::array::from_fn(|i| a_limbs[i].clone() * b_limbs[i].clone() - d_limbs[i].clone());
    equation.iter().for_each(|var| {
        env.assert_zero(var.clone());
    });
}

/// Circuit generator function for A * B - C, with D = 0.
pub fn test_multiplication<
    F: PrimeField,
    Ff: PrimeField,
    Env: ColAccessCap<F, TestColumn> + ColWriteCap<F, TestColumn>,
>(
    env: &mut Env,
    a: Ff,
    b: Ff,
) {
    let (a_limbs, b_limbs) = fill_limbs_a_b(env, a, b);

    (0..N_LIMBS).for_each(|i| {
        env.write_column(TestColumn::D(i), &(a_limbs[i].clone() * b_limbs[i].clone()));
        env.write_column(TestColumn::C(i), &Env::constant(Zero::zero()));
    });

    constrain_multiplication(env);
}

/// A constraint function for A * B - D that reads values from limbs A
/// and B, and multiplication_constally returns resulting value in D.
pub fn constrain_test_const<F: PrimeField, Env: ColAccessCap<F, TestColumn>>(
    env: &mut Env,
    constant: F,
) {
    let a0 = Env::read_column(env, TestColumn::A(0));
    let b0 = Env::read_column(env, TestColumn::B(0));
    let equation = a0.clone() * b0.clone() - Env::constant(constant);
    env.assert_zero(equation.clone());
}

/// Circuit generator function for A_0 * B_0 - const, with every other column = 0
pub fn test_const<F: PrimeField, Env: ColAccessCap<F, TestColumn> + ColWriteCap<F, TestColumn>>(
    env: &mut Env,
    a: F,
    b: F,
    constant: F,
) {
    env.write_column(TestColumn::A(0), &Env::constant(a));
    env.write_column(TestColumn::B(0), &Env::constant(b));

    constrain_test_const(env, constant);
}

/// A constraint function for A_0 + B_0 - FIXED_SEL_1
pub fn constrain_test_fixed_sel<F: PrimeField, Env: ColAccessCap<F, TestColumn>>(env: &mut Env) {
    let a0 = Env::read_column(env, TestColumn::A(0));
    let b0 = Env::read_column(env, TestColumn::B(0));
    let fixed_e = Env::read_column(env, TestColumn::FixedSel1);
    let equation = a0.clone() + b0.clone() - fixed_e;
    env.assert_zero(equation.clone());
}

/// A constraint function for A_0^7 + B_0 - FIXED_SEL_1
pub fn constrain_test_fixed_sel_degree_7<F: PrimeField, Env: ColAccessCap<F, TestColumn>>(
    env: &mut Env,
) {
    let a0 = Env::read_column(env, TestColumn::A(0));
    let b0 = Env::read_column(env, TestColumn::B(0));
    let fixed_e = Env::read_column(env, TestColumn::FixedSel1);
    let a0_2 = a0.clone() * a0.clone();
    let a0_4 = a0_2.clone() * a0_2.clone();
    let a0_6 = a0_4.clone() * a0_2.clone();
    let a0_7 = a0_6.clone() * a0.clone();
    let equation = a0_7.clone() + b0.clone() - fixed_e;
    env.assert_zero(equation.clone());
}

/// A constraint function for 3 * A_0^7 + 42 * B_0 - FIXED_SEL_1
pub fn constrain_test_fixed_sel_degree_7_with_constants<
    F: PrimeField,
    Env: ColAccessCap<F, TestColumn>,
>(
    env: &mut Env,
) {
    let a0 = Env::read_column(env, TestColumn::A(0));
    let fourty_two = Env::constant(F::from(42u32));
    let three = Env::constant(F::from(3u32));
    let b0 = Env::read_column(env, TestColumn::B(0));
    let fixed_e = Env::read_column(env, TestColumn::FixedSel1);
    let a0_2 = a0.clone() * a0.clone();
    let a0_4 = a0_2.clone() * a0_2.clone();
    let a0_6 = a0_4.clone() * a0_2.clone();
    let a0_7 = a0_6.clone() * a0.clone();
    let equation = three * a0_7.clone() + fourty_two * b0.clone() - fixed_e;
    env.assert_zero(equation.clone());
}

// NB: Assumes non-standard selectors
/// A constraint function for 3 * A_0^7 + B_0 * FIXED_SEL_3
pub fn constrain_test_fixed_sel_degree_7_mul_witness<
    F: PrimeField,
    Env: ColAccessCap<F, TestColumn>,
>(
    env: &mut Env,
) {
    let a0 = Env::read_column(env, TestColumn::A(0));
    let three = Env::constant(F::from(3u32));
    let b0 = Env::read_column(env, TestColumn::B(0));
    let fixed_e = Env::read_column(env, TestColumn::FixedSel3);
    let a0_2 = a0.clone() * a0.clone();
    let a0_4 = a0_2.clone() * a0_2.clone();
    let a0_6 = a0_4.clone() * a0_2.clone();
    let a0_7 = a0_6.clone() * a0.clone();
    let equation = three * a0_7.clone() + b0.clone() * fixed_e;
    env.assert_zero(equation.clone());
}

/// Circuit generator function for A_0 + B_0 - FIXED_SEL_1.
pub fn test_fixed_sel<
    F: PrimeField,
    Env: ColAccessCap<F, TestColumn> + ColWriteCap<F, TestColumn>,
>(
    env: &mut Env,
    a: F,
) {
    env.write_column(TestColumn::A(0), &Env::constant(a));
    let fixed_e = env.read_column(TestColumn::FixedSel1);
    env.write_column(TestColumn::B(0), &(fixed_e - Env::constant(a)));

    constrain_test_fixed_sel(env);
}

/// Circuit generator function for A_0^7 + B_0 - FIXED_SEL_1.
pub fn test_fixed_sel_degree_7<
    F: PrimeField,
    Env: ColAccessCap<F, TestColumn> + ColWriteCap<F, TestColumn>,
>(
    env: &mut Env,
    a: F,
) {
    env.write_column(TestColumn::A(0), &Env::constant(a));
    let a_2 = a * a;
    let a_4 = a_2 * a_2;
    let a_6 = a_4 * a_2;
    let a_7 = a_6 * a;
    let fixed_e = env.read_column(TestColumn::FixedSel1);
    env.write_column(TestColumn::B(0), &(fixed_e - Env::constant(a_7)));
    constrain_test_fixed_sel_degree_7(env);
}

/// Circuit generator function for 3 * A_0^7 + 42 * B_0 - FIXED_SEL_1.
pub fn test_fixed_sel_degree_7_with_constants<
    F: PrimeField,
    Env: ColAccessCap<F, TestColumn> + ColWriteCap<F, TestColumn>,
>(
    env: &mut Env,
    a: F,
) {
    env.write_column(TestColumn::A(0), &Env::constant(a));
    let a_2 = a * a;
    let a_4 = a_2 * a_2;
    let a_6 = a_4 * a_2;
    let a_7 = a_6 * a;
    let fixed_e = env.read_column(TestColumn::FixedSel1);
    let inv_42 = F::from(42u32).inverse().unwrap();
    let three = F::from(3u32);
    env.write_column(
        TestColumn::B(0),
        &((fixed_e - Env::constant(three) * Env::constant(a_7)) * Env::constant(inv_42)),
    );
    constrain_test_fixed_sel_degree_7_with_constants(env);
}

// NB: Assumes non-standard selectors
/// Circuit generator function for 3 * A_0^7 + B_0 * FIXED_SEL_3.
pub fn test_fixed_sel_degree_7_mul_witness<
    F: PrimeField,
    Env: ColAccessCap<F, TestColumn> + ColWriteCap<F, TestColumn> + DirectWitnessCap<F, TestColumn>,
>(
    env: &mut Env,
    a: F,
) {
    env.write_column(TestColumn::A(0), &Env::constant(a));
    let a_2 = a * a;
    let a_4 = a_2 * a_2;
    let a_6 = a_4 * a_2;
    let a_7 = a_6 * a;
    let fixed_e = env.read_column(TestColumn::FixedSel3);
    let three = F::from(3u32);
    let val_fixed_e: F = Env::variable_to_field(fixed_e);
    let inv_fixed_e: F = val_fixed_e.inverse().unwrap();
    let res = -three * a_7 * inv_fixed_e;
    let res_var = Env::constant(res);
    env.write_column(TestColumn::B(0), &res_var);
    constrain_test_fixed_sel_degree_7_mul_witness(env);
}

pub fn constrain_lookups<
    F: PrimeField,
    Env: ColAccessCap<F, TestColumn> + LookupCap<F, TestColumn, LookupTable>,
>(
    env: &mut Env,
) {
    let a0 = Env::read_column(env, TestColumn::A(0));
    let a1 = Env::read_column(env, TestColumn::A(1));

    env.lookup(LookupTable::RangeCheck15, vec![a0.clone()]);
    env.lookup(LookupTable::RangeCheck15, vec![a1.clone()]);

    let cur_index = Env::read_column(env, TestColumn::FixedSel1);
    let prev_index = Env::read_column(env, TestColumn::FixedSel2);
    let next_index = Env::read_column(env, TestColumn::FixedSel3);

    env.lookup(
        LookupTable::RuntimeTable1,
        vec![
            cur_index.clone(),
            prev_index.clone(),
            next_index.clone(),
            Env::constant(F::from(4u64)),
        ],
    );

    // For now we only allow one read per runtime table with runtime_create_column = true.
    //env.lookup(LookupTable::RuntimeTable1, vec![a0.clone(), a1.clone()]);

    env.lookup_runtime_write(
        LookupTable::RuntimeTable2,
        vec![
            Env::constant(F::from(1u64 << 26)),
            Env::constant(F::from(5u64)),
        ],
    );
    env.lookup_runtime_write(
        LookupTable::RuntimeTable2,
        vec![cur_index, Env::constant(F::from(5u64))],
    );
    env.lookup(
        LookupTable::RuntimeTable2,
        vec![
            Env::constant(F::from(1u64 << 26)),
            Env::constant(F::from(5u64)),
        ],
    );
    env.lookup(
        LookupTable::RuntimeTable2,
        vec![prev_index, Env::constant(F::from(5u64))],
    );
}

pub fn lookups_circuit<
    F: PrimeField,
    Env: ColAccessCap<F, TestColumn>
        + ColWriteCap<F, TestColumn>
        + DirectWitnessCap<F, TestColumn>
        + LookupCap<F, TestColumn, LookupTable>,
>(
    env: &mut Env,
    domain_size: usize,
) {
    for row_i in 0..domain_size {
        env.write_column(TestColumn::A(0), &Env::constant(F::from(11u64)));
        env.write_column(TestColumn::A(1), &Env::constant(F::from(17u64)));

        constrain_lookups(env);

        if row_i < domain_size - 1 {
            env.next_row();
        }
    }
}

/// Fixed selectors for the test circuit.
pub fn build_fixed_selectors<F: Field>(domain_size: usize) -> Box<[Vec<F>; N_FSEL_TEST]> {
    // 0 1 2 3 4 ...
    let sel1 = (0..domain_size).map(|i| F::from(i as u64)).collect();
    // 0 0 1 2 3 4 ...
    let sel2 = (0..domain_size)
        .map(|i| {
            if i == 0 {
                F::zero()
            } else {
                F::from((i as u64) - 1)
            }
        })
        .collect();
    // 1 2 3 4 5 ...
    let sel3 = (0..domain_size).map(|i| F::from((i + 1) as u64)).collect();

    Box::new([sel1, sel2, sel3])
}