|
| 1 | +"""Tests for `libcrypto.keys` utility classes.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import pytest |
| 5 | + |
| 6 | +from libcrypto.keys import KeyError, PrivateKey, PublicKey |
| 7 | +from libcrypto.formats import wif_to_private_key, InvalidFormatError |
| 8 | + |
| 9 | + |
| 10 | +def test_private_key_wif_roundtrip(deterministic_private_key_hex: str) -> None: |
| 11 | + """PrivateKey should round-trip through WIF with compression preserved.""" |
| 12 | + key = PrivateKey(deterministic_private_key_hex) |
| 13 | + wif = key.to_wif(compressed=True) |
| 14 | + |
| 15 | + key_bytes, is_compressed, network = wif_to_private_key(wif) |
| 16 | + |
| 17 | + assert key_bytes.hex() == deterministic_private_key_hex |
| 18 | + assert is_compressed is True |
| 19 | + assert network == "bitcoin" |
| 20 | + |
| 21 | + |
| 22 | +def test_private_key_invalid_hex_length() -> None: |
| 23 | + """Creating a private key with invalid hex length must raise KeyError.""" |
| 24 | + with pytest.raises(KeyError): |
| 25 | + PrivateKey("deadbeef") |
| 26 | + |
| 27 | + |
| 28 | +def test_wif_to_private_key_invalid_checksum() -> None: |
| 29 | + """wif_to_private_key should raise when checksum is incorrect.""" |
| 30 | + invalid_wif = "5HpHagT65TZzG1PH3CSu63k8DbpvD8s5ip4nEB3kEsreAnchuDg" # altered last char |
| 31 | + with pytest.raises(InvalidFormatError): |
| 32 | + wif_to_private_key(invalid_wif) |
| 33 | + |
| 34 | + |
| 35 | +def test_public_key_enforces_length() -> None: |
| 36 | + """PublicKey rejects byte sequences of unsupported length.""" |
| 37 | + with pytest.raises(KeyError): |
| 38 | + PublicKey(b"\x02" * 10) |
| 39 | + |
| 40 | + |
| 41 | +def test_public_key_compression_roundtrip(deterministic_private_key_hex: str) -> None: |
| 42 | + """Compression toggling should preserve public key material.""" |
| 43 | + private_key = PrivateKey(deterministic_private_key_hex) |
| 44 | + compressed = private_key.get_public_key(compressed=True) |
| 45 | + uncompressed = compressed.to_uncompressed() |
| 46 | + |
| 47 | + assert uncompressed.compressed is False |
| 48 | + assert compressed.to_uncompressed().to_compressed().hex == compressed.hex |
0 commit comments