|
| 1 | +"""Unit tests for crypto_utils module.""" |
| 2 | +from cryptography.hazmat.primitives.asymmetric import ec |
| 3 | + |
| 4 | +from hiero_sdk_python.utils.crypto_utils import ( |
| 5 | + compress_point_unchecked, |
| 6 | + compress_with_cryptography, |
| 7 | + decompress_point, |
| 8 | + keccak256, |
| 9 | +) |
| 10 | + |
| 11 | + |
| 12 | +def test_keccak256(): |
| 13 | + """Test keccak256 hashing.""" |
| 14 | + # Known vector: empty string -> c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 |
| 15 | + assert keccak256(b"").hex() == "c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470" |
| 16 | + |
| 17 | + # "hello" -> 1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8 |
| 18 | + assert keccak256(b"hello").hex() == "1c8aff950685c2ed4bc3174f3472287b56d9517b9c948127319a09a7a36deac8" |
| 19 | + |
| 20 | + |
| 21 | +def test_compress_point_unchecked(): |
| 22 | + """Test point compression logic.""" |
| 23 | + # Use cryptography to generate a valid point |
| 24 | + priv = ec.generate_private_key(ec.SECP256K1()) |
| 25 | + pub = priv.public_key() |
| 26 | + nums = pub.public_numbers() |
| 27 | + x = nums.x |
| 28 | + y = nums.y |
| 29 | + |
| 30 | + compressed = compress_point_unchecked(x, y) |
| 31 | + assert len(compressed) == 33 |
| 32 | + |
| 33 | + # Verify expected prefix |
| 34 | + expected_prefix = 0x03 if y % 2 else 0x02 |
| 35 | + assert compressed[0] == expected_prefix |
| 36 | + assert int.from_bytes(compressed[1:], "big") == x |
| 37 | + |
| 38 | + |
| 39 | +def test_decompress_point(): |
| 40 | + """Test point decompression logic.""" |
| 41 | + priv = ec.generate_private_key(ec.SECP256K1()) |
| 42 | + pub = priv.public_key() |
| 43 | + nums = pub.public_numbers() |
| 44 | + |
| 45 | + # Create valid compressed point |
| 46 | + compressed = compress_point_unchecked(nums.x, nums.y) |
| 47 | + |
| 48 | + # Test decompression |
| 49 | + x, y = decompress_point(compressed) |
| 50 | + assert x == nums.x |
| 51 | + assert y == nums.y |
| 52 | + |
| 53 | + # Test uncompressed 65-byte format (0x04 + x + y) |
| 54 | + uncompressed = b'\x04' + nums.x.to_bytes(32, 'big') + nums.y.to_bytes(32, 'big') |
| 55 | + x2, y2 = decompress_point(uncompressed) |
| 56 | + assert x2 == nums.x |
| 57 | + assert y2 == nums.y |
| 58 | + |
| 59 | + |
| 60 | +def test_compress_with_cryptography(): |
| 61 | + """Test compression using cryptography library.""" |
| 62 | + priv = ec.generate_private_key(ec.SECP256K1()) |
| 63 | + pub = priv.public_key() |
| 64 | + nums = pub.public_numbers() |
| 65 | + |
| 66 | + # Create uncompressed |
| 67 | + uncompressed = b'\x04' + nums.x.to_bytes(32, 'big') + nums.y.to_bytes(32, 'big') |
| 68 | + |
| 69 | + compressed_via_lib = compress_with_cryptography(uncompressed) |
| 70 | + compressed_manual = compress_point_unchecked(nums.x, nums.y) |
| 71 | + |
| 72 | + assert compressed_via_lib == compressed_manual |
0 commit comments