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
use halo2_base::{gates::GateInstructions, utils::ScalarField, AssignedValue, Context};
use itertools::Itertools;
use std::{
    marker::PhantomData,
    ops::{Index, IndexMut},
};

use crate::bigint::{CRTInteger, ProperCrtUint};

use super::{fp::Reduced, FieldChip, FieldExtConstructor, PrimeField, PrimeFieldChip, Selectable};

/// A fixed length vector of `FieldPoint`s
#[repr(transparent)]
#[derive(Clone, Debug)]
pub struct FieldVector<T>(pub Vec<T>);

impl<T> Index<usize> for FieldVector<T> {
    type Output = T;

    fn index(&self, index: usize) -> &Self::Output {
        &self.0[index]
    }
}

impl<T> IndexMut<usize> for FieldVector<T> {
    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
        &mut self.0[index]
    }
}

impl<T> AsRef<[T]> for FieldVector<T> {
    fn as_ref(&self) -> &[T] {
        &self.0
    }
}

impl<'a, T: Clone, U: From<T>> From<&'a FieldVector<T>> for FieldVector<U> {
    fn from(other: &'a FieldVector<T>) -> Self {
        FieldVector(other.clone().into_iter().map(Into::into).collect())
    }
}

impl<F: ScalarField> From<FieldVector<ProperCrtUint<F>>> for FieldVector<CRTInteger<F>> {
    fn from(other: FieldVector<ProperCrtUint<F>>) -> Self {
        FieldVector(other.into_iter().map(|x| x.0).collect())
    }
}

impl<T, Fp> From<FieldVector<Reduced<T, Fp>>> for FieldVector<T> {
    fn from(value: FieldVector<Reduced<T, Fp>>) -> Self {
        FieldVector(value.0.into_iter().map(|x| x.0).collect())
    }
}

impl<T> IntoIterator for FieldVector<T> {
    type Item = T;
    type IntoIter = std::vec::IntoIter<T>;

    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

/// Contains common functionality for vector operations that can be derived from those of the underlying `FpChip`
#[derive(Clone, Copy, Debug)]
pub struct FieldVectorChip<'fp, F: PrimeField, FpChip: FieldChip<F>> {
    pub fp_chip: &'fp FpChip,
    _f: PhantomData<F>,
}

impl<'fp, F, FpChip> FieldVectorChip<'fp, F, FpChip>
where
    F: PrimeField,
    FpChip: PrimeFieldChip<F>,
    FpChip::FieldType: PrimeField,
{
    pub fn new(fp_chip: &'fp FpChip) -> Self {
        Self { fp_chip, _f: PhantomData }
    }

    pub fn gate(&self) -> &impl GateInstructions<F> {
        self.fp_chip.gate()
    }

    pub fn fp_mul_no_carry<FP>(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FP>,
        fp_point: impl Into<FpChip::UnsafeFieldPoint>,
    ) -> FieldVector<FpChip::UnsafeFieldPoint>
    where
        FP: Into<FpChip::UnsafeFieldPoint>,
    {
        let fp_point = fp_point.into();
        FieldVector(
            a.into_iter().map(|a| self.fp_chip.mul_no_carry(ctx, a, fp_point.clone())).collect(),
        )
    }

    pub fn select<FP>(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FP>,
        b: impl IntoIterator<Item = FP>,
        sel: AssignedValue<F>,
    ) -> FieldVector<FP>
    where
        FpChip: Selectable<F, FP>,
    {
        FieldVector(
            a.into_iter().zip_eq(b).map(|(a, b)| self.fp_chip.select(ctx, a, b, sel)).collect(),
        )
    }

    pub fn load_private<FieldExt, const DEGREE: usize>(
        &self,
        ctx: &mut Context<F>,
        fe: FieldExt,
    ) -> FieldVector<FpChip::FieldPoint>
    where
        FieldExt: FieldExtConstructor<FpChip::FieldType, DEGREE>,
    {
        FieldVector(fe.coeffs().into_iter().map(|a| self.fp_chip.load_private(ctx, a)).collect())
    }

    pub fn load_constant<FieldExt, const DEGREE: usize>(
        &self,
        ctx: &mut Context<F>,
        c: FieldExt,
    ) -> FieldVector<FpChip::FieldPoint>
    where
        FieldExt: FieldExtConstructor<FpChip::FieldType, DEGREE>,
    {
        FieldVector(c.coeffs().into_iter().map(|a| self.fp_chip.load_constant(ctx, a)).collect())
    }

    // signed overflow BigInt functions
    pub fn add_no_carry<A, B>(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = A>,
        b: impl IntoIterator<Item = B>,
    ) -> FieldVector<FpChip::UnsafeFieldPoint>
    where
        A: Into<FpChip::UnsafeFieldPoint>,
        B: Into<FpChip::UnsafeFieldPoint>,
    {
        FieldVector(
            a.into_iter().zip_eq(b).map(|(a, b)| self.fp_chip.add_no_carry(ctx, a, b)).collect(),
        )
    }

    pub fn add_constant_no_carry<A, FieldExt, const DEGREE: usize>(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = A>,
        c: FieldExt,
    ) -> FieldVector<FpChip::UnsafeFieldPoint>
    where
        A: Into<FpChip::UnsafeFieldPoint>,
        FieldExt: FieldExtConstructor<FpChip::FieldType, DEGREE>,
    {
        let c_coeffs = c.coeffs();
        FieldVector(
            a.into_iter()
                .zip_eq(c_coeffs)
                .map(|(a, c)| self.fp_chip.add_constant_no_carry(ctx, a, c))
                .collect(),
        )
    }

    pub fn sub_no_carry<A, B>(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = A>,
        b: impl IntoIterator<Item = B>,
    ) -> FieldVector<FpChip::UnsafeFieldPoint>
    where
        A: Into<FpChip::UnsafeFieldPoint>,
        B: Into<FpChip::UnsafeFieldPoint>,
    {
        FieldVector(
            a.into_iter().zip_eq(b).map(|(a, b)| self.fp_chip.sub_no_carry(ctx, a, b)).collect(),
        )
    }

    pub fn negate(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FpChip::FieldPoint>,
    ) -> FieldVector<FpChip::FieldPoint> {
        FieldVector(a.into_iter().map(|a| self.fp_chip.negate(ctx, a)).collect())
    }

    pub fn scalar_mul_no_carry<A>(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = A>,
        c: i64,
    ) -> FieldVector<FpChip::UnsafeFieldPoint>
    where
        A: Into<FpChip::UnsafeFieldPoint>,
    {
        FieldVector(a.into_iter().map(|a| self.fp_chip.scalar_mul_no_carry(ctx, a, c)).collect())
    }

    pub fn scalar_mul_and_add_no_carry<A, B>(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = A>,
        b: impl IntoIterator<Item = B>,
        c: i64,
    ) -> FieldVector<FpChip::UnsafeFieldPoint>
    where
        A: Into<FpChip::UnsafeFieldPoint>,
        B: Into<FpChip::UnsafeFieldPoint>,
    {
        FieldVector(
            a.into_iter()
                .zip_eq(b)
                .map(|(a, b)| self.fp_chip.scalar_mul_and_add_no_carry(ctx, a, b, c))
                .collect(),
        )
    }

    pub fn check_carry_mod_to_zero(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FpChip::UnsafeFieldPoint>,
    ) {
        for coeff in a {
            self.fp_chip.check_carry_mod_to_zero(ctx, coeff);
        }
    }

    pub fn carry_mod(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FpChip::UnsafeFieldPoint>,
    ) -> FieldVector<FpChip::FieldPoint> {
        FieldVector(a.into_iter().map(|coeff| self.fp_chip.carry_mod(ctx, coeff)).collect())
    }

    pub fn range_check<A>(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = A>,
        max_bits: usize,
    ) where
        A: Into<FpChip::UnsafeFieldPoint>,
    {
        for coeff in a {
            self.fp_chip.range_check(ctx, coeff, max_bits);
        }
    }

    pub fn enforce_less_than(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FpChip::FieldPoint>,
    ) -> FieldVector<FpChip::ReducedFieldPoint> {
        FieldVector(a.into_iter().map(|coeff| self.fp_chip.enforce_less_than(ctx, coeff)).collect())
    }

    pub fn is_soft_zero(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FpChip::FieldPoint>,
    ) -> AssignedValue<F> {
        let mut prev = None;
        for a_coeff in a {
            let coeff = self.fp_chip.is_soft_zero(ctx, a_coeff);
            if let Some(p) = prev {
                let new = self.gate().and(ctx, coeff, p);
                prev = Some(new);
            } else {
                prev = Some(coeff);
            }
        }
        prev.unwrap()
    }

    pub fn is_soft_nonzero(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FpChip::FieldPoint>,
    ) -> AssignedValue<F> {
        let mut prev = None;
        for a_coeff in a {
            let coeff = self.fp_chip.is_soft_nonzero(ctx, a_coeff);
            if let Some(p) = prev {
                let new = self.gate().or(ctx, coeff, p);
                prev = Some(new);
            } else {
                prev = Some(coeff);
            }
        }
        prev.unwrap()
    }

    pub fn is_zero(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FpChip::FieldPoint>,
    ) -> AssignedValue<F> {
        let mut prev = None;
        for a_coeff in a {
            let coeff = self.fp_chip.is_zero(ctx, a_coeff);
            if let Some(p) = prev {
                let new = self.gate().and(ctx, coeff, p);
                prev = Some(new);
            } else {
                prev = Some(coeff);
            }
        }
        prev.unwrap()
    }

    pub fn is_equal_unenforced(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FpChip::ReducedFieldPoint>,
        b: impl IntoIterator<Item = FpChip::ReducedFieldPoint>,
    ) -> AssignedValue<F> {
        let mut acc = None;
        for (a_coeff, b_coeff) in a.into_iter().zip_eq(b) {
            let coeff = self.fp_chip.is_equal_unenforced(ctx, a_coeff, b_coeff);
            if let Some(c) = acc {
                acc = Some(self.gate().and(ctx, coeff, c));
            } else {
                acc = Some(coeff);
            }
        }
        acc.unwrap()
    }

    pub fn assert_equal(
        &self,
        ctx: &mut Context<F>,
        a: impl IntoIterator<Item = FpChip::FieldPoint>,
        b: impl IntoIterator<Item = FpChip::FieldPoint>,
    ) {
        for (a_coeff, b_coeff) in a.into_iter().zip(b) {
            self.fp_chip.assert_equal(ctx, a_coeff, b_coeff)
        }
    }
}

#[macro_export]
macro_rules! impl_field_ext_chip_common {
    // Implementation of the functions in `FieldChip` trait for field extensions that can be derived from `FieldVectorChip`
    () => {
        fn native_modulus(&self) -> &BigUint {
            self.0.fp_chip.native_modulus()
        }

        fn range(&self) -> &Self::RangeChip {
            self.0.fp_chip.range()
        }

        fn limb_bits(&self) -> usize {
            self.0.fp_chip.limb_bits()
        }

        fn load_private(&self, ctx: &mut Context<F>, fe: Self::FieldType) -> Self::FieldPoint {
            self.0.load_private(ctx, fe)
        }

        fn load_constant(&self, ctx: &mut Context<F>, fe: Self::FieldType) -> Self::FieldPoint {
            self.0.load_constant(ctx, fe)
        }

        fn add_no_carry(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::UnsafeFieldPoint>,
            b: impl Into<Self::UnsafeFieldPoint>,
        ) -> Self::UnsafeFieldPoint {
            self.0.add_no_carry(ctx, a.into(), b.into())
        }

        fn add_constant_no_carry(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::UnsafeFieldPoint>,
            c: Self::FieldType,
        ) -> Self::UnsafeFieldPoint {
            self.0.add_constant_no_carry(ctx, a.into(), c)
        }

        fn sub_no_carry(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::UnsafeFieldPoint>,
            b: impl Into<Self::UnsafeFieldPoint>,
        ) -> Self::UnsafeFieldPoint {
            self.0.sub_no_carry(ctx, a.into(), b.into())
        }

        fn negate(&self, ctx: &mut Context<F>, a: Self::FieldPoint) -> Self::FieldPoint {
            self.0.negate(ctx, a)
        }

        fn scalar_mul_no_carry(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::UnsafeFieldPoint>,
            c: i64,
        ) -> Self::UnsafeFieldPoint {
            self.0.scalar_mul_no_carry(ctx, a.into(), c)
        }

        fn scalar_mul_and_add_no_carry(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::UnsafeFieldPoint>,
            b: impl Into<Self::UnsafeFieldPoint>,
            c: i64,
        ) -> Self::UnsafeFieldPoint {
            self.0.scalar_mul_and_add_no_carry(ctx, a.into(), b.into(), c)
        }

        fn check_carry_mod_to_zero(&self, ctx: &mut Context<F>, a: Self::UnsafeFieldPoint) {
            self.0.check_carry_mod_to_zero(ctx, a);
        }

        fn carry_mod(&self, ctx: &mut Context<F>, a: Self::UnsafeFieldPoint) -> Self::FieldPoint {
            self.0.carry_mod(ctx, a)
        }

        fn range_check(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::UnsafeFieldPoint>,
            max_bits: usize,
        ) {
            self.0.range_check(ctx, a.into(), max_bits)
        }

        fn enforce_less_than(
            &self,
            ctx: &mut Context<F>,
            a: Self::FieldPoint,
        ) -> Self::ReducedFieldPoint {
            self.0.enforce_less_than(ctx, a)
        }

        fn is_soft_zero(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::FieldPoint>,
        ) -> AssignedValue<F> {
            let a = a.into();
            self.0.is_soft_zero(ctx, a)
        }

        fn is_soft_nonzero(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::FieldPoint>,
        ) -> AssignedValue<F> {
            let a = a.into();
            self.0.is_soft_nonzero(ctx, a)
        }

        fn is_zero(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::FieldPoint>,
        ) -> AssignedValue<F> {
            let a = a.into();
            self.0.is_zero(ctx, a)
        }

        fn is_equal_unenforced(
            &self,
            ctx: &mut Context<F>,
            a: Self::ReducedFieldPoint,
            b: Self::ReducedFieldPoint,
        ) -> AssignedValue<F> {
            self.0.is_equal_unenforced(ctx, a, b)
        }

        fn assert_equal(
            &self,
            ctx: &mut Context<F>,
            a: impl Into<Self::FieldPoint>,
            b: impl Into<Self::FieldPoint>,
        ) {
            let a = a.into();
            let b = b.into();
            self.0.assert_equal(ctx, a, b)
        }
    };
}