Merge branch 'master' into feature/trio

This commit is contained in:
mhchia 2020-02-06 10:39:54 +08:00
commit f1dbd52d67
No known key found for this signature in database
GPG Key ID: 389EFBEA1362589A
15 changed files with 69 additions and 58 deletions

View File

@ -32,7 +32,7 @@ class ECCPublicKey(PublicKey):
return KeyType.ECC_P256
def verify(self, data: bytes, signature: bytes) -> bool:
raise NotImplementedError
raise NotImplementedError()
class ECCPrivateKey(PrivateKey):
@ -53,7 +53,7 @@ class ECCPrivateKey(PrivateKey):
return KeyType.ECC_P256
def sign(self, data: bytes) -> bytes:
raise NotImplementedError
raise NotImplementedError()
def get_public_key(self) -> PublicKey:
public_key_impl = keys.get_public_key(self.impl, self.curve)

View File

@ -20,8 +20,10 @@ def deserialize_public_key(data: bytes) -> PublicKey:
f = PublicKey.deserialize_from_protobuf(data)
try:
deserializer = key_type_to_public_key_deserializer[f.key_type]
except KeyError:
raise MissingDeserializerError({"key_type": f.key_type, "key": "public_key"})
except KeyError as e:
raise MissingDeserializerError(
{"key_type": f.key_type, "key": "public_key"}
) from e
return deserializer(f.data)
@ -29,6 +31,8 @@ def deserialize_private_key(data: bytes) -> PrivateKey:
f = PrivateKey.deserialize_from_protobuf(data)
try:
deserializer = key_type_to_private_key_deserializer[f.key_type]
except KeyError:
raise MissingDeserializerError({"key_type": f.key_type, "key": "private_key"})
except KeyError as e:
raise MissingDeserializerError(
{"key_type": f.key_type, "key": "private_key"}
) from e
return deserializer(f.data)

View File

@ -95,7 +95,7 @@ class BasicHost(IHost):
:return: all the multiaddr addresses this host is listening to
"""
# TODO: We don't need "/p2p/{peer_id}" postfix actually.
p2p_part = multiaddr.Multiaddr("/p2p/{}".format(self.get_id().pretty()))
p2p_part = multiaddr.Multiaddr(f"/p2p/{self.get_id()!s}")
addrs: List[multiaddr.Multiaddr] = []
for transport in self._network.listeners.values():
@ -147,7 +147,7 @@ class BasicHost(IHost):
except MultiselectClientError as error:
logger.debug("fail to open a stream to peer %s, error=%s", peer_id, error)
await net_stream.reset()
raise StreamFailure("failt to open a stream to peer %s", peer_id) from error
raise StreamFailure(f"failed to open a stream to peer {peer_id}") from error
net_stream.set_protocol(selected_protocol)
return net_stream

View File

@ -47,9 +47,9 @@ class NetStream(INetStream):
try:
return await self.muxed_stream.read(n)
except MuxedStreamEOF as error:
raise StreamEOF from error
raise StreamEOF() from error
except MuxedStreamReset as error:
raise StreamReset from error
raise StreamReset() from error
async def write(self, data: bytes) -> int:
"""
@ -60,7 +60,7 @@ class NetStream(INetStream):
try:
return await self.muxed_stream.write(data)
except MuxedStreamClosed as error:
raise StreamClosed from error
raise StreamClosed() from error
async def close(self) -> None:
"""close stream."""

View File

@ -171,20 +171,21 @@ class Swarm(Service, INetworkService):
try:
secured_conn = await self.upgrader.upgrade_security(raw_conn, peer_id, True)
except SecurityUpgradeFailure as error:
error_msg = "fail to upgrade security for peer %s"
logger.debug(error_msg, peer_id)
logger.debug("failed to upgrade security for peer %s", peer_id)
await raw_conn.close()
raise SwarmException(error_msg % peer_id) from error
raise SwarmException(
f"failed to upgrade security for peer {peer_id}"
) from error
logger.debug("upgraded security for peer %s", peer_id)
try:
muxed_conn = await self.upgrader.upgrade_connection(secured_conn, peer_id)
except MuxerUpgradeFailure as error:
error_msg = "fail to upgrade mux for peer %s"
logger.debug(error_msg, peer_id)
logger.debug("failed to upgrade mux for peer %s", peer_id)
await secured_conn.close()
raise SwarmException(error_msg % peer_id) from error
raise SwarmException(f"failed to upgrade mux for peer {peer_id}") from error
logger.debug("upgraded mux for peer %s", peer_id)
swarm_conn = await self.add_conn(muxed_conn)
@ -241,8 +242,11 @@ class Swarm(Service, INetworkService):
raw_conn, ID(b""), False
)
except SecurityUpgradeFailure as error:
logger.debug("failed to upgrade security for peer at %s", maddr)
await raw_conn.close()
raise SwarmException() from error
raise SwarmException(
f"failed to upgrade security for peer at {maddr}"
) from error
peer_id = secured_conn.get_remote_peer()
try:
@ -250,10 +254,11 @@ class Swarm(Service, INetworkService):
secured_conn, peer_id
)
except MuxerUpgradeFailure as error:
error_msg = "fail to upgrade mux for peer %s"
logger.debug(error_msg, peer_id)
logger.debug("fail to upgrade mux for peer %s", peer_id)
await secured_conn.close()
raise SwarmException(error_msg % peer_id) from error
raise SwarmException(
f"fail to upgrade mux for peer {peer_id}"
) from error
logger.debug("upgraded mux for peer %s", peer_id)
await self.add_conn(muxed_conn)
@ -279,7 +284,7 @@ class Swarm(Service, INetworkService):
return True
except IOError:
# Failed. Continue looping.
logger.debug("fail to listen on: " + str(maddr))
logger.debug("fail to listen on: %s", maddr)
# No maddr succeeded
return False

