halo2curves/ff_ext/
quadratic.rs

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
use ff::Field;
use subtle::{Choice, CtOption};

use super::{
    cubic::{CubicExtField, CubicSparseMul},
    ExtField,
};

pub trait QuadSparseMul {
    type Base: ExtField;

    fn mul_by_014(
        lhs: &mut QuadExtField<CubicExtField<Self::Base>>,
        c0: &Self::Base,
        c1: &Self::Base,
        c4: &Self::Base,
    ) where
        CubicExtField<Self::Base>: CubicSparseMul<Base = Self::Base> + ExtField,
    {
        let aa = CubicExtField::mul_by_01(&lhs.c0, c0, c1);
        let bb = CubicExtField::mul_by_1(&lhs.c1, c4);
        let t0 = &(lhs.c1 + lhs.c0);
        let t1 = *c1 + c4;
        lhs.c1 = CubicExtField::mul_by_01(t0, c0, &t1) - (aa + bb);
        lhs.c0 = bb.mul_by_nonresidue() + aa;
    }

    fn mul_by_034(
        lhs: &mut QuadExtField<CubicExtField<Self::Base>>,
        c0: &Self::Base,
        c3: &Self::Base,
        c4: &Self::Base,
    ) where
        CubicExtField<Self::Base>: CubicSparseMul<Base = Self::Base> + ExtField,
    {
        let t0 = CubicExtField {
            c0: lhs.c0.c0 * c0,
            c1: lhs.c0.c1 * c0,
            c2: lhs.c0.c2 * c0,
        };
        let t1 = CubicExtField::mul_by_01(&lhs.c1, c3, c4);
        let t2 = lhs.c0 + lhs.c1;
        let t3 = *c0 + c3;
        lhs.c1 = CubicExtField::mul_by_01(&t2, &t3, c4) - t0 - t1;
        lhs.c0 = t0 + t1.mul_by_nonresidue();
    }
}

// Algorithm 9 of https://eprint.iacr.org/2012/685.pdf
pub fn sqrt_algo9<F: ExtField, S: AsRef<[u64]>>(
    e: &QuadExtField<F>,
    q_minus_3_over_4: S,
    q_minus_1_over_2: S,
) -> subtle::CtOption<QuadExtField<F>>
where
    QuadExtField<F>: QuadExtFieldArith<Base = F> + ExtField,
{
    if e.is_zero().into() {
        subtle::CtOption::new(QuadExtField::ZERO, subtle::Choice::from(1))
    } else {
        let mut a1 = e.pow(q_minus_3_over_4);

        let alpha = a1.square();
        let alpha = alpha * e;

        let mut a0 = alpha;
        a0.frobenius_map(1);
        let a0 = a0 * alpha;

        let neg1 = QuadExtField::<F> {
            c0: F::ZERO - F::ONE,
            c1: F::ZERO,
        };

        if a0 == neg1 {
            subtle::CtOption::new(a0, subtle::Choice::from(0))
        } else {
            a1.mul_assign(e);

            if alpha == neg1 {
                a1.mul_assign(&QuadExtField::<F> {
                    c0: F::ZERO,
                    c1: F::ONE,
                });
            } else {
                let alpha = alpha + QuadExtField::<F>::ONE;
                let alpha = alpha.pow(q_minus_1_over_2);
                a1.mul_assign(&alpha);
            }
            subtle::CtOption::new(a1, subtle::Choice::from(1))
        }
    }
}

// Algorithm 10 of https://eprint.iacr.org/2012/685.pdf
pub fn sqrt_algo10<F: ExtField, S: AsRef<[u64]>>(
    el: &QuadExtField<F>,
    precompute_e: &QuadExtField<F>,
    precompute_f: &QuadExtField<F>,
    q_minus_1_over_4: S,
) -> subtle::CtOption<QuadExtField<F>>
where
    QuadExtField<F>: QuadExtFieldArith<Base = F> + ExtField,
{
    let b = el.pow_vartime(q_minus_1_over_4);

    let b_2 = b.square();
    let mut b_2_q = b_2;
    b_2_q.frobenius_map(1);

    let a0 = b_2_q * b_2;
    let neg1 = QuadExtField::<F> {
        c0: F::ZERO - F::ONE,
        c1: F::ZERO,
    };

    if a0 == neg1 {
        CtOption::new(a0, Choice::from(0))
    } else {
        let mut x = b;
        x.frobenius_map(1);
        if x * b == QuadExtField::ONE {
            let x0 = (b_2 * el).c0.sqrt().unwrap();
            x.c0.mul_assign(x0);
            x.c1.mul_assign(x0);
            CtOption::new(x, Choice::from(1))
        } else {
            let x0 = (b_2 * precompute_f * el).sqrt().unwrap();
            x *= x0 * precompute_e;
            CtOption::new(x, Choice::from(1))
        }
    }
}

pub enum SQRT<F: Field> {
    Algorithm9 {
        q_minus_3_over_4: &'static [u64],
        q_minus_1_over_2: &'static [u64],
    },
    Algorithm10 {
        precompute_e: QuadExtField<F>,
        precompute_f: QuadExtField<F>,
        q_minus_1_over_4: &'static [u64],
    },
    Unimplemented,
}

pub trait QuadExtFieldArith {
    type Base: ExtField;
    const SQRT: SQRT<Self::Base> = SQRT::Unimplemented;

