Skip to content

Commit 15ecf31

Browse files
committed
Improve python3 compatibility of network module
- some network tests now run with python3, rest use mock network
1 parent 5e43fe2 commit 15ecf31

11 files changed

Lines changed: 38 additions & 24 deletions

File tree

‎src/mockbm/network.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,28 @@ class objectracker(object):
1414
class stats(object):
1515
"""Mock network statistics"""
1616

17+
pool = None
18+
19+
@staticmethod
20+
def init(pool_instance):
21+
"""Mock init with pool reference"""
22+
stats.pool = pool_instance
23+
1724
@staticmethod
1825
def connectedHostsList():
1926
"""Mock list of all the connected hosts"""
2027
return ["conn1", "conn2", "conn3", "conn4"]
2128

29+
@staticmethod
30+
def sentBytes():
31+
"""Mock sent bytes"""
32+
return 1
33+
34+
@staticmethod
35+
def receivedBytes():
36+
"""Mock received bytes"""
37+
return 1
38+
2239
@staticmethod
2340
def pendingDownload():
2441
"""Mock pending download count"""

‎src/network/advanceddispatcher.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ class AdvancedDispatcher(asyncore.dispatcher):
2828
_buf_len = 131072 # 128kB
2929

3030
def __init__(self, sock=None):
31-
if not hasattr(self, '_map'):
31+
if '_map' not in self.__dict__:
3232
asyncore.dispatcher.__init__(self, sock)
3333
self.connectedAt = 0
3434
self.close_reason = None

‎src/network/bmproto.py‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ def state_bm_header(self):
8484
"""Process incoming header"""
8585
self.magic, self.command, self.payloadLength, self.checksum = \
8686
protocol.Header.unpack(self.read_buf[:protocol.Header.size])
87-
self.command = self.command.rstrip('\x00')
87+
self.command = self.command.rstrip(b'\x00').decode('ascii', 'replace')
8888
if self.magic != protocol.magic:
8989
# skip 1 byte in order to sync
9090
self.set_state("bm_header", length=1)
@@ -170,17 +170,17 @@ def decode_payload_node(self):
170170
"""Decode node details from the payload"""
171171
# protocol.checkIPAddress()
172172
services, host, port = self.decode_payload_content("Q16sH")
173-
if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
174-
host = socket.inet_ntop(socket.AF_INET, str(host[12:16]))
175-
elif host[0:6] == '\xfd\x87\xd8\x7e\xeb\x43':
173+
if host[0:12] == b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
174+
host = socket.inet_ntop(socket.AF_INET, bytes(host[12:16]))
175+
elif host[0:6] == b'\xfd\x87\xd8\x7e\xeb\x43':
176176
# Onion, based on BMD/bitcoind
177-
host = base64.b32encode(host[6:]).lower() + ".onion"
177+
host = base64.b32encode(bytes(host[6:])).decode('ascii').lower() + ".onion"
178178
else:
179-
host = socket.inet_ntop(socket.AF_INET6, str(host))
179+
host = socket.inet_ntop(socket.AF_INET6, bytes(host))
180180
if host == "":
181181
# This can happen on Windows systems which are not 64-bit
182182
# compatible so let us drop the IPv6 address.
183-
host = socket.inet_ntop(socket.AF_INET, str(host[12:16]))
183+
host = socket.inet_ntop(socket.AF_INET, bytes(host[12:16]))
184184

185185
return Node(services, host, port)
186186

@@ -445,11 +445,11 @@ def bm_command_addr(self):
445445
"""Incoming addresses, process them"""
446446
# not using services
447447
for seenTime, stream, _, ip, port in self._decode_addr():
448-
ip = str(ip)
448+
ip = bytes(ip)
449449
if (
450450
stream not in self.pool.streams
451451
# FIXME: should check against complete list
452-
or ip.startswith('bootstrap')
452+
or ip.startswith(b'bootstrap')
453453
):
454454
continue
455455
decodedIP = protocol.checkIPAddress(ip)

