openvm_pairing_guest/halo2curves_shims/bls12_381/
miller_loop.rs

1use alloc::vec::Vec;
2
3use halo2curves_axiom::bls12_381::{Fq, Fq12, Fq2};
4use itertools::izip;
5use openvm_ecc_guest::{
6    algebra::{DivUnsafe, Field},
7    AffinePoint,
8};
9
10use super::Bls12_381;
11use crate::{
12    bls12_381::{BLS12_381_PSEUDO_BINARY_ENCODING, BLS12_381_SEED_ABS},
13    pairing::{
14        Evaluatable, EvaluatedLine, LineMulMType, MillerStep, MultiMillerLoop, UnevaluatedLine,
15    },
16};
17
18impl MillerStep for Bls12_381 {
19    type Fp2 = Fq2;
20
21    /// Miller double step
22    fn miller_double_step(
23        s: &AffinePoint<Self::Fp2>,
24    ) -> (AffinePoint<Self::Fp2>, UnevaluatedLine<Self::Fp2>) {
25        let one = &Self::Fp2::ONE;
26        let two = &(one + one);
27        let three = &(one + two);
28
29        let x = &s.x;
30        let y = &s.y;
31        // λ = (3x^2) / (2y)
32        let lambda = &((three * x * x).div_unsafe(&(two * y)));
33        // x_2s = λ^2 - 2x
34        let x_2s = lambda * lambda - two * x;
35        // y_2s = λ(x - x_2s) - y
36        let y_2s = lambda * (x - x_2s) - y;
37        let two_s = AffinePoint { x: x_2s, y: y_2s };
38
39        // Tangent line
40        //   1 + b' (x_P / y_P) w^-1 + c' (1 / y_P) w^-3
41        // where
42        //   l_{\Psi(S),\Psi(S)}(P) = (λ * x_S - y_S) (1 / y_P)  - λ (x_P / y_P) w^2 + w^3
43        // x0 = λ * x_S - y_S
44        // x2 = - λ
45        let b = lambda.neg();
46        let c = lambda * x - y;
47
48        (two_s, UnevaluatedLine { b, c })
49    }
50
51    fn miller_add_step(
52        s: &AffinePoint<Self::Fp2>,
53        q: &AffinePoint<Self::Fp2>,
54    ) -> (AffinePoint<Self::Fp2>, UnevaluatedLine<Self::Fp2>) {
55        let x_s = &s.x;
56        let y_s = &s.y;
57        let x_q = &q.x;
58        let y_q = &q.y;
59
60        // λ1 = (y_s - y_q) / (x_s - x_q)
61        let x_delta = x_s - x_q;
62        let lambda = (y_s - y_q).div_unsafe(&x_delta);
63        let x_s_plus_q = lambda * lambda - x_s - x_q;
64        let y_s_plus_q = lambda * (x_q - x_s_plus_q) - y_q;
65
66        let s_plus_q = AffinePoint {
67            x: x_s_plus_q,
68            y: y_s_plus_q,
69        };
70
71        // l_{\Psi(S),\Psi(Q)}(P) = (λ_1 * x_S - y_S) (1 / y_P) - λ_1 (x_P / y_P) w^2 + w^3
72        let b = lambda.neg();
73        let c = lambda * x_s - y_s;
74
75        (s_plus_q, UnevaluatedLine { b, c })
76    }
77
78    /// Miller double and add step (2S + Q implemented as S + Q + S for efficiency)
79    #[allow(clippy::type_complexity)]
80    fn miller_double_and_add_step(
81        s: &AffinePoint<Self::Fp2>,
82        q: &AffinePoint<Self::Fp2>,
83    ) -> (
84        AffinePoint<Self::Fp2>,
85        UnevaluatedLine<Self::Fp2>,
86        UnevaluatedLine<Self::Fp2>,
87    ) {
88        let one = &Self::Fp2::ONE;
89        let two = &(one + one);
90
91        let x_s = &s.x;
92        let y_s = &s.y;
93        let x_q = &q.x;
94        let y_q = &q.y;
95
96        // λ1 = (y_s - y_q) / (x_s - x_q)
97        let lambda1 = &((y_s - y_q).div_unsafe(&(x_s - x_q)));
98        let x_s_plus_q = lambda1 * lambda1 - x_s - x_q;
99
100        // λ2 = -λ1 - 2y_s / (x_{s+q} - x_s)
101        let lambda2 = &(lambda1.neg() - (two * y_s).div_unsafe(&(x_s_plus_q - x_s)));
102        let x_s_plus_q_plus_s = lambda2 * lambda2 - x_s - x_s_plus_q;
103        let y_s_plus_q_plus_s = lambda2 * (x_s - x_s_plus_q_plus_s) - y_s;
104
105        let s_plus_q_plus_s = AffinePoint {
106            x: x_s_plus_q_plus_s,
107            y: y_s_plus_q_plus_s,
108        };
109
110        // l_{\Psi(S),\Psi(Q)}(P) = (λ_1 * x_S - y_S) (1 / y_P) - λ_1 (x_P / y_P) w^2 + w^3
111        let b0 = lambda1.neg();
112        let c0 = lambda1 * x_s - y_s;
113
114        // l_{\Psi(S+Q),\Psi(S)}(P) = (λ_2 * x_S - y_S) (1 / y_P) - λ_2 (x_P / y_P) w^2 + w^3
115        let b1 = lambda2.neg();
116        let c1 = lambda2 * x_s - y_s;
117
118        (
119            s_plus_q_plus_s,
120            UnevaluatedLine { b: b0, c: c0 },
121            UnevaluatedLine { b: b1, c: c1 },
122        )
123    }
124}
125
126#[allow(non_snake_case)]
127impl MultiMillerLoop for Bls12_381 {
128    type Fp = Fq;
129    type Fp12 = Fq12;
130
131    const SEED_ABS: u64 = BLS12_381_SEED_ABS;
132    const PSEUDO_BINARY_ENCODING: &[i8] = &BLS12_381_PSEUDO_BINARY_ENCODING;
133
134    fn evaluate_lines_vec(f: Fq12, lines: Vec<EvaluatedLine<Fq2>>) -> Fq12 {
135        let mut f = f;
136        let mut lines = lines;
137        if lines.len() % 2 == 1 {
138            f = Self::mul_by_023(&f, &lines.pop().unwrap());
139        }
140        for chunk in lines.chunks(2) {
141            if let [line0, line1] = chunk {
142                let prod = Self::mul_023_by_023(line0, line1);
143                f = Self::mul_by_02345(&f, &prod);
144            } else {
145                panic!("lines.len() % 2 should be 0 at this point");
146            }
147        }
148        f
149    }
150
151    /// The expected output of this function when running the Miller loop with embedded exponent is c^3 * l_{3Q}
152    fn pre_loop(
153        Q_acc: Vec<AffinePoint<Fq2>>,
154        Q: &[AffinePoint<Fq2>],
155        c: Option<Fq12>,
156        xy_fracs: &[(Fq, Fq)],
157    ) -> (Fq12, Vec<AffinePoint<Fq2>>) {
158        let mut f = if let Some(mut c) = c {
159            // for the miller loop with embedded exponent, f will be set to c at the beginning of the function, and we
160            // will multiply by c again due to the last two values of the pseudo-binary encoding (BN12_381_PBE) being 1.
161            // Therefore, the final value of f at the end of this block is c^3.
162            let mut c3 = c;
163            c.square_assign();
164            c3 *= &c;
165            c3
166        } else {
167            Self::Fp12::ONE
168        };
169
170        let mut Q_acc = Q_acc;
171
172        // Special case the first iteration of the Miller loop with pseudo_binary_encoding = 1:
173        // this means that the first step is a double and add, but we need to separate the two steps since the optimized
174        // `miller_double_and_add_step` will fail because Q_acc is equal to Q_signed on the first iteration
175        let (Q_out_double, lines_2S) = Q_acc
176            .into_iter()
177            .map(|Q| Self::miller_double_step(&Q))
178            .unzip::<_, _, Vec<_>, Vec<_>>();
179        Q_acc = Q_out_double;
180
181        let mut initial_lines = Vec::<EvaluatedLine<Fq2>>::new();
182
183        let lines_iter = izip!(lines_2S.iter(), xy_fracs.iter());
184        for (line_2S, xy_frac) in lines_iter {
185            let line = line_2S.evaluate(xy_frac);
186            initial_lines.push(line);
187        }
188
189        let (Q_out_add, lines_S_plus_Q) = Q_acc
190            .iter()
191            .zip(Q.iter())
192            .map(|(Q_acc, Q)| Self::miller_add_step(Q_acc, Q))
193            .unzip::<_, _, Vec<_>, Vec<_>>();
194        Q_acc = Q_out_add;
195
196        let lines_iter = izip!(lines_S_plus_Q.iter(), xy_fracs.iter());
197        for (lines_S_plus_Q, xy_frac) in lines_iter {
198            let line = lines_S_plus_Q.evaluate(xy_frac);
199            initial_lines.push(line);
200        }
201
202        f = Self::evaluate_lines_vec(f, initial_lines);
203
204        (f, Q_acc)
205    }
206
207    /// After running the main body of the Miller loop, we conjugate f due to the curve seed x being negative.
208    fn post_loop(
209        f: &Fq12,
210        Q_acc: Vec<AffinePoint<Fq2>>,
211        _Q: &[AffinePoint<Fq2>],
212        _c: Option<Fq12>,
213        _xy_fracs: &[(Fq, Fq)],
214    ) -> (Fq12, Vec<AffinePoint<Fq2>>) {
215        // Conjugate for negative component of the seed
216        // Explanation:
217        // The general Miller loop formula implies that f_{-x} = 1/f_x. To avoid an inversion, we use the fact that
218        // for the final exponentiation, we only need the Miller loop result up to multiplication by some proper subfield
219        // of Fp12. Using the fact that Fp12 is a quadratic extension of Fp6, we have that f_x * conjugate(f_x) * 1/f_x lies in Fp6.
220        // Therefore we conjugate f_x instead of taking the inverse.
221        let f = f.conjugate();
222        (f, Q_acc)
223    }
224}