ecc

Elliptic Curve Cryptograpy library from scratch in python.
Log | Files | Refs | README | LICENSE

commit 14bada6d546e6b66de75ef42846a96cde6e06ede
parent 61662fd87732c3ca9a217094353e3e2fd08ede24
Author: Shivakumar <[email protected]>
Date:   Sat,  2 Aug 2025 21:25:01 +0530

update files for type safety

Diffstat:
Mecc/__init__.py | 11++++-------
Mecc/curve.py | 3++-
Mecc/curves/secp256k1.py | 1-
Mecc/field.py | 20++++++++++----------
Mecc/keys.py | 15+++++++++------
Mecc/point.py | 35++++++++++++++++++++++++++++-------
Mtests/test_curve.py | 5+++++
Mtests/test_ecdsa.py | 7++++---
Mtests/test_field.py | 9+++++----
Mtests/test_keys.py | 9++++-----
Mtests/test_point.py | 14+++++++++-----
Mtests/test_secp256k1.py | 17++++++++++++++---
12 files changed, 94 insertions(+), 52 deletions(-)

diff --git a/ecc/__init__.py b/ecc/__init__.py @@ -1,10 +1,9 @@ -from .field import FieldElement -from .point import Point from .curve import Curve -from .keys import generate_keypair, PublicKey, PrivateKey -from .ecdsa import Signature - from .curves.secp256k1 import secp256k1 +from .ecdsa import Signature +from .field import FieldElement +from .keys import PrivateKey, PublicKey, generate_keypair +from .point import Point __all__ = [ "FieldElement", @@ -15,6 +14,4 @@ __all__ = [ "PublicKey", "PrivateKey", "Signature", - "sign", - "verify", ] diff --git a/ecc/curve.py b/ecc/curve.py @@ -4,6 +4,7 @@ in the short Weierstrass form. """ from __future__ import annotations + from functools import cached_property from .field import FieldElement @@ -21,7 +22,7 @@ class Curve: G: tuple[int, int], n: int, h: int = 1, - name: str = None, + name: str | None = None, ): """ parameters: diff --git a/ecc/curves/secp256k1.py b/ecc/curves/secp256k1.py @@ -1,6 +1,5 @@ from ecc import Curve - a = 0 b = 7 diff --git a/ecc/field.py b/ecc/field.py @@ -27,7 +27,7 @@ class FieldElement: self.num = num % prime self.prime = prime - def _normalize(self, other: object) -> FieldElement: + def _normalize(self, other: int | FieldElement) -> FieldElement: """Helper function to check type, and convert integer to FieldElement""" if isinstance(other, int): return FieldElement(other, self.prime) @@ -44,28 +44,28 @@ class FieldElement: f"Unsupported operand type(s) for FieldElement: '{type(other).__name__}'" ) - def __add__(self, other: object) -> FieldElement: + def __add__(self, other: int | FieldElement) -> FieldElement: other = self._normalize(other) return FieldElement((self.num + other.num) % self.prime, self.prime) - def __radd__(self, other: object) -> FieldElement: + def __radd__(self, other: int | FieldElement) -> FieldElement: return self + other - def __sub__(self, other: object) -> FieldElement: + def __sub__(self, other: int | FieldElement) -> FieldElement: other = self._normalize(other) return FieldElement((self.num - other.num) % self.prime, self.prime) - def __rsub__(self, other: object) -> FieldElement: + def __rsub__(self, other: int | FieldElement) -> FieldElement: return self - other - def __mul__(self, other: object) -> FieldElement: + def __mul__(self, other: int | FieldElement) -> FieldElement: other = self._normalize(other) return FieldElement((self.num * other.num) % self.prime, self.prime) - def __rmul__(self, other: object) -> FieldElement: + def __rmul__(self, other: int | FieldElement) -> FieldElement: return self * other - def __truediv__(self, other: object) -> FieldElement: + def __truediv__(self, other: int | FieldElement) -> FieldElement: other = self._normalize(other) inv = pow(other.num, -1, self.prime) @@ -73,7 +73,7 @@ class FieldElement: return FieldElement(num, self.prime) - def __rtruediv__(self, other: object) -> FieldElement: + def __rtruediv__(self, other: int | FieldElement) -> FieldElement: other = self._normalize(other) return other / self @@ -85,7 +85,7 @@ class FieldElement: return FieldElement(pow(self.num, exponent, self.prime), self.prime) def __eq__(self, other: object) -> bool: - if other is None: + if not isinstance(other, FieldElement): return NotImplemented return self.num == other.num and self.prime == other.prime diff --git a/ecc/keys.py b/ecc/keys.py @@ -14,13 +14,14 @@ Public Key - The point P = k * G, on the elliptic curve with Field E(Z/pZ) """ from __future__ import annotations + +import hashlib from functools import cached_property from secrets import randbelow -import hashlib from .curve import Curve -from .point import Point from .ecdsa import Signature, _rfc6979_nonce +from .point import Point class PublicKey: @@ -65,12 +66,10 @@ class PublicKey: return self.point == other.point def __repr__(self) -> str: - if (self.point.x, self.point.y) == (None, None): + if self.point.x is None or self.point.y is None: return "PublicKey(Point(infinity))" - return ( - f"PublicKey(\n\tx={hex(self.point.x.num)}, \n\ty={hex(self.point.y.num)}\n)" - ) + return f"PublicKey(\n\tx=0x{self.point.x.num:x}, \n\ty=0x{self.point.y.num:x})" class PrivateKey: @@ -109,6 +108,10 @@ class PrivateKey: k = _rfc6979_nonce(self.secret, n, message_hash) R = k * self.curve.G + + if R.x is None: + continue + r = R.x.num % n if r == 0: continue diff --git a/ecc/point.py b/ecc/point.py @@ -15,8 +15,16 @@ The operations are: """ from __future__ import annotations + +import typing + from .field import FieldElement +# To provide a type hint for the Curve class, which is defined elsewhere +# and would otherwise cause a circular import or NameError. +if typing.TYPE_CHECKING: + from .curve import Curve + class Point: """ @@ -27,7 +35,7 @@ class Point: parameters (a, b) and a prime modulo P. """ - def __init__(self, x: int, y: int | None, curve): + def __init__(self, x: int | None, y: int | None, curve: Curve): """ Arguments: x, y : (x, y) on the curve over the Field E(Z/pZ) @@ -37,14 +45,20 @@ class Point: if x is None and y is None: self.x, self.y = None, None - else: - self.x = FieldElement(x, curve.P) - self.y = FieldElement(y, curve.P) + return - if self.y**2 != self.x**3 + curve.a * self.x + curve.b: - raise ValueError(f"Point({x}, {y}) is not on the curve.") + if x is None or y is None: + raise ValueError( + "Invalid coordinates: both x and y must be integers, or both must be None." + ) - def __add__(self, other) -> "Point": + self.x = FieldElement(x, curve.P) + self.y = FieldElement(y, curve.P) + + if self.y**2 != self.x**3 + curve.a * self.x + curve.b: + raise ValueError(f"Point({x}, {y}) is not on the curve.") + + def __add__(self, other: Point) -> Point: """Performs elliptic curve point addition. Let's say we have two distinct point P and Q, we want @@ -69,6 +83,11 @@ class Point: if other.x is None: return self + # After the identity checks, we know both points have non-None coordinates + # Assestion for Type safety + assert self.x is not None and self.y is not None + assert other.x is not None and other.y is not None + # Checks for Point doubling and additive inverses if self.x == other.x: # Additive inverses case: (P) + (-P) = infinity @@ -142,4 +161,6 @@ class Point: if self.x is None: return "Point(infinity)" + # Assertion for Type safety + assert self.x is not None and self.y is not None return f"Point(\n\t{self.x.num}, \n\t{self.y.num}\n)" diff --git a/tests/test_curve.py b/tests/test_curve.py @@ -1,4 +1,5 @@ import pytest + from ecc import Curve, Point curve = Curve(P=17, a=2, b=2, G=(5, 1), n=19, h=1, name="toy_curve") @@ -35,6 +36,10 @@ class TestCurve: """Test that the G property returns a valid Point object.""" G = curve.G assert isinstance(G, Point) + + # Assertion: Type safety + assert G.x is not None and G.y is not None + assert G.x.num == 5 and G.y.num == 1 assert G.curve == curve diff --git a/tests/test_ecdsa.py b/tests/test_ecdsa.py @@ -1,6 +1,7 @@ -from hypothesis import given, strategies as st -from ecc.curves import secp256k1 -from ecc import PrivateKey, Signature, generate_keypair +from hypothesis import given +from hypothesis import strategies as st + +from ecc import PrivateKey, Signature, generate_keypair, secp256k1 # --- Official RFC 6979 Test Vector for secp256k1 --- # Source: RFC 6979, Appendix A.2.5 diff --git a/tests/test_field.py b/tests/test_field.py @@ -1,5 +1,6 @@ import pytest -from hypothesis import given, strategies as st +from hypothesis import given +from hypothesis import strategies as st from ecc import FieldElement @@ -12,7 +13,7 @@ class TestFieldElementErrors: def test_init_invalid_type(self): with pytest.raises(TypeError, match="Number and prime must be integers."): - FieldElement(3.5, 13) + FieldElement(3.5, 13) # type: ignore def test_add_mismatched_fields(self): a = FieldElement(7, 13) @@ -20,13 +21,13 @@ class TestFieldElementErrors: with pytest.raises( TypeError, match="Cannot operate on FieldElements from different fields." ): - a + b + a + b # pyright: ignore[reportUnusedExpression] def test_division_by_zero(self): a = FieldElement(7, 13) b = FieldElement(0, 13) with pytest.raises((ValueError, ZeroDivisionError)): - a / b + a / b # pyright: ignore[reportUnusedExpression] # --- Testing Edge Cases and Reflected Operations --- diff --git a/tests/test_keys.py b/tests/test_keys.py @@ -1,9 +1,8 @@ import pytest -from hypothesis import given, strategies as st +from hypothesis import given +from hypothesis import strategies as st -from ecc import Point, Curve -from ecc import PrivateKey, PublicKey, generate_keypair -from ecc import secp256k1 +from ecc import Curve, Point, PrivateKey, PublicKey, generate_keypair, secp256k1 # --- Test Setup --- curve = Curve(P=17, a=2, b=2, G=(5, 1), n=19) @@ -95,7 +94,7 @@ class TestKeyGeneration: def test_error_on_missing_curve(self): """The curve is a required keyword-only argument.""" with pytest.raises(TypeError): - PrivateKey(secret=5) + PrivateKey(secret=5) # pyright: ignore[reportCallIssue] # --- Property-Based Testing --- diff --git a/tests/test_point.py b/tests/test_point.py @@ -1,8 +1,8 @@ import pytest -from hypothesis import given, strategies as st +from hypothesis import given +from hypothesis import strategies as st -from ecc import Point, Curve -from ecc import secp256k1 +from ecc import Curve, Point, secp256k1 # --- Test Setup --- P = 17 @@ -29,12 +29,12 @@ class TestPointErrors: p1 = G p2 = secp256k1.G with pytest.raises(TypeError, match="Points are not on the same curve"): - p1 + p2 + p1 + p2 # pyright: ignore[reportUnusedExpression] def test_rmul_by_non_integer(self): """Scalar multiplication requires an integer scalar.""" with pytest.raises(TypeError, match="Scalar must be an integer"): - 2.5 * G + 2.5 * G # pyright: ignore[reportUnusedExpression, reportOperatorIssue] # --- Testing Edge Cases and Core Operations --- @@ -56,6 +56,10 @@ class TestPointOperations: def test_additive_inverse(self): """Test that adding a point to its inverse results in infinity.""" + + # Assertion: Type safety + assert G.x is not None and G.y is not None + p_inv = Point(G.x.num, -G.y.num, curve) assert G + p_inv == identity diff --git a/tests/test_secp256k1.py b/tests/test_secp256k1.py @@ -1,6 +1,7 @@ -from hypothesis import given, strategies as st -from ecc import secp256k1 -from ecc import PrivateKey +from hypothesis import given +from hypothesis import strategies as st + +from ecc import PrivateKey, secp256k1 class TestSecp256k1Integration: @@ -14,6 +15,10 @@ class TestSecp256k1Integration: """The secp256k1 generator point G must satisfy the curve equation.""" G = secp256k1.G assert G is not None, "Generator point should not be None" + + # Assertion: type safety + assert G.x is not None and G.y is not None + assert G.y**2 == G.x**3 + secp256k1.a * G.x + secp256k1.b def test_point_order_is_correct(self): @@ -40,6 +45,9 @@ class TestSecp256k1Integration: two_G_x = 0xC6047F9441ED7D6D3045406E95C07CD85C778E4B8CEF3CA7ABAC09B95C709EE5 two_G_y = 0x1AE168FEA63DC339A3C58419466CEAEEF7F632653266D0E1236431A950CFE52A + # Assertion: type safety + assert two_G.x is not None and two_G.y is not None + assert two_G.x.num == two_G_x assert two_G.y.num == two_G_y @@ -72,4 +80,7 @@ def test_generated_public_key_is_valid(secret): private_key = PrivateKey(secret=secret, curve=secp256k1) point = private_key.public_key.point + # Assertion: type safety + assert point.x is not None and point.y is not None + assert point.y**2 == point.x**3 + secp256k1.a * point.x + secp256k1.b