Skip to content

Commit

Permalink
Merge pull request #7 from pluto/review_point_addition
Browse files Browse the repository at this point in the history
Update curve.rs
  • Loading branch information
0xJepsen authored May 1, 2024
2 parents e744ed4 + 70b5eda commit 98bfacb
Showing 1 changed file with 14 additions and 8 deletions.
22 changes: 14 additions & 8 deletions src/curve.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ pub struct Point<F: Field> {
y: F,
}

// Since EVERY point is either at "infinity" or not, the coproduct makes sense.
#[derive(Clone, Copy)]
pub enum PointOrInfinity<F: Field> {
Point(Point<F>),
Expand All @@ -30,13 +31,15 @@ impl<F: Field> Curve<F> {
}
}

// inverse
pub fn negate(&self, p: PointOrInfinity<F>) -> PointOrInfinity<F> {
match p {
PointOrInfinity::Point(p) => PointOrInfinity::Point(Point { x: p.x, y: -p.y }),
PointOrInfinity::Infinity => PointOrInfinity::Infinity,
}
}

// outer add does infinitity check
pub fn add(&self, p: PointOrInfinity<F>, q: PointOrInfinity<F>) -> PointOrInfinity<F> {
match (p, q) {
(PointOrInfinity::Infinity, _) => q,
Expand All @@ -49,21 +52,24 @@ impl<F: Field> Curve<F> {
}

fn add_points(&self, p: Point<F>, q: Point<F>) -> Point<F> {
let (x1, y1) = (p.x, p.y);
let (x2, y2) = (q.x, q.y);
// https://en.wikipedia.org/wiki/Elliptic_curve_point_multiplicationcv
let (x_p, y_p) = (p.x, p.y);
let (x_q, y_q) = (q.x, q.y);

if x1 == x2 && y1 == -y2 {
// check for zero
if x_p == x_q && y_p == -y_q {
return Point { x: F::zero(), y: F::zero() };
}

let m = if x1 == x2 && y1 == y2 {
(self.three * x1 * x1 + self.a) / (self.two * y1)
// Check if point is itself, if it is you double (which is easier)
let lamda = if x_p == x_q && y_p == y_q {
(self.three * x_p * x_p + self.a) / (self.two * y_p)
} else {
(y2 - y1) / (x2 - x1)
(y_q - y_p) / (x_q - x_p)
};

let x = m * m - x1 - x2;
let y = m * (x1 - x) - y1;
let x = lamda * lamda - x_p - x_q;
let y = lamda * (x_p - x) - y_p;

Point { x, y }
}
Expand Down

0 comments on commit 98bfacb

Please sign in to comment.