‎src/network/connectionchooser.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
def getDiscoveredPeer():
2121
"""Get a peer from the local peer discovery list"""
2222
try:
23-
peer = random.choice(state.discoveredPeers.keys()) # nosec B311
23+
peer = random.choice(list(state.discoveredPeers.keys())) # nosec B311
2424
except (IndexError, KeyError):
2525
raise ValueError
2626
try:
@@ -48,7 +48,7 @@ def chooseConnection(stream):
4848
return getDiscoveredPeer()
4949
for _ in range(50):
5050
peer = random.choice( # nosec B311
51-
knownnodes.knownNodes[stream].keys())
51+
list(knownnodes.knownNodes[stream].keys()))
5252
try:
5353
peer_info = knownnodes.knownNodes[stream][peer]
5454
if peer_info.get('self'):

‎src/network/httpd.py‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ class HTTPRequestHandler(asyncore.dispatcher):
3131
</html>"""
3232

3333
def __init__(self, sock):
34-
if not hasattr(self, '_map'):
34+
if '_map' not in self.__dict__:
3535
asyncore.dispatcher.__init__(self, sock)
3636
self.inbuf = ""
3737
self.ready = True
@@ -70,7 +70,7 @@ def handle_write(self):
7070
class HTTPSRequestHandler(HTTPRequestHandler, TLSHandshake):
7171
"""Handling HTTPS request"""
7272
def __init__(self, sock):
73-
if not hasattr(self, '_map'):
73+
if '_map' not in self.__dict__:
7474
asyncore.dispatcher.__init__(self, sock) # pylint: disable=non-parent-init-called
7575
# self.tlsDone = False
7676
TLSHandshake.__init__(
@@ -118,7 +118,7 @@ class HTTPServer(asyncore.dispatcher):
118118
port = 12345
119119

120120
def __init__(self):
121-
if not hasattr(self, '_map'):
121+
if '_map' not in self.__dict__:
122122
asyncore.dispatcher.__init__(self)
123123
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
124124
self.set_reuse_addr()
@@ -142,7 +142,7 @@ class HTTPSServer(HTTPServer):
142142
port = 12345
143143

144144
def __init__(self):
145-
if not hasattr(self, '_map'):
145+
if '_map' not in self.__dict__:
146146
HTTPServer.__init__(self)
147147

148148
def handle_accept(self):

‎src/network/https.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
class HTTPSClient(HTTPClient, TLSHandshake):
1919
def __init__(self, host, path):
20-
if not hasattr(self, '_map'):
20+
if '_map' not in self.__dict__:
2121
asyncore.dispatcher.__init__(self)
2222
self.tlsDone = False
2323
"""

‎src/network/knownnodes.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ def saveKnownNodes(dirName=None):
9797
if dirName is None:
9898
dirName = state.appdata
9999
with knownNodesLock:
100-
with open(os.path.join(dirName, 'knownnodes.dat'), 'wb') as output:
100+
with open(os.path.join(dirName, 'knownnodes.dat'), 'w') as output:
101101
json_serialize_knownnodes(output)
102102

103103

‎src/network/tcp.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -390,7 +390,7 @@ class TCPServer(AdvancedDispatcher):
390390
"""TCP connection server for Bitmessage protocol"""
391391

392392
def __init__(self, host='127.0.0.1', port=8444):
393-
if not hasattr(self, '_map'):
393+
if '_map' not in self.__dict__:
394394
AdvancedDispatcher.__init__(self)
395395
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
396396
self.set_reuse_addr()

‎src/network/tls.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
# ciphers
3535
if (
3636
ssl.OPENSSL_VERSION_NUMBER >= 0x10100000
37-
and not ssl.OPENSSL_VERSION.startswith(b"LibreSSL")
37+
and not ssl.OPENSSL_VERSION.startswith("LibreSSL")
3838
):
3939
sslProtocolCiphers = "AECDH-AES256-SHA@SECLEVEL=0"
4040
else:

‎src/network/udp.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ def bm_command_addr(self):
8080
return True
8181
remoteport = False
8282
for seenTime, stream, _, ip, port in addresses:
83-
decodedIP = protocol.checkIPAddress(str(ip))
83+
decodedIP = protocol.checkIPAddress(bytes(ip))
8484
if stream not in self.pool.streams:
8585
continue
8686
if (seenTime < time.time() - protocol.MAX_TIME_OFFSET

0 commit comments

Comments
 (0)