test_secp256k1.py (2686B)
1 from hypothesis import given 2 from hypothesis import strategies as st 3 4 from ecc import PrivateKey, secp256k1 5 6 7 class TestSecp256k1Integration: 8 """ 9 Integration tests for the secp256k1 curve instance. 10 These tests verify that the library works correctly with standard, 11 real-world curve parameters and known test vectors. 12 """ 13 14 def test_generator_is_on_curve(self): 15 """The secp256k1 generator point G must satisfy the curve equation.""" 16 G = secp256k1.G 17 assert G is not None, "Generator point should not be None" 18 19 # Assertion: type safety 20 assert G.x is not None and G.y is not None 21 22 assert G.y**2 == G.x**3 + secp256k1.a * G.x + secp256k1.b 23 24 def test_point_order_is_correct(self): 25 """The order 'n' of the curve should result in n * G = Infinity.""" 26 G = secp256k1.G 27 n = secp256k1.n 28 infinity_point = n * G 29 30 assert infinity_point.x is None, ( 31 "The x-coordinate should be None for the point at infinity" 32 ) 33 assert infinity_point.y is None, ( 34 "The y-coordinate should be None for the point at infinity" 35 ) 36 37 def test_known_scalar_multiplication(self): 38 """ 39 Known Answer Test (KAT): Verifies scalar multiplication against a 40 standard, pre-computed value for 2*G on secp256k1. 41 """ 42 G = secp256k1.G 43 two_G = 2 * G 44 45 two_G_x = 0xC6047F9441ED7D6D3045406E95C07CD85C778E4B8CEF3CA7ABAC09B95C709EE5 46 two_G_y = 0x1AE168FEA63DC339A3C58419466CEAEEF7F632653266D0E1236431A950CFE52A 47 48 # Assertion: type safety 49 assert two_G.x is not None and two_G.y is not None 50 51 assert two_G.x.num == two_G_x 52 assert two_G.y.num == two_G_y 53 54 55 # --- Property-Based Testing for Secp256k1 --- 56 57 secp256k1_secrets = st.integers(min_value=1, max_value=secp256k1.n - 1) 58 59 60 @given(k=secp256k1_secrets) 61 def test_multiplicative_inverse_property(k): 62 """ 63 Property: For any scalar k, k * G * k⁻¹ should result back in G. 64 This is a strong check of the entire multiplication and field logic. 65 """ 66 G = secp256k1.G 67 P = k * G 68 k_inv = pow(k, -1, secp256k1.n) 69 G_check = k_inv * P 70 71 assert G_check == G 72 73 74 @given(secret=secp256k1_secrets) 75 def test_generated_public_key_is_valid(secret): 76 """ 77 Property: A public key generated from any valid secret must be a 78 valid point on the curve. 79 """ 80 private_key = PrivateKey(secret=secret, curve=secp256k1) 81 point = private_key.public_key.point 82 83 # Assertion: type safety 84 assert point.x is not None and point.y is not None 85 86 assert point.y**2 == point.x**3 + secp256k1.a * point.x + secp256k1.b