diff --git a/libp2p/crypto/keys.py b/libp2p/crypto/keys.py index b0dec3d..f0485ad 100644 --- a/libp2p/crypto/keys.py +++ b/libp2p/crypto/keys.py @@ -32,12 +32,29 @@ class Key(ABC): """ ... + def _serialize_to_protobuf(self) -> protobuf.PublicKey: + """ + Return the protobuf representation of this ``Key``. + """ + key_type = self.get_type().value + data = self.to_bytes() + protobuf_key = self.protobuf_constructor(key_type=key_type, data=data) + return protobuf_key + + def serialize(self) -> bytes: + """ + Return the canonical serialization of this ``Key``. + """ + return self._serialize_to_protobuf().SerializeToString() + class PublicKey(Key): """ A ``PublicKey`` represents a cryptographic public key. """ + protobuf_constructor = protobuf.PublicKey + @abstractmethod def verify(self, data: bytes, signature: bytes) -> bool: """ @@ -45,18 +62,14 @@ class PublicKey(Key): """ ... - def serialize_to_protobuf(self) -> protobuf.PublicKey: - key_type = self.get_type().value - data = self.to_bytes() - protobuf_key = protobuf.PublicKey(key_type=key_type, data=data) - return protobuf_key - class PrivateKey(Key): """ A ``PrivateKey`` represents a cryptographic private key. """ + protobuf_constructor = protobuf.PrivateKey + @abstractmethod def sign(self, data: bytes) -> bytes: ... @@ -65,12 +78,6 @@ class PrivateKey(Key): def get_public_key(self) -> PublicKey: ... - def serialize_to_protobuf(self) -> protobuf.PrivateKey: - key_type = self.get_type().value - data = self.to_bytes() - protobuf_key = protobuf.PrivateKey(key_type=key_type, data=data) - return protobuf_key - @dataclass(frozen=True) class KeyPair: diff --git a/libp2p/peer/id.py b/libp2p/peer/id.py index 26029b6..303f519 100644 --- a/libp2p/peer/id.py +++ b/libp2p/peer/id.py @@ -7,13 +7,6 @@ import multihash from libp2p.crypto.keys import PublicKey -def _serialize_public_key(key: PublicKey) -> bytes: - """ - Serializes ``key`` in the way expected to form valid peer ids. - """ - return key.serialize_to_protobuf().SerializeToString() - - class ID: _bytes: bytes _xor_id: int = None @@ -62,7 +55,7 @@ class ID: @classmethod def from_pubkey(cls, key: PublicKey) -> "ID": - serialized_key = _serialize_public_key(key) + serialized_key = key.serialize() algo = multihash.Func.sha2_256 mh_digest = multihash.digest(serialized_key, algo) return cls(mh_digest.encode()) diff --git a/tests/peer/test_peerid.py b/tests/peer/test_peerid.py index 30b74c1..ea244ce 100644 --- a/tests/peer/test_peerid.py +++ b/tests/peer/test_peerid.py @@ -92,7 +92,7 @@ def test_id_from_public_key(): key_pair = create_new_key_pair() public_key = key_pair.public_key - key_bin = public_key.serialize_to_protobuf().SerializeToString() + key_bin = public_key.serialize() algo = multihash.Func.sha2_256 mh_digest = multihash.digest(key_bin, algo) expected = ID(mh_digest.encode())