Done PEP8 formatting in network.bmproto (Fixes: #1703)

This commit is contained in:
Dmitri Bogomolov 2019-11-27 19:07:15 +02:00
parent 49f9620236
commit 3f63278468
Signed by untrusted user: g1itch
GPG Key ID: 720A756F18DEED13

View File

@ -1,7 +1,7 @@
""" """
Bitmessage Protocol Class BMProto defines bitmessage's network protocol workflow.
""" """
# pylint: disable=attribute-defined-outside-init, too-few-public-methods
import base64 import base64
import hashlib import hashlib
import logging import logging
@ -66,6 +66,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
self.pendingUpload = RandomTrackingDict() self.pendingUpload = RandomTrackingDict()
# canonical identifier of network group # canonical identifier of network group
self.network_group = None self.network_group = None
# userAgent initialization
self.userAgent = ''
def bm_proto_reset(self): def bm_proto_reset(self):
"""Reset the bitmessage object parser""" """Reset the bitmessage object parser"""
@ -185,7 +187,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
return Node(services, host, port) return Node(services, host, port)
# pylint: disable=too-many-branches, too-many-statements # pylint: disable=too-many-branches,too-many-statements
def decode_payload_content(self, pattern="v"): def decode_payload_content(self, pattern="v"):
""" """
Decode the payload depending on pattern: Decode the payload depending on pattern:
@ -202,7 +204,6 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
, = end of array , = end of array
""" """
# pylint: disable=inconsistent-return-statements
def decode_simple(self, char="v"): def decode_simple(self, char="v"):
"""Decode the payload using one char pattern""" """Decode the payload using one char pattern"""
if char == "v": if char == "v":
@ -221,6 +222,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
self.payloadOffset += 8 self.payloadOffset += 8
return struct.unpack(">Q", self.payload[ return struct.unpack(">Q", self.payload[
self.payloadOffset - 8:self.payloadOffset])[0] self.payloadOffset - 8:self.payloadOffset])[0]
return None
size = None size = None
isArray = False isArray = False
@ -254,10 +256,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
]) ])
parserStack[-2][4] = len(parserStack[-2][3]) parserStack[-2][4] = len(parserStack[-2][3])
else: else:
for j in range(parserStack[-1][4], len(parserStack[-1][3])): j = 0
for j in range(
parserStack[-1][4], len(parserStack[-1][3])):
if parserStack[-1][3][j] not in "lL0123456789": if parserStack[-1][3][j] not in "lL0123456789":
break break
# pylint: disable=undefined-loop-variable
parserStack.append([ parserStack.append([
size, size, isArray, size, size, isArray,
parserStack[-1][3][parserStack[-1][4]:j + 1], 0, [] parserStack[-1][3][parserStack[-1][4]:j + 1], 0, []
@ -268,7 +271,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
elif i == "s": elif i == "s":
# if parserStack[-2][2]: # if parserStack[-2][2]:
# parserStack[-1][5].append(self.payload[ # parserStack[-1][5].append(self.payload[
# self.payloadOffset:self.payloadOffset + parserStack[-1][0]]) # self.payloadOffset:self.payloadOffset
# + parserStack[-1][0]])
# else: # else:
parserStack[-1][5] = self.payload[ parserStack[-1][5] = self.payload[
self.payloadOffset:self.payloadOffset + parserStack[-1][0]] self.payloadOffset:self.payloadOffset + parserStack[-1][0]]
@ -339,6 +343,10 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
return True return True
def _command_inv(self, dandelion=False): def _command_inv(self, dandelion=False):
"""
Common inv announce implementation:
both inv and dinv depending on *dandelion* kwarg
"""
items = self.decode_payload_content("l32s") items = self.decode_payload_content("l32s")
if len(items) > MAX_OBJECT_COUNT: if len(items) > MAX_OBJECT_COUNT:
@ -376,10 +384,11 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
nonce, expiresTime, objectType, version, streamNumber, nonce, expiresTime, objectType, version, streamNumber,
self.payload, self.payloadOffset) self.payload, self.payloadOffset)
if len(self.payload) - self.payloadOffset > MAX_OBJECT_PAYLOAD_SIZE: payload_len = len(self.payload) - self.payloadOffset
if payload_len > MAX_OBJECT_PAYLOAD_SIZE:
logger.info( logger.info(
'The payload length of this object is too large (%d bytes).' 'The payload length of this object is too large'
' Ignoring it.', len(self.payload) - self.payloadOffset) ' (%d bytes). Ignoring it.', payload_len)
raise BMProtoExcessiveDataError() raise BMProtoExcessiveDataError()
try: try:
@ -434,9 +443,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
def bm_command_addr(self): def bm_command_addr(self):
"""Incoming addresses, process them""" """Incoming addresses, process them"""
# pylint: disable=redefined-outer-name # not using services
addresses = self._decode_addr() for seenTime, stream, _, ip, port in self._decode_addr():
for seenTime, stream, _, ip, port in addresses:
ip = str(ip) ip = str(ip)
if ( if (
stream not in state.streamsInWhichIAmParticipating stream not in state.streamsInWhichIAmParticipating
@ -446,8 +454,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
continue continue
decodedIP = protocol.checkIPAddress(ip) decodedIP = protocol.checkIPAddress(ip)
if ( if (
decodedIP decodedIP and time.time() - seenTime > 0
and time.time() - seenTime > 0
and seenTime > time.time() - ADDRESS_ALIVE and seenTime > time.time() - ADDRESS_ALIVE
and port > 0 and port > 0
): ):
@ -475,7 +482,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
self.append_write_buf(protocol.CreatePacket('pong')) self.append_write_buf(protocol.CreatePacket('pong'))
return True return True
def bm_command_pong(self): # pylint: disable=no-self-use @staticmethod
def bm_command_pong():
""" """
Incoming pong. Incoming pong.
Ignore it. PyBitmessage pings connections after about 5 minutes Ignore it. PyBitmessage pings connections after about 5 minutes
@ -562,7 +570,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
" compared to mine. Closing connection.", fatal=2)) " compared to mine. Closing connection.", fatal=2))
logger.info( logger.info(
"%s's time is too far in the future (%s seconds)." "%s's time is too far in the future (%s seconds)."
" Closing connection to it.", self.destination, self.timeOffset) " Closing connection to it.",
self.destination, self.timeOffset)
BMProto.timeOffsetWrongCount += 1 BMProto.timeOffsetWrongCount += 1
return False return False
elif self.timeOffset < -MAX_TIME_OFFSET: elif self.timeOffset < -MAX_TIME_OFFSET:
@ -570,8 +579,9 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
errorText="Your time is too far in the past compared to mine." errorText="Your time is too far in the past compared to mine."
" Closing connection.", fatal=2)) " Closing connection.", fatal=2))
logger.info( logger.info(
"%s's time is too far in the past (timeOffset %s seconds)." "%s's time is too far in the past"
" Closing connection to it.", self.destination, self.timeOffset) " (timeOffset %s seconds). Closing connection to it.",
self.destination, self.timeOffset)
BMProto.timeOffsetWrongCount += 1 BMProto.timeOffsetWrongCount += 1
return False return False
else: else:
@ -584,7 +594,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
'Closed connection to %s because there is no overlapping' 'Closed connection to %s because there is no overlapping'
' interest in streams.', self.destination) ' interest in streams.', self.destination)
return False return False
if self.destination in connectionpool.BMConnectionPool().inboundConnections: if connectionpool.BMConnectionPool().inboundConnections.get(
self.destination):
try: try:
if not protocol.checkSocksIP(self.destination.host): if not protocol.checkSocksIP(self.destination.host):
self.append_write_buf(protocol.assembleErrorMessage( self.append_write_buf(protocol.assembleErrorMessage(
@ -594,7 +605,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
'Closed connection to %s because we are already' 'Closed connection to %s because we are already'
' connected to that IP.', self.destination) ' connected to that IP.', self.destination)
return False return False
except Exception: except Exception: # TODO: exception types
pass pass
if not self.isOutbound: if not self.isOutbound:
# incoming from a peer we're connected to as outbound, # incoming from a peer we're connected to as outbound,
@ -614,8 +625,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
'Closed connection to %s due to server full' 'Closed connection to %s due to server full'
' or duplicate inbound/outbound.', self.destination) ' or duplicate inbound/outbound.', self.destination)
return False return False
if connectionpool.BMConnectionPool().isAlreadyConnected( if connectionpool.BMConnectionPool().isAlreadyConnected(self.nonce):
self.nonce):
self.append_write_buf(protocol.assembleErrorMessage( self.append_write_buf(protocol.assembleErrorMessage(
errorText="I'm connected to myself. Closing connection.", errorText="I'm connected to myself. Closing connection.",
fatal=2)) fatal=2))
@ -628,7 +638,7 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
@staticmethod @staticmethod
def stopDownloadingObject(hashId, forwardAnyway=False): def stopDownloadingObject(hashId, forwardAnyway=False):
"""Stop downloading an object""" """Stop downloading object *hashId*"""
for connection in connectionpool.BMConnectionPool().connections(): for connection in connectionpool.BMConnectionPool().connections():
try: try:
del connection.objectsNewToMe[hashId] del connection.objectsNewToMe[hashId]
@ -658,7 +668,8 @@ class BMProto(AdvancedDispatcher, ObjectTracker):
except AttributeError: except AttributeError:
try: try:
logger.debug( logger.debug(
'%(host)s:%(port)i: closing', self.destination._asdict()) '%s:%i: closing',
self.destination.host, self.destination.port)
except AttributeError: except AttributeError:
logger.debug('Disconnected socket closing') logger.debug('Disconnected socket closing')
AdvancedDispatcher.handle_close(self) AdvancedDispatcher.handle_close(self)