franklin_crypto/jubjub/
montgomery.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
use bellman::pairing::ff::{BitIterator, Field, PrimeField, PrimeFieldRepr, SqrtField};

use super::{edwards, JubjubEngine, JubjubParams, PrimeOrder, Unknown};

use rand::Rng;

use std::marker::PhantomData;

// Represents the affine point (X, Y)
pub struct Point<E: JubjubEngine, Subgroup> {
    x: E::Fr,
    y: E::Fr,
    infinity: bool,
    _marker: PhantomData<Subgroup>,
}

fn convert_subgroup<E: JubjubEngine, S1, S2>(from: &Point<E, S1>) -> Point<E, S2> {
    Point {
        x: from.x,
        y: from.y,
        infinity: from.infinity,
        _marker: PhantomData,
    }
}

impl<E: JubjubEngine> From<Point<E, PrimeOrder>> for Point<E, Unknown> {
    fn from(p: Point<E, PrimeOrder>) -> Point<E, Unknown> {
        convert_subgroup(&p)
    }
}

impl<E: JubjubEngine, Subgroup> Clone for Point<E, Subgroup> {
    fn clone(&self) -> Self {
        convert_subgroup(self)
    }
}

impl<E: JubjubEngine, Subgroup> PartialEq for Point<E, Subgroup> {
    fn eq(&self, other: &Point<E, Subgroup>) -> bool {
        match (self.infinity, other.infinity) {
            (true, true) => true,
            (true, false) | (false, true) => false,
            (false, false) => self.x == other.x && self.y == other.y,
        }
    }
}

impl<E: JubjubEngine> Point<E, Unknown> {
    pub fn get_for_x(x: E::Fr, sign: bool, params: &E::Params) -> Option<Self> {
        // Given an x on the curve, y = sqrt(x^3 + A*x^2 + x)

        let mut x2 = x;
        x2.square();

        let mut rhs = x2;
        rhs.mul_assign(params.montgomery_a());
        rhs.add_assign(&x);
        x2.mul_assign(&x);
        rhs.add_assign(&x2);

        match rhs.sqrt() {
            Some(mut y) => {
                if y.into_repr().is_odd() != sign {
                    y.negate();
                }

                return Some(Point {
                    x: x,
                    y: y,
                    infinity: false,
                    _marker: PhantomData,
                });
            }
            None => None,
        }
    }

    /// This guarantees the point is in the prime order subgroup
    #[must_use]
    pub fn mul_by_cofactor(&self, params: &E::Params) -> Point<E, PrimeOrder> {
        let tmp = self.double(params).double(params).double(params);

        convert_subgroup(&tmp)
    }

    pub fn rand<R: Rng>(rng: &mut R, params: &E::Params) -> Self {
        loop {
            let x: E::Fr = rng.gen();

            match Self::get_for_x(x, rng.gen(), params) {
                Some(p) => return p,
                None => {}
            }
        }
    }
}

impl<E: JubjubEngine, Subgroup> Point<E, Subgroup> {
    /// Convert from an Edwards point
    pub fn from_edwards(e: &edwards::Point<E, Subgroup>, params: &E::Params) -> Self {
        let (x, y) = e.into_xy();

        if y == E::Fr::one() {
            // The only solution for y = 1 is x = 0. (0, 1) is
            // the neutral element, so we map this to the point
            // at infinity.

            Point::zero()
        } else {
            // The map from a twisted Edwards curve is defined as
            // (x, y) -> (u, v) where
            //      u = (1 + y) / (1 - y)
            //      v = u / x
            //
            // This mapping is not defined for y = 1 and for x = 0.
            //
            // We have that y != 1 above. If x = 0, the only
            // solutions for y are 1 (contradiction) or -1.
            if x.is_zero() {
                // (0, -1) is the point of order two which is not
                // the neutral element, so we map it to (0, 0) which is
                // the only affine point of order 2.

                Point {
                    x: E::Fr::zero(),
                    y: E::Fr::zero(),
                    infinity: false,
                    _marker: PhantomData,
                }
            } else {
                // The mapping is defined as above.
                //
                // (x, y) -> (u, v) where
                //      u = (1 + y) / (1 - y)
                //      v = u / x

                let mut u = E::Fr::one();
                u.add_assign(&y);
                {
                    let mut tmp = E::Fr::one();
                    tmp.sub_assign(&y);
                    u.mul_assign(&tmp.inverse().unwrap())
                }

                let mut v = u;
                v.mul_assign(&x.inverse().unwrap());

                // Scale it into the correct curve constants
                v.mul_assign(params.scale());

                Point {
                    x: u,
                    y: v,
                    infinity: false,
                    _marker: PhantomData,
                }
            }
        }
    }

    /// Attempts to cast this as a prime order element, failing if it's
    /// not in the prime order subgroup.
    pub fn as_prime_order(&self, params: &E::Params) -> Option<Point<E, PrimeOrder>> {
        if self.mul(E::Fs::char(), params) == Point::zero() {
            Some(convert_subgroup(self))
        } else {
            None
        }
    }

    pub fn zero() -> Self {
        Point {
            x: E::Fr::zero(),
            y: E::Fr::zero(),
            infinity: true,
            _marker: PhantomData,
        }
    }

    pub fn into_xy(&self) -> Option<(E::Fr, E::Fr)> {
        if self.infinity {
            None
        } else {
            Some((self.x, self.y))
        }
    }

    #[must_use]
    pub fn negate(&self) -> Self {
        let mut p = self.clone();

        p.y.negate();

        p
    }

    #[must_use]
    pub fn double(&self, params: &E::Params) -> Self {
        if self.infinity {
            return Point::zero();
        }

        // (0, 0) is the point of order 2. Doubling
        // produces the point at infinity.
        if self.y == E::Fr::zero() {
            return Point::zero();
        }

        // This is a standard affine point doubling formula
        // See 4.3.2 The group law for Weierstrass curves
        //     Montgomery curves and the Montgomery Ladder
        //     Daniel J. Bernstein and Tanja Lange

        let mut delta = E::Fr::one();
        {
            let mut tmp = params.montgomery_a().clone();
            tmp.mul_assign(&self.x);
            tmp.double();
            delta.add_assign(&tmp);
        }
        {
            let mut tmp = self.x;
            tmp.square();
            delta.add_assign(&tmp);
            tmp.double();
            delta.add_assign(&tmp);
        }
        {
            let mut tmp = self.y;
            tmp.double();
            delta.mul_assign(&tmp.inverse().expect("y is nonzero so this must be nonzero"));
        }

        let mut x3 = delta;
        x3.square();
        x3.sub_assign(params.montgomery_a());
        x3.sub_assign(&self.x);
        x3.sub_assign(&self.x);

        let mut y3 = x3;
        y3.sub_assign(&self.x);
        y3.mul_assign(&delta);
        y3.add_assign(&self.y);
        y3.negate();

        Point {
            x: x3,
            y: y3,
            infinity: false,
            _marker: PhantomData,
        }
    }

    #[must_use]
    pub fn add(&self, other: &Self, params: &E::Params) -> Self {
        // This is a standard affine point addition formula
        // See 4.3.2 The group law for Weierstrass curves
        //     Montgomery curves and the Montgomery Ladder
        //     Daniel J. Bernstein and Tanja Lange

        match (self.infinity, other.infinity) {
            (true, true) => Point::zero(),
            (true, false) => other.clone(),
            (false, true) => self.clone(),
            (false, false) => {
                if self.x == other.x {
                    if self.y == other.y {
                        self.double(params)
                    } else {
                        Point::zero()
                    }
                } else {
                    let mut delta = other.y;
                    delta.sub_assign(&self.y);
                    {
                        let mut tmp = other.x;
                        tmp.sub_assign(&self.x);
                        delta.mul_assign(&tmp.inverse().expect("self.x != other.x, so this must be nonzero"));
                    }

                    let mut x3 = delta;
                    x3.square();
                    x3.sub_assign(params.montgomery_a());
                    x3.sub_assign(&self.x);
                    x3.sub_assign(&other.x);

                    let mut y3 = x3;
                    y3.sub_assign(&self.x);
                    y3.mul_assign(&delta);
                    y3.add_assign(&self.y);
                    y3.negate();

                    Point {
                        x: x3,
                        y: y3,
                        infinity: false,
                        _marker: PhantomData,
                    }
                }
            }
        }
    }

    #[must_use]
    pub fn mul<S: Into<<E::Fs as PrimeField>::Repr>>(&self, scalar: S, params: &E::Params) -> Self {
        // Standard double-and-add scalar multiplication

        let mut res = Self::zero();

        for b in BitIterator::new(scalar.into()) {
            res = res.double(params);

            if b {
                res = res.add(self, params);
            }
        }

        res
    }
}