From ae68cd33da7f058340af45168db0e093c84582ca Mon Sep 17 00:00:00 2001 From: Sergi Delgado Segura Date: Fri, 27 Mar 2020 16:41:19 +0100 Subject: [PATCH] Captures TypeErrors in Cryptographer.get_compressed_pk and adds unit tests --- common/cryptographer.py | 11 ++++++++--- test/common/unit/test_cryptographer.py | 24 ++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 3 deletions(-) diff --git a/common/cryptographer.py b/common/cryptographer.py index f5427e7..5414fda 100644 --- a/common/cryptographer.py +++ b/common/cryptographer.py @@ -315,7 +315,7 @@ class Cryptographer: if "failed to recover ECDSA public key" in str(e): logger.error("Cannot recover public key from signature".format(type(rsig_recid))) else: - logger.error("Unknown exception", error=e) + logger.error("Unknown exception", error=str(e)) return None @@ -334,7 +334,6 @@ class Cryptographer: return pk.point() == rpk.point() - # TODO: UNITTEST @staticmethod def get_compressed_pk(pk): """ @@ -351,4 +350,10 @@ class Cryptographer: logger.error("The received data is not a PublicKey object") return None - return hexlify(pk.format(compressed=True)).decode("utf-8") + try: + compressed_pk = pk.format(compressed=True) + return hexlify(compressed_pk).decode("utf-8") + + except TypeError as e: + logger.error("PublicKey has invalid initializer", error=str(e)) + return None diff --git a/test/common/unit/test_cryptographer.py b/test/common/unit/test_cryptographer.py index d5983f5..ddbb707 100644 --- a/test/common/unit/test_cryptographer.py +++ b/test/common/unit/test_cryptographer.py @@ -255,3 +255,27 @@ def test_verify_pk_wrong(): rpk = Cryptographer.recover_pk(message, zbase32_sig) assert not Cryptographer.verify_rpk(sk2.public_key, rpk) + + +def test_get_compressed_pk(): + sk, pk = generate_keypair() + compressed_pk = Cryptographer.get_compressed_pk(pk) + + assert isinstance(compressed_pk, str) and len(compressed_pk) == 66 + assert compressed_pk[:2] in ["02", "03"] + + +def test_get_compressed_pk_wrong_key(): + # pk should be properly initialized. Initializing from int will case it to not be recoverable + pk = PublicKey(0) + compressed_pk = Cryptographer.get_compressed_pk(pk) + + assert compressed_pk is None + + +def test_get_compressed_pk_wrong_type(): + # Passing a value that is not a PublicKey will make it to fail too + pk = get_random_value_hex(33) + compressed_pk = Cryptographer.get_compressed_pk(pk) + + assert compressed_pk is None