From 0173b5e0d9ef4aac1daede6d716b0d1ef5963b42 Mon Sep 17 00:00:00 2001 From: NIC619 Date: Thu, 1 Aug 2019 21:48:30 +0800 Subject: [PATCH] Add ID.to_base58() and comparison against str type --- libp2p/peer/id.py | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/libp2p/peer/id.py b/libp2p/peer/id.py index 73c65bc..9ad8821 100644 --- a/libp2p/peer/id.py +++ b/libp2p/peer/id.py @@ -20,6 +20,7 @@ class ID: _bytes: bytes _xor_id: int = None + _b58_str: str = None def __init__(self, peer_id_bytes: bytes) -> None: self._bytes = peer_id_bytes @@ -33,17 +34,21 @@ class ID: def to_bytes(self) -> bytes: return self._bytes - def pretty(self) -> str: - return base58.b58encode(self._bytes).decode() + def to_base58(self) -> str: + if not self._b58_str: + self._b58_str = base58.b58encode(self._bytes).decode() + return self._b58_str - def __str__(self) -> str: - return self.pretty() + def __bytes__(self) -> bytes: + return self._bytes - __repr__ = __str__ + __repr__ = __str__ = pretty = to_string = to_base58 def __eq__(self, other: object) -> bool: # pylint: disable=protected-access, no-else-return - if isinstance(other, bytes): + if isinstance(other, str): + return self.to_base58() == other + elif isinstance(other, bytes): return self._bytes == other elif isinstance(other, ID): return self._bytes == other._bytes