Skip to content

fix: reject off-curve points when decompressing public keys in native backend - #122

Open
haybinalim wants to merge 1 commit into
ApeWorX:mainfrom
haybinalim:fix/native-decompress-reject-off-curve
Open

haybinalim wants to merge 1 commit into
ApeWorX:mainfrom
haybinalim:fix/native-decompress-reject-off-curve

Conversation

@haybinalim

Copy link
Copy Markdown

What I did

Fixes #121

NativeECCBackend.decompress_public_key_bytes (via PublicKey.from_compressed_bytes) returned a point that is not on secp256k1 when x**3 + 7 is not a quadratic residue mod p, and accepted x >= p without reducing or rejecting it. The coincurve backend rejects both with ValueError.

How I did it

  • decompress_public_key now raises ValueError when x >= p, and when the computed square root does not square back to x**3 + 7 (no point with that x exists). ValueError matches what the coincurve backend raises and what the function already raises for a bad length or prefix.
  • Tests in tests/backends/test_native_backend_against_coincurve.py:
    • test_public_key_decompression_rejects_invalid_points: both prefixes × non-residue x values (5, 7, 9, 10, 11) and x ≥ p (p, p + 1, 2**256 - 1) must raise on both backends.
    • test_public_key_decompression_of_arbitrary_bytes_is_equal: hypothesis over arbitrary 32-byte x; native and coincurve must either both reject or return the same key.
    • test_public_key_decompression_is_equal now passes backend= explicitly. Without it, from_compressed_bytes (a classmethod) used the global default backend, which is coincurve when installed, so the native side was never exercised.

How to verify it

  • Without the fix, the 17 new test cases fail; with it they pass.
  • pytest tests: 116 passed.
  • ruff check ., ruff format --check ., mypy eth_keys, mdformat --check README.md: clean.

AI assistance

I used an AI assistant (Hark) to help find this with differential testing against the coincurve backend and to draft the fix and tests. I reviewed the change, reproduced the bug on main, and ran the test suite and linters locally.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Native backend accepts off-curve points and x >= p in PublicKey.from_compressed_bytes

1 participant