View File

@ -56,7 +56,7 @@ class ID:
return self._b58_str
def __repr__(self) -> str:
return f"<libp2p.peer.id.ID ({self.to_string()})>"
return f"<libp2p.peer.id.ID ({self!s})>"
__str__ = pretty = to_string = to_base58

View File

@ -71,7 +71,7 @@ class PeerStore(IPeerStore):
try:
val = self.peer_data_map[peer_id].get_metadata(key)
except PeerDataError as error:
raise PeerStoreError(error)
raise PeerStoreError() from error
return val
raise PeerStoreError("peer ID not found")
@ -153,8 +153,8 @@ class PeerStore(IPeerStore):
peer_data = self.peer_data_map[peer_id]
try:
pubkey = peer_data.get_pubkey()
except PeerDataError:
raise PeerStoreError("peer pubkey not found")
except PeerDataError as e:
raise PeerStoreError("peer pubkey not found") from e
return pubkey
raise PeerStoreError("peer ID not found")
@ -179,8 +179,8 @@ class PeerStore(IPeerStore):
peer_data = self.peer_data_map[peer_id]
try:
privkey = peer_data.get_privkey()
except PeerDataError:
raise PeerStoreError("peer privkey not found")
except PeerDataError as e:
raise PeerStoreError("peer privkey not found") from e
return privkey
raise PeerStoreError("peer ID not found")

View File

@ -49,7 +49,7 @@ class Multiselect(IMultiselectMuxer):
try:
command = await communicator.read()
except MultiselectCommunicatorError as error:
raise MultiselectError(error)
raise MultiselectError() from error
if command == "ls":
# TODO: handle ls command
@ -60,13 +60,13 @@ class Multiselect(IMultiselectMuxer):
try:
await communicator.write(protocol)
except MultiselectCommunicatorError as error:
raise MultiselectError(error)
raise MultiselectError() from error
return protocol, self.handlers[protocol]
try:
await communicator.write(PROTOCOL_NOT_FOUND_MSG)
except MultiselectCommunicatorError as error:
raise MultiselectError(error)
raise MultiselectError() from error
async def handshake(self, communicator: IMultiselectCommunicator) -> None:
"""
@ -78,12 +78,12 @@ class Multiselect(IMultiselectMuxer):
try:
await communicator.write(MULTISELECT_PROTOCOL_ID)
except MultiselectCommunicatorError as error:
raise MultiselectError(error)
raise MultiselectError() from error
try:
handshake_contents = await communicator.read()
except MultiselectCommunicatorError as error:
raise MultiselectError(error)
raise MultiselectError() from error
if not is_valid_handshake(handshake_contents):
raise MultiselectError(

View File

@ -25,12 +25,12 @@ class MultiselectClient(IMultiselectClient):
try:
await communicator.write(MULTISELECT_PROTOCOL_ID)
except MultiselectCommunicatorError as error:
raise MultiselectClientError(error)
raise MultiselectClientError() from error
try:
handshake_contents = await communicator.read()
except MultiselectCommunicatorError as error:
raise MultiselectClientError(str(error))
raise MultiselectClientError() from error
if not is_valid_handshake(handshake_contents):
raise MultiselectClientError("multiselect protocol ID mismatch")
@ -73,18 +73,18 @@ class MultiselectClient(IMultiselectClient):
try:
await communicator.write(protocol)
except MultiselectCommunicatorError as error:
raise MultiselectClientError(error)
raise MultiselectClientError() from error
try:
response = await communicator.read()
except MultiselectCommunicatorError as error:
raise MultiselectClientError(str(error))
raise MultiselectClientError() from error
if response == protocol:
return protocol
if response == PROTOCOL_NOT_FOUND_MSG:
raise MultiselectClientError("protocol not supported")
raise MultiselectClientError("unrecognized response: " + response)
raise MultiselectClientError(f"unrecognized response: {response}")
def is_valid_handshake(handshake_contents: str) -> bool:

View File

@ -567,10 +567,12 @@ class Pubsub(Service, IPubsub):
await self.validate_msg(msg_forwarder, msg)
except ValidationError:
logger.debug(
"Topic validation failed: sender %s sent data %s under topic IDs: %s",
f"{base58.b58encode(msg.from_id).decode()}:{msg.seqno.hex()}",
"Topic validation failed: sender %s sent data %s under topic IDs: %s %s:%s",
msg_forwarder,
msg.data.hex(),
msg.topicIDs,
base58.b58encode(msg.from_id).decode(),
msg.seqno.hex(),
)
return

View File

@ -52,13 +52,13 @@ class InsecureSession(BaseSession):
encoded_msg_bytes = encode_fixedint_prefixed(msg_bytes)
try:
await self.write(encoded_msg_bytes)
except RawConnError:
raise HandshakeFailure("connection closed")
except RawConnError as e:
raise HandshakeFailure("connection closed") from e
try:
remote_msg_bytes = await read_fixedint_prefixed(self.conn)
except RawConnError:
raise HandshakeFailure("connection closed")
except RawConnError as e:
raise HandshakeFailure("connection closed") from e
remote_msg = plaintext_pb2.Exchange()
remote_msg.ParseFromString(remote_msg_bytes)
received_peer_id = ID(remote_msg.id)
@ -77,12 +77,12 @@ class InsecureSession(BaseSession):
received_pubkey = deserialize_public_key(
remote_msg.pubkey.SerializeToString()
)
except ValueError:
except ValueError as e:
raise HandshakeFailure(
f"unknown `key_type` of remote_msg.pubkey={remote_msg.pubkey}"
)
) from e
except MissingDeserializerError as error:
raise HandshakeFailure(error)
raise HandshakeFailure() from error
peer_id_from_received_pubkey = ID.from_pubkey(received_pubkey)
if peer_id_from_received_pubkey != received_peer_id:
raise HandshakeFailure(

View File

@ -131,8 +131,8 @@ class SecureSession(BaseSession):
msg = await self.conn.read_msg()
try:
decrypted_msg = self.remote_encrypter.decrypt_if_valid(msg)
except InvalidMACException:
raise DecryptionFailedException
except InvalidMACException as e:
raise DecryptionFailedException() from e
return decrypted_msg
async def write(self, data: bytes) -> int:
@ -175,7 +175,7 @@ class Proposal:
try:
public_key = deserialize_public_key(public_key_protobuf_bytes)
except MissingDeserializerError as error:
raise SedesException(error)
raise SedesException() from error
exchanges = protobuf.exchanges
ciphers = protobuf.ciphers
hashes = protobuf.hashes
@ -424,8 +424,8 @@ async def create_secure_session(
await conn.close()
raise e
# `IOException` includes errors raised while read from/write to raw connection
except IOException:
raise SecioException("connection closed")
except IOException as e:
raise SecioException("connection closed") from e
is_initiator = remote_peer is not None
session = _mk_session_from(
@ -435,8 +435,8 @@ async def create_secure_session(
try:
received_nonce = await _finish_handshake(session, remote_nonce)
# `IOException` includes errors raised while read from/write to raw connection
except IOException:
raise SecioException("connection closed")
except IOException as e:
raise SecioException("connection closed") from e
if received_nonce != local_nonce:
await conn.close()
raise InconsistentNonce()

View File

@ -26,7 +26,7 @@ class P2PDProcess(BaseInteractiveProcess):
is_pubsub_signing: bool = False,
is_pubsub_signing_strict: bool = False,
) -> None:
args = [f"-listen={str(control_maddr)}"]
args = [f"-listen={control_maddr!s}"]
# NOTE: To support `-insecure`, we need to hack `go-libp2p-daemon`.
if not is_secure:
args.append("-insecure=true")

View File

@ -81,7 +81,7 @@ class DummyAccountNode(Service):
:param dest_user: user to send crypto to
:param amount: amount of crypto to send
"""
msg_contents = "send," + source_user + "," + dest_user + "," + str(amount)
msg_contents = f"send,{source_user},{dest_user},{amount!s}"
await self.pubsub.publish(CRYPTO_TOPIC, msg_contents.encode())
async def publish_set_crypto(self, user: str, amount: int) -> None:
@ -92,7 +92,7 @@ class DummyAccountNode(Service):
:param user: user to set crypto for
:param amount: amount of crypto
"""
msg_contents = "set," + user + "," + str(amount)
msg_contents = f"set,{user},{amount!s}"
await self.pubsub.publish(CRYPTO_TOPIC, msg_contents.encode())
def handle_send_crypto(self, source_user: str, dest_user: str, amount: int) -> None:

View File

@ -12,7 +12,7 @@ envlist =
combine_as_imports=False
force_sort_within_sections=True
include_trailing_comma=True
known_third_party=anyio,factory,p2pclient,pytest
known_third_party=anyio,factory,lru,p2pclient,pytest
known_first_party=libp2p
line_length=88
multi_line_output=3