Convert from base58/pubkey/privkey to class method

This commit is contained in:
NIC619
2019-07-31 19:31:58 +08:00
parent 80481252ca
commit b928bdb356
7 changed files with 46 additions and 19 deletions

View File

@ -53,6 +53,29 @@ class ID:
def __hash__(self) -> int:
return hash(self._bytes)
@classmethod
def from_base58(cls, b58_encoded_peer_id_str: str) -> 'ID':
peer_id_bytes = base58.b58decode(b58_encoded_peer_id_str)
pid = ID(peer_id_bytes)
return pid
@classmethod
def from_pubkey(cls, key: RsaKey) -> 'ID':
# export into binary format
key_bin = key.exportKey("DER")
algo: int = multihash.Func.sha2_256
# TODO: seems identity is not yet supported in pymultihash
# if len(b) <= MAX_INLINE_KEY_LENGTH:
# algo multihash.func.identity
mh_digest: multihash.Multihash = multihash.digest(key_bin, algo)
return cls(mh_digest.encode())
@classmethod
def from_privkey(cls, key: RsaKey) -> 'ID':
return cls.from_pubkey(key.publickey())
def id_b58_encode(peer_id: ID) -> str:
"""

View File

@ -2,7 +2,7 @@ from typing import List
import multiaddr
from .id import ID, id_b58_decode
from .id import ID
from .peerdata import PeerData
@ -39,7 +39,7 @@ def info_from_p2p_addr(addr: multiaddr.Multiaddr) -> PeerInfo:
# make sure the /p2p value parses as a peer.ID
peer_id_str: str = p2p_part.value_for_protocol(multiaddr.protocols.P_P2P)
peer_id: ID = id_b58_decode(peer_id_str)
peer_id: ID = ID.from_base58(peer_id_str)
# we might have received just an / p2p part, which means there's no addr.
if len(parts) > 1: