Merge pull request #256 from ralexstokes/patch-up-key-to-bytes

Internalize the protobuf serialization to the concept of a `Key`
This commit is contained in:
Alex Stokes 2019-08-20 10:33:33 -07:00 committed by GitHub
commit 20aed4430e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 11 deletions

View File

@ -45,18 +45,29 @@ class PublicKey(Key):
"""
...
def serialize_to_protobuf(self) -> protobuf.PublicKey:
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 = protobuf.PublicKey(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 PrivateKey(Key):
"""
A ``PrivateKey`` represents a cryptographic private key.
"""
protobuf_constructor = protobuf.PrivateKey
@abstractmethod
def sign(self, data: bytes) -> bytes:
...
@ -65,12 +76,21 @@ class PrivateKey(Key):
def get_public_key(self) -> PublicKey:
...
def serialize_to_protobuf(self) -> protobuf.PrivateKey:
def _serialize_to_protobuf(self) -> protobuf.PrivateKey:
"""
Return the protobuf representation of this ``Key``.
"""
key_type = self.get_type().value
data = self.to_bytes()
protobuf_key = protobuf.PrivateKey(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()
@dataclass(frozen=True)
class KeyPair:

View File

@ -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())

View File

@ -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())