89 lines
2.5 KiB
Python
Raw Normal View History

2019-07-28 22:30:51 +08:00
import hashlib
2019-07-31 15:00:12 -07:00
from typing import Union
2019-07-27 16:27:01 +08:00
2018-11-18 17:22:56 +01:00
import base58
2019-07-28 22:30:51 +08:00
import multihash
2019-07-28 22:30:51 +08:00
from Crypto.PublicKey.RSA import RsaKey
# MaxInlineKeyLength is the maximum length a key can be for it to be inlined in
# the peer ID.
# * When `len(pubKey.Bytes()) <= MaxInlineKeyLength`, the peer ID is the
# identity multihash hash of the public key.
# * When `len(pubKey.Bytes()) > MaxInlineKeyLength`, the peer ID is the
# sha2-256 multihash of the public key.
MAX_INLINE_KEY_LENGTH = 42
2018-11-18 17:22:56 +01:00
class ID:
2019-07-31 19:26:13 +08:00
_bytes: bytes
_xor_id: int = None
_b58_str: str = None
2019-07-27 16:27:01 +08:00
2019-07-31 19:26:13 +08:00
def __init__(self, peer_id_bytes: bytes) -> None:
self._bytes = peer_id_bytes
2018-11-18 17:22:56 +01:00
2019-07-31 19:26:13 +08:00
@property
def xor_id(self) -> int:
if not self._xor_id:
self._xor_id = int(digest(self._bytes).hex(), 16)
return self._xor_id
2019-07-31 19:26:13 +08:00
def to_bytes(self) -> bytes:
return self._bytes
def to_base58(self) -> str:
if not self._b58_str:
self._b58_str = base58.b58encode(self._bytes).decode()
return self._b58_str
def __bytes__(self) -> bytes:
return self._bytes
2018-11-18 17:22:56 +01:00
__repr__ = __str__ = pretty = to_string = to_base58
2019-07-27 16:27:01 +08:00
def __eq__(self, other: object) -> bool:
# pylint: disable=protected-access, no-else-return
if isinstance(other, str):
return self.to_base58() == other
elif isinstance(other, bytes):
2019-07-31 19:26:13 +08:00
return self._bytes == other
elif isinstance(other, ID):
return self._bytes == other._bytes
else:
2019-07-27 16:27:01 +08:00
return NotImplemented
2019-07-27 16:27:01 +08:00
def __hash__(self) -> int:
2019-07-31 19:26:13 +08:00
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())
2019-07-27 16:27:01 +08:00
def digest(data: Union[str, bytes]) -> bytes:
2019-07-30 23:41:28 +08:00
if isinstance(data, str):
2019-07-31 15:00:12 -07:00
data = data.encode("utf8")
2019-07-29 12:42:13 +08:00
return hashlib.sha1(data).digest()