Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update curve.rs #7

Merged
merged 2 commits into from
May 1, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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