    fn mul_assign(lhs: &mut QuadExtField<Self::Base>, rhs: &QuadExtField<Self::Base>) {
        let v0 = lhs.c0 * rhs.c0;
        let v1 = lhs.c1 * rhs.c1;
        lhs.c1 = (lhs.c0 + lhs.c1) * (rhs.c0 + rhs.c1) - (v0 + v1);
        lhs.c0 = v0 + v1.mul_by_nonresidue();
    }

    fn square_assign(el: &mut QuadExtField<Self::Base>) {
        let ab = el.c0 * el.c1;
        let c0c1 = el.c0 + el.c1;
        let c0 = (el.c1.mul_by_nonresidue() + el.c0) * c0c1 - ab;
        el.c1 = ab.double();
        el.c0 = c0 - ab.mul_by_nonresidue();
    }
}

#[cfg(feature = "derive_serde")]
use serde::{Deserialize, Serialize};

#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "derive_serde", derive(Serialize, Deserialize))]
pub struct QuadExtField<F: ff::Field> {
    pub(crate) c0: F,
    pub(crate) c1: F,
}

impl<F: ff::Field> QuadExtField<F> {
    #[inline]
    pub const fn new(c0: F, c1: F) -> Self {
        Self { c0, c1 }
    }

    #[inline]
    pub const fn zero() -> Self {
        Self {
            c0: F::ZERO,
            c1: F::ZERO,
        }
    }

    #[inline]
    pub const fn one() -> Self {
        Self {
            c0: F::ONE,
            c1: F::ZERO,
        }
    }

    #[inline]
    pub fn double(&self) -> Self {
        Self {
            c0: self.c0.double(),
            c1: self.c1.double(),
        }
    }

    #[inline]
    pub fn add(&self, other: &Self) -> Self {
        Self {
            c0: self.c0 + other.c0,
            c1: self.c1 + other.c1,
        }
    }

    #[inline]
    pub fn sub(&self, other: &Self) -> Self {
        Self {
            c0: self.c0 - other.c0,
            c1: self.c1 - other.c1,
        }
    }

    #[inline]
    pub fn neg(&self) -> Self {
        Self {
            c0: -self.c0,
            c1: -self.c1,
        }
    }

    #[inline]
    pub fn conjugate(&mut self) {
        self.c1 = -self.c1;
    }
}

impl<F: ExtField> QuadExtField<F>
where
    Self: QuadExtFieldArith<Base = F>,
{
    pub fn mul(&self, rhs: &Self) -> Self {
        let mut lhs = *self;
        Self::mul_assign(&mut lhs, rhs);
        lhs
    }

    pub fn mul_assign(&mut self, rhs: &Self) {
        <Self as QuadExtFieldArith>::mul_assign(self, rhs);
    }

    pub fn square(el: &Self) -> Self {
        let mut el = *el;
        Self::square_assign(&mut el);
        el
    }

    pub fn square_assign(&mut self) {
        <Self as QuadExtFieldArith>::square_assign(self);
    }

    pub fn norm(&self) -> F {
        self.c0.square() - self.c1.square().mul_by_nonresidue()
    }
}

impl<F: ExtField> Field for QuadExtField<F>
where
    QuadExtField<F>: QuadExtFieldArith<Base = F> + ExtField,
{
    const ZERO: Self = Self::zero();
    const ONE: Self = Self::one();

    fn random(mut rng: impl rand_core::RngCore) -> Self {
        Self::new(F::random(&mut rng), F::random(&mut rng))
    }

    fn is_zero(&self) -> subtle::Choice {
        self.c0.is_zero() & self.c1.is_zero()
    }

    fn square(&self) -> Self {
        QuadExtField::square(self)
    }

    fn double(&self) -> Self {
        self.double()
    }

    fn sqrt(&self) -> subtle::CtOption<Self> {
        match Self::SQRT {
            SQRT::Algorithm9 {
                q_minus_3_over_4,
                q_minus_1_over_2,
            } => sqrt_algo9(self, q_minus_3_over_4, q_minus_1_over_2),
            SQRT::Algorithm10 {
                precompute_e,
                precompute_f,
                q_minus_1_over_4,
            } => sqrt_algo10(self, &precompute_e, &precompute_f, q_minus_1_over_4),
            SQRT::Unimplemented => unimplemented!(),
        }
    }

    fn sqrt_ratio(_: &Self, _: &Self) -> (subtle::Choice, Self) {
        unimplemented!()
    }

    fn invert(&self) -> subtle::CtOption<Self> {
        self.norm().invert().map(|t| Self {
            c0: self.c0 * t,
            c1: self.c1 * -t,
        })
    }
}

impl<F: ff::Field> subtle::ConditionallySelectable for QuadExtField<F> {
    fn conditional_select(a: &Self, b: &Self, choice: subtle::Choice) -> Self {
        QuadExtField {
            c0: F::conditional_select(&a.c0, &b.c0, choice),
            c1: F::conditional_select(&a.c1, &b.c1, choice),
        }
    }
}

impl<F: ff::Field> subtle::ConstantTimeEq for QuadExtField<F> {
    fn ct_eq(&self, other: &Self) -> subtle::Choice {
        self.c0.ct_eq(&other.c0) & self.c1.ct_eq(&other.c1)
    }
}