Change argument name of Network.listen and blakc format

This commit is contained in:
NIC619 2019-08-01 13:25:20 +08:00
parent cd684aad9e
commit 924e965537
No known key found for this signature in database
GPG Key ID: 570C35F5C2D51B17
7 changed files with 23 additions and 35 deletions

View File

@ -136,8 +136,11 @@ class KadPeerHeap:
def get_uncontacted(self): def get_uncontacted(self):
return [n for n in self if n.peer_id_bytes not in self.contacted] return [n for n in self if n.peer_id_bytes not in self.contacted]
def create_kad_peerinfo(node_id_bytes=None, sender_ip=None, sender_port=None): def create_kad_peerinfo(node_id_bytes=None, sender_ip=None, sender_port=None):
node_id = ID(node_id_bytes) if node_id_bytes else ID(digest(random.getrandbits(255))) node_id = (
ID(node_id_bytes) if node_id_bytes else ID(digest(random.getrandbits(255)))
)
peer_data = None peer_data = None
if sender_ip and sender_port: if sender_ip and sender_port:
peer_data = PeerData() # pylint: disable=no-value-for-parameter peer_data = PeerData() # pylint: disable=no-value-for-parameter

View File

@ -212,10 +212,10 @@ class KademliaServer:
""" """
log.info("Saving state to %s", fname) log.info("Saving state to %s", fname)
data = { data = {
'ksize': self.ksize, "ksize": self.ksize,
'alpha': self.alpha, "alpha": self.alpha,
'id': self.node.peer_id_bytes, "id": self.node.peer_id_bytes,
'neighbors': self.bootstrappable_neighbors() "neighbors": self.bootstrappable_neighbors(),
} }
if not data["neighbors"]: if not data["neighbors"]:
log.warning("No known neighbors, so not writing to cache.") log.warning("No known neighbors, so not writing to cache.")

View File

@ -58,9 +58,9 @@ class INetwork(ABC):
""" """
@abstractmethod @abstractmethod
async def listen(self, *args: Sequence[Multiaddr]) -> bool: async def listen(self, multiaddrs: Sequence[Multiaddr]) -> bool:
""" """
:param *args: one or many multiaddrs to start listening on :param multiaddrs: one or many multiaddrs to start listening on
:return: True if at least one success :return: True if at least one success
""" """

View File

@ -163,12 +163,12 @@ class Swarm(INetwork):
return net_stream return net_stream
async def listen(self, *args: Sequence[Multiaddr]) -> bool: async def listen(self, multiaddrs: Sequence[Multiaddr]) -> bool:
""" """
:param *args: one or many multiaddrs to start listening on :param multiaddrs: one or many multiaddrs to start listening on
:return: true if at least one success :return: true if at least one success
For each multiaddr in args For each multiaddr
Check if a listener for multiaddr exists already Check if a listener for multiaddr exists already
If listener already exists, continue If listener already exists, continue
Otherwise: Otherwise:
@ -177,7 +177,7 @@ class Swarm(INetwork):
Call listener listen with the multiaddr Call listener listen with the multiaddr
Map multiaddr to listener Map multiaddr to listener
""" """
for multiaddr in args: for multiaddr in multiaddrs:
if str(multiaddr) in self.listeners: if str(multiaddr) in self.listeners:
return True return True

View File

@ -42,7 +42,7 @@ class ID:
__repr__ = __str__ __repr__ = __str__
def __eq__(self, other: object) -> bool: def __eq__(self, other: object) -> bool:
#pylint: disable=protected-access, no-else-return # pylint: disable=protected-access, no-else-return
if isinstance(other, bytes): if isinstance(other, bytes):
return self._bytes == other return self._bytes == other
elif isinstance(other, ID): elif isinstance(other, ID):
@ -54,13 +54,13 @@ class ID:
return hash(self._bytes) return hash(self._bytes)
@classmethod @classmethod
def from_base58(cls, b58_encoded_peer_id_str: str) -> 'ID': def from_base58(cls, b58_encoded_peer_id_str: str) -> "ID":
peer_id_bytes = base58.b58decode(b58_encoded_peer_id_str) peer_id_bytes = base58.b58decode(b58_encoded_peer_id_str)
pid = ID(peer_id_bytes) pid = ID(peer_id_bytes)
return pid return pid
@classmethod @classmethod
def from_pubkey(cls, key: RsaKey) -> 'ID': def from_pubkey(cls, key: RsaKey) -> "ID":
# export into binary format # export into binary format
key_bin = key.exportKey("DER") key_bin = key.exportKey("DER")
@ -73,7 +73,7 @@ class ID:
return cls(mh_digest.encode()) return cls(mh_digest.encode())
@classmethod @classmethod
def from_privkey(cls, key: RsaKey) -> 'ID': def from_privkey(cls, key: RsaKey) -> "ID":
return cls.from_pubkey(key.publickey()) return cls.from_pubkey(key.publickey())
@ -81,7 +81,7 @@ def id_b58_encode(peer_id: ID) -> str:
""" """
return a b58-encoded string return a b58-encoded string
""" """
#pylint: disable=protected-access # pylint: disable=protected-access
return base58.b58encode(peer_id.to_bytes()).decode() return base58.b58encode(peer_id.to_bytes()).decode()

View File

@ -1,14 +1,7 @@
from ast import literal_eval from ast import literal_eval
import asyncio import asyncio
import random import random
from typing import ( from typing import Any, Dict, Iterable, List, Set, Sequence
Any,
Dict,
Iterable,
List,
Set,
Sequence,
)
from libp2p.peer.id import ID from libp2p.peer.id import ID
@ -287,11 +280,7 @@ class GossipSub(IPubsubRouter):
return "unknown" return "unknown"
async def deliver_messages_to_peers( async def deliver_messages_to_peers(
self, self, peers: List[ID], msg_sender: ID, origin_id: ID, serialized_packet: bytes
peers: List[ID],
msg_sender: ID,
origin_id: ID,
serialized_packet: bytes,
) -> None: ) -> None:
for peer_id_in_topic in peers: for peer_id_in_topic in peers:
# Forward to all peers that are not the # Forward to all peers that are not the

View File

@ -3,10 +3,7 @@ import multihash
import pytest import pytest
import base58 import base58
from Crypto.PublicKey import RSA from Crypto.PublicKey import RSA
from libp2p.peer.id import ( from libp2p.peer.id import ID, id_b58_encode
ID,
id_b58_encode,
)
ALPHABETS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz" ALPHABETS = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"
@ -17,11 +14,10 @@ def test_init():
for _ in range(10): for _ in range(10):
random_id_string += random.SystemRandom().choice(ALPHABETS) random_id_string += random.SystemRandom().choice(ALPHABETS)
peer_id = ID(random_id_string.encode()) peer_id = ID(random_id_string.encode())
#pylint: disable=protected-access # pylint: disable=protected-access
assert peer_id == random_id_string.encode() assert peer_id == random_id_string.encode()
def test_no_init_value(): def test_no_init_value():
with pytest.raises(Exception) as _: with pytest.raises(Exception) as _:
# pylint: disable=no-value-for-parameter # pylint: disable=no-value-for-parameter