From 6506079a362178907ae3f77f6725421ad34e6bad Mon Sep 17 00:00:00 2001 From: Alex Stokes Date: Tue, 13 Aug 2019 18:19:01 -0700 Subject: [PATCH] Generate peer IDs according to the spec --- libp2p/peer/id.py | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/libp2p/peer/id.py b/libp2p/peer/id.py index d9f0dc5..bfb78d0 100644 --- a/libp2p/peer/id.py +++ b/libp2p/peer/id.py @@ -4,6 +4,15 @@ from typing import Union import base58 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: @@ -53,9 +62,10 @@ class ID: return pid @classmethod - def from_pubkey(cls, key: bytes) -> "ID": + def from_pubkey(cls, key: PublicKey) -> "ID": + serialized_key = _serialize_public_key(key) algo = multihash.Func.sha2_256 - mh_digest = multihash.digest(key, algo) + mh_digest = multihash.digest(serialized_key, algo) return cls(mh_digest.encode())