Skip to content

Commit 287abf1

Browse files
committed
Replaced string with bytes literal, refactored & formatted the code
few changes added tearDown() & fixed code quality fixed import errors & code quality formatted, refactored & cleaned code fixed code quality fixed Pylint E401 fixed imports merged glitch's changes added tests for protocol refactored test_networkgroup reverted import changes fixed code quality removed test_networkgroup module & fixed code quality
1 parent e1e2337 commit 287abf1

File tree

3 files changed

+104
-71
lines changed

3 files changed

+104
-71
lines changed

src/protocol.py

Lines changed: 27 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -91,16 +91,16 @@ def isBitSetWithinBitfield(fourByteString, n):
9191
return x & 2**n != 0
9292

9393

94-
# ip addresses
94+
# IP addresses
9595

9696

9797
def encodeHost(host):
9898
"""Encode a given host to be used in low-level socket operations"""
9999
if host.find('.onion') > -1:
100-
return '\xfd\x87\xd8\x7e\xeb\x43' + base64.b32decode(
100+
return b'\xfd\x87\xd8\x7e\xeb\x43' + base64.b32decode(
101101
host.split(".")[0], True)
102102
elif host.find(':') == -1:
103-
return '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
103+
return b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + \
104104
socket.inet_aton(host)
105105
return socket.inet_pton(socket.AF_INET6, host)
106106

@@ -147,10 +147,10 @@ def checkIPAddress(host, private=False):
147147
Returns hostStandardFormat if it is a valid IP address,
148148
otherwise returns False
149149
"""
150-
if host[0:12] == '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
150+
if host[0:12] == b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF':
151151
hostStandardFormat = socket.inet_ntop(socket.AF_INET, host[12:])
152152
return checkIPv4Address(host[12:], hostStandardFormat, private)
153-
elif host[0:6] == '\xfd\x87\xd8\x7e\xeb\x43':
153+
elif host[0:6] == b'\xfd\x87\xd8\x7e\xeb\x43':
154154
# Onion, based on BMD/bitcoind
155155
hostStandardFormat = base64.b32encode(host[6:]).lower() + ".onion"
156156
if private:
@@ -161,7 +161,7 @@ def checkIPAddress(host, private=False):
161161
hostStandardFormat = socket.inet_ntop(socket.AF_INET6, host)
162162
except ValueError:
163163
return False
164-
if hostStandardFormat == "":
164+
if hostStandardFormat:
165165
# This can happen on Windows systems which are
166166
# not 64-bit compatible so let us drop the IPv6 address.
167167
return False
@@ -173,23 +173,23 @@ def checkIPv4Address(host, hostStandardFormat, private=False):
173173
Returns hostStandardFormat if it is an IPv4 address,
174174
otherwise returns False
175175
"""
176-
if host[0] == '\x7F': # 127/8
176+
if host[0:1] == b'\x7F': # 127/8
177177
if not private:
178178
logger.debug(
179179
'Ignoring IP address in loopback range: %s',
180180
hostStandardFormat)
181181
return hostStandardFormat if private else False
182-
if host[0] == '\x0A': # 10/8
182+
if host[0:1] == b'\x0A': # 10/8
183183
if not private:
184184
logger.debug(
185185
'Ignoring IP address in private range: %s', hostStandardFormat)
186186
return hostStandardFormat if private else False
187-
if host[0:2] == '\xC0\xA8': # 192.168/16
187+
if host[0:2] == b'\xC0\xA8': # 192.168/16
188188
if not private:
189189
logger.debug(
190190
'Ignoring IP address in private range: %s', hostStandardFormat)
191191
return hostStandardFormat if private else False
192-
if host[0:2] >= '\xAC\x10' and host[0:2] < '\xAC\x20': # 172.16/12
192+
if host[0:2] >= b'\xAC\x10' and host[0:2] < b'\xAC\x20': # 172.16/12
193193
if not private:
194194
logger.debug(
195195
'Ignoring IP address in private range: %s', hostStandardFormat)
@@ -202,15 +202,19 @@ def checkIPv6Address(host, hostStandardFormat, private=False):
202202
Returns hostStandardFormat if it is an IPv6 address,
203203
otherwise returns False
204204
"""
205-
if host == ('\x00' * 15) + '\x01':
205+
if host == b'\x00' * 15 + b'\x01':
206206
if not private:
207207
logger.debug('Ignoring loopback address: %s', hostStandardFormat)
208208
return False
209-
if host[0] == '\xFE' and (ord(host[1]) & 0xc0) == 0x80:
209+
try:
210+
host = [ord(c) for c in host[:2]]
211+
except TypeError: # python3 has ints already
212+
pass
213+
if host[0:1] == b'\xFE' and host[1] & 0xc0 == 0x80:
210214
if not private:
211215
logger.debug('Ignoring local address: %s', hostStandardFormat)
212216
return hostStandardFormat if private else False
213-
if (ord(host[0]) & 0xfe) == 0xfc:
217+
if host[0] & 0xfe == 0xfc:
214218
if not private:
215219
logger.debug(
216220
'Ignoring unique local address: %s', hostStandardFormat)
@@ -280,7 +284,7 @@ def isProofOfWorkSufficient(
280284
# Packet creation
281285

282286

283-
def CreatePacket(command, payload=''):
287+
def CreatePacket(command, payload=b''):
284288
"""Construct and return a packet"""
285289
payload_length = len(payload)
286290
checksum = hashlib.sha512(payload).digest()[0:4]
@@ -298,14 +302,14 @@ def assembleVersionMessage(
298302
Construct the payload of a version message,
299303
return the resulting bytes of running `CreatePacket` on it
300304
"""
301-
payload = ''
305+
payload = b''
302306
payload += pack('>L', 3) # protocol version.
303307
# bitflags of the services I offer.
304308
payload += pack(
305309
'>q',
306-
NODE_NETWORK |
307-
(NODE_SSL if haveSSL(server) else 0) |
308-
(NODE_DANDELION if state.dandelion else 0)
310+
NODE_NETWORK
311+
| (NODE_SSL if haveSSL(server) else 0)
312+
| (NODE_DANDELION if state.dandelion else 0)
309313
)
310314
payload += pack('>q', int(time.time()))
311315

@@ -327,13 +331,13 @@ def assembleVersionMessage(
327331
# bitflags of the services I offer.
328332
payload += pack(
329333
'>q',
330-
NODE_NETWORK |
331-
(NODE_SSL if haveSSL(server) else 0) |
332-
(NODE_DANDELION if state.dandelion else 0)
334+
NODE_NETWORK
335+
| (NODE_SSL if haveSSL(server) else 0)
336+
| (NODE_DANDELION if state.dandelion else 0)
333337
)
334338
# = 127.0.0.1. This will be ignored by the remote host.
335339
# The actual remote connected IP will be used.
336-
payload += '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack(
340+
payload += b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF' + pack(
337341
'>L', 2130706433)
338342
# we have a separate extPort and incoming over clearnet
339343
# or outgoing through clearnet
@@ -355,7 +359,7 @@ def assembleVersionMessage(
355359
payload += nodeid[0:8]
356360
else:
357361
payload += eightBytesOfRandomDataUsedToDetectConnectionsToSelf
358-
userAgent = '/PyBitmessage:' + softwareVersion + '/'
362+
userAgent = ('/PyBitmessage:%s/' % softwareVersion).encode('utf-8')
359363
payload += encodeVarint(len(userAgent))
360364
payload += userAgent
361365

src/tests/test_networkgroup.py

Lines changed: 0 additions & 43 deletions
This file was deleted.

src/tests/test_protocol.py

Lines changed: 77 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,25 +2,97 @@
22
Tests for common protocol functions
33
"""
44

5+
import sys
56
import unittest
67

7-
from .common import skip_python3
8-
9-
skip_python3()
8+
from pybitmessage import protocol, state
109

1110

1211
class TestProtocol(unittest.TestCase):
1312
"""Main protocol test case"""
1413

14+
def test_checkIPv4Address(self):
15+
"""Check the results of protocol.checkIPv4Address()"""
16+
token = 'HELLO'
17+
# checking protocol.encodeHost()[12:]
18+
self.assertEqual( # 127.0.0.1
19+
token, protocol.checkIPv4Address(b'\x7f\x00\x00\x01', token, True))
20+
self.assertEqual( # 10.42.43.1
21+
token, protocol.checkIPv4Address(b'\n*+\x01', token, True))
22+
self.assertEqual( # 192.168.0.254
23+
token, protocol.checkIPv4Address(b'\xc0\xa8\x00\xfe', token, True))
24+
self.assertEqual( # 172.31.255.254
25+
token, protocol.checkIPv4Address(b'\xac\x1f\xff\xfe', token, True))
26+
self.assertFalse( # 8.8.8.8
27+
protocol.checkIPv4Address(b'\x08\x08\x08\x08', token, True))
28+
29+
def test_checkIPv6Address(self):
30+
"""Check the results of protocol.checkIPv6Address()"""
31+
test_ip = '2001:db8::ff00:42:8329'
32+
self.assertEqual(
33+
'test', protocol.checkIPv6Address(
34+
protocol.encodeHost(test_ip), 'test'))
35+
self.assertFalse(
36+
protocol.checkIPv6Address(
37+
protocol.encodeHost(test_ip), 'test', True))
38+
1539
def test_check_local(self):
1640
"""Check the logic of TCPConnection.local"""
17-
from pybitmessage import protocol, state
18-
1941
self.assertTrue(
2042
protocol.checkIPAddress(protocol.encodeHost('127.0.0.1'), True))
2143
self.assertTrue(
2244
protocol.checkIPAddress(protocol.encodeHost('192.168.0.1'), True))
45+
self.assertTrue(
46+
protocol.checkIPAddress(protocol.encodeHost('10.42.43.1'), True))
47+
self.assertTrue(
48+
protocol.checkIPAddress(protocol.encodeHost('172.31.255.2'), True))
49+
self.assertFalse(protocol.checkIPAddress(
50+
protocol.encodeHost('2001:db8::ff00:42:8329'), True))
2351

52+
globalhost = protocol.encodeHost('8.8.8.8')
53+
self.assertFalse(protocol.checkIPAddress(globalhost, True))
54+
self.assertEqual(protocol.checkIPAddress(globalhost), '8.8.8.8')
55+
56+
@unittest.skipIf(
57+
sys.hexversion >= 0x3000000, 'this is still not working with python3')
58+
def test_check_local_socks(self):
59+
"""The SOCKS part of the local check"""
2460
self.assertTrue(
2561
not protocol.checkSocksIP('127.0.0.1')
2662
or state.socksIP)
63+
64+
def test_network_group(self):
65+
"""Test various types of network groups"""
66+
67+
test_ip = '1.2.3.4'
68+
self.assertEqual(b'\x01\x02', protocol.network_group(test_ip))
69+
70+
test_ip = '127.0.0.1'
71+
self.assertEqual('IPv4', protocol.network_group(test_ip))
72+
73+
self.assertEqual(
74+
protocol.network_group('8.8.8.8'),
75+
protocol.network_group('8.8.4.4'))
76+
self.assertNotEqual(
77+
protocol.network_group('1.1.1.1'),
78+
protocol.network_group('8.8.8.8'))
79+
80+
test_ip = '0102:0304:0506:0708:090A:0B0C:0D0E:0F10'
81+
self.assertEqual(
82+
b'\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0A\x0B\x0C',
83+
protocol.network_group(test_ip))
84+
85+
test_ip = 'bootstrap8444.bitmessage.org'
86+
self.assertEqual(
87+
'bootstrap8444.bitmessage.org',
88+
protocol.network_group(test_ip))
89+
90+
test_ip = 'quzwelsuziwqgpt2.onion'
91+
self.assertEqual(
92+
test_ip,
93+
protocol.network_group(test_ip))
94+
95+
test_ip = None
96+
self.assertEqual(
97+
None,
98+
protocol.network_group(test_ip))

0 commit comments

Comments
 (0)