Skip to content

Commit a6f81f5

Browse files
committed
feat: implement EC point addition
1 parent f713bfc commit a6f81f5

File tree

1 file changed

+44
-1
lines changed

1 file changed

+44
-1
lines changed

src/ec.rs

Lines changed: 44 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,30 @@ impl<const A: i32, const B: i32> ops::Add for EPoint<A, B> {
103103
return EPoint::<A, B>::infinity();
104104
}
105105

106-
unimplemented!()
106+
// 3. Points are the same point.
107+
if self == other {
108+
// Special case: If the y coord is 0, the tangent line is vertical since the elliptic
109+
// curve is symmetrical wrt. the x axis. This results on a point on the infinity.
110+
if self_coords.y == 0 {
111+
return Self::infinity();
112+
}
113+
114+
let s = (3 * self_coords.x * self_coords.x + A) / (2 * self_coords.y);
115+
let x = s * s - 2 * self_coords.x;
116+
let y = s * (self_coords.x - x) - self_coords.y;
117+
return Self {
118+
p: Some(Coordinates { x, y }),
119+
};
120+
}
121+
122+
// 4. The general case, where points are distinct, none is infinity and they are not additive inverses.
123+
let s = (other_coords.y - self_coords.y) / (other_coords.x - self_coords.x);
124+
let x = s * s - self_coords.x - other_coords.x;
125+
let y = s * (self_coords.x - x) - self_coords.y;
126+
127+
return Self {
128+
p: Some(Coordinates { x, y }),
129+
};
107130
}
108131
}
109132

@@ -156,4 +179,24 @@ mod tests {
156179
assert_eq!(a + b, TEST_EC.point_at_ifty());
157180
assert_eq!(b + a, TEST_EC.point_at_ifty());
158181
}
182+
183+
#[test]
184+
fn test_add_same() {
185+
let a = TEST_EC.point_at(-1, -1).unwrap();
186+
let res = TEST_EC.point_at(18, 77).unwrap();
187+
assert_eq!(res, a + a);
188+
189+
let a = TEST_EC.point_at(-1, 1).unwrap();
190+
let res = TEST_EC.point_at(18, -77).unwrap();
191+
assert_eq!(res, a + a);
192+
}
193+
194+
#[test]
195+
fn test_add() {
196+
let a = TEST_EC.point_at(-1, -1).unwrap();
197+
let b = TEST_EC.point_at(2, 5).unwrap();
198+
let res = TEST_EC.point_at(3, -7).unwrap();
199+
assert_eq!(res, a + b);
200+
assert_eq!(res, b + a);
201+
}
159202
}

0 commit comments

Comments
 (0)