Skip to content

Commit 9d7875f

Browse files
committed
Code quality
1 parent f6f5273 commit 9d7875f

13 files changed

Lines changed: 115 additions & 73 deletions

setup.cfg

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,18 +15,35 @@ ignore = E722,F841,W503
1515
# F841: pylint is preferred for unused-variable
1616
# W503: deprecated: https://bugs.python.org/issue26763 - https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator
1717

18-
# pylint honours the [MESSAGES CONTROL] section
19-
# as well as [MASTER] section
20-
[MESSAGES CONTROL]
21-
disable=
18+
# -- pylint (modern, >= 2.14) -- pylint.*-prefixed sections for setup.cfg
19+
20+
[pylint.main]
21+
init-hook = import sys;sys.path.append('src')
22+
ignore = bitmessagekivy
23+
24+
[pylint.messages_control]
25+
disable =
2226
invalid-name,bare-except,broad-except,superfluous-parens,
2327
bad-option-value
2428
# invalid-name: needs fixing during a large, project-wide refactor
2529
# bare-except,broad-except: Need fixing once thorough testing is easier
2630
# bad-option-value is for backward compatibility between python 2 and 3
31+
32+
[pylint.design]
2733
max-args = 8
2834
max-attributes = 8
2935

36+
# -- pylint (legacy, < 2.0 / python 2.7) -- old .pylintrc-style section names
37+
3038
[MASTER]
3139
init-hook = import sys;sys.path.append('src')
3240
ignore = bitmessagekivy
41+
42+
[MESSAGES CONTROL]
43+
disable =
44+
invalid-name,bare-except,broad-except,superfluous-parens,
45+
bad-option-value
46+
47+
[DESIGN]
48+
max-args = 8
49+
max-attributes = 8

src/bitmessagecli.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
# -*- coding: utf-8 -*-
33
# pylint: disable=too-many-lines,global-statement,too-many-branches,too-many-statements,inconsistent-return-statements
44
# pylint: disable=too-many-nested-blocks,too-many-locals,protected-access,too-many-arguments,too-many-function-args
5-
# pylint: disable=no-member
5+
# pylint: disable=no-member,superfluous-parens
66
"""
77
Created by Adam Melton (.dok) referenceing https://bitmessage.org/wiki/API_Reference for API documentation
88
Distributed under the MIT/X11 software license. See http://www.opensource.org/licenses/mit-license.php.
@@ -16,15 +16,14 @@
1616
import datetime
1717
import imghdr
1818
import json
19-
import ntpath
2019
import os
2120
import socket
2221
import sys
2322
import time
24-
2523
from six.moves import input as raw_input
2624
from six.moves import xmlrpc_client as xmlrpclib
2725

26+
import ntpath
2827
from bmconfigparser import config
2928

3029

src/bitmessagemain.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -256,8 +256,8 @@ def start(self):
256256
while state.shutdown == 0:
257257
time.sleep(1)
258258
if (
259-
state.testmode
260-
and time.time() - state.last_api_response >= 30
259+
state.testmode
260+
and time.time() - state.last_api_response >= 30
261261
):
262262
self.stop()
263263
elif not state.enableGUI:

src/class_addressGenerator.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -221,8 +221,8 @@ def run(self):
221221
))
222222

223223
elif command in (
224-
'createDeterministicAddresses', 'createChan',
225-
'getDeterministicAddress', 'joinChan'
224+
'createDeterministicAddresses', 'createChan',
225+
'getDeterministicAddress', 'joinChan'
226226
):
227227
if not deterministicPassphrase:
228228
self.logger.warning(
@@ -268,8 +268,8 @@ def run(self):
268268
ripe = highlevelcrypto.to_ripe(
269269
potentialPubSigningKey, potentialPubEncryptionKey)
270270
if (
271-
ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash]
272-
== b'\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash
271+
ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash]
272+
== b'\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash
273273
):
274274
break
275275

@@ -303,9 +303,9 @@ def run(self):
303303
saveAddressToDisk = False
304304

305305
if saveAddressToDisk and live and self.save_address(
306-
addressVersionNumber, streamNumber, ripe, label,
307-
potentialPrivSigningKey, potentialPrivEncryptionKey,
308-
nonceTrialsPerByte, payloadLengthExtraBytes
306+
addressVersionNumber, streamNumber, ripe, label,
307+
potentialPrivSigningKey, potentialPrivEncryptionKey,
308+
nonceTrialsPerByte, payloadLengthExtraBytes
309309
):
310310
if command in ('createChan', 'joinChan'):
311311
config.set(address, 'chan', 'true')
@@ -326,7 +326,7 @@ def run(self):
326326

327327
# Done generating addresses.
328328
if command in (
329-
'createDeterministicAddresses', 'createChan', 'joinChan'
329+
'createDeterministicAddresses', 'createChan', 'joinChan'
330330
):
331331
queues.apiAddressGeneratorReturnQueue.put(
332332
listOfNewAddressesToSendOutThroughTheAPI)

src/class_objectProcessor.py

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
"""
55
# pylint: disable=too-many-locals,too-many-return-statements
66
# pylint: disable=too-many-branches,too-many-statements
7+
# pylint: disable=too-many-lines
78
import hashlib
89
import logging
910
import os
@@ -718,10 +719,10 @@ def processmsg(self, data):
718719
# Don't send ACK if invalid, blacklisted senders, invisible
719720
# messages, disabled or chan
720721
if (
721-
self.ackDataHasAValidHeader(ackData) and not blockMessage
722-
and messageEncodingType != 0
723-
and not config.safeGetBoolean(toAddress, 'dontsendack')
724-
and not config.safeGetBoolean(toAddress, 'chan')
722+
self.ackDataHasAValidHeader(ackData) and not blockMessage
723+
and messageEncodingType != 0
724+
and not config.safeGetBoolean(toAddress, 'dontsendack')
725+
and not config.safeGetBoolean(toAddress, 'chan')
725726
):
726727
ackPayload = ackData[24:]
727728
objectType, toStreamNumber, expiresTime = \

src/class_singleWorker.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -772,9 +772,9 @@ def sendMsg(self):
772772
if queryreturn != []:
773773
# set the status of this msg to doingmsgpow
774774
if not sqlExecute(
775-
'''UPDATE sent SET status='doingmsgpow' '''
776-
''' WHERE toaddress=? AND status='msgqueued' AND folder='sent' ''',
777-
toaddress
775+
'''UPDATE sent SET status='doingmsgpow' '''
776+
''' WHERE toaddress=? AND status='msgqueued' AND folder='sent' ''',
777+
toaddress
778778
):
779779
continue
780780
status = 'doingmsgpow'

src/helper_sent.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -44,8 +44,7 @@ def insert(msgid=None, toAddress='[Broadcast subscribers]', fromAddress=None, su
4444

4545
sqlExecute('''INSERT INTO sent VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)''', *t)
4646
return ackdata
47-
else:
48-
return None
47+
return None
4948

5049

5150
def delete(ack_data):

src/main.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,13 @@
44
"""Mock kivy app with mock threads."""
55

66
import os
7-
from kivy.config import Config
8-
from mockbm import multiqueue
9-
import state
7+
from kivy.config import Config # pylint: disable=import-error
108

11-
from mockbm.class_addressGenerator import FakeAddressGenerator # noqa:E402
12-
from bitmessagekivy.mpybit import NavigateApp # noqa:E402
13-
from mockbm import network # noqa:E402
9+
import pybitmessage.state as state
10+
from pybitmessage.bitmessagekivy.mpybit import NavigateApp # noqa:E402
11+
from pybitmessage.mockbm import multiqueue
12+
from pybitmessage.mockbm.class_addressGenerator import FakeAddressGenerator # noqa:E402
13+
from pybitmessage.mockbm import network # noqa:E402
1414

1515
stats = network.stats
1616
objectracker = network.objectracker

src/pathmagic.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
"""
2+
Hack to work around relative imports
3+
"""
14
import os
25
import sys
36

src/proofofwork.py

Lines changed: 36 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
"""
22
Proof of work calculation
33
"""
4-
# pylint: disable=import-outside-toplevel
4+
# pylint: disable=import-outside-toplevel,relative-import
55

66
import ctypes
77
import hashlib
@@ -25,8 +25,8 @@
2525
from tr import _translate
2626

2727

28-
bitmsglib = 'bitmsghash.so'
29-
bmpow = None
28+
BITMSGLIB = 'bitmsghash.so'
29+
BMPOW = None
3030

3131

3232
class LogOutput(object): # pylint: disable=too-few-public-methods
@@ -173,7 +173,7 @@ def _doCPoW(target, initialHash):
173173
out_h = ctypes.pointer(ctypes.create_string_buffer(h, 64))
174174
out_m = ctypes.c_ulonglong(m)
175175
logger.debug('C PoW start')
176-
nonce = bmpow(out_h, out_m)
176+
nonce = BMPOW(out_h, out_m)
177177

178178
trialValue = trial_value(nonce, initialHash)
179179
if state.shutdown != 0:
@@ -200,7 +200,7 @@ def _doGPUPoW(target, initialHash):
200200
'Your GPUs (%s) did not calculate correctly, disabling OpenCL.'
201201
' Please report to the developers.', deviceNames)
202202
openclpow.enabledGpus = []
203-
raise Exception("GPU did not calculate correctly.")
203+
raise RuntimeError("GPU did not calculate correctly.")
204204
if state.shutdown != 0:
205205
raise StopIteration("Interrupted")
206206
logger.debug('GPU PoW done')
@@ -240,7 +240,7 @@ def getPowType():
240240

241241
if openclpow.openclEnabled():
242242
return "OpenCL"
243-
if bmpow:
243+
if BMPOW:
244244
return "C"
245245
return "python"
246246

@@ -250,7 +250,7 @@ def notifyBuild(tried=False):
250250
Notify the user of the success or otherwise of building the PoW C module
251251
"""
252252

253-
if bmpow:
253+
if BMPOW:
254254
queues.UISignalQueue.put(('updateStatusBar', (_translate(
255255
"proofofwork", "C PoW module built successfully."), 1)))
256256
elif tried:
@@ -264,7 +264,7 @@ def notifyBuild(tried=False):
264264

265265
def buildCPoW():
266266
"""Attempt to build the PoW C module"""
267-
if bmpow is not None:
267+
if BMPOW is not None:
268268
return
269269
if paths.frozen or sys.platform.startswith('win'):
270270
notifyBuild(False)
@@ -279,7 +279,9 @@ def buildCPoW():
279279

280280
subprocess.check_call(make_cmd) # nosec B603
281281
if os.path.exists(
282-
os.path.join(paths.codePath(), 'bitmsghash', 'bitmsghash.so')
282+
os.path.join(paths.codePath(),
283+
'bitmsghash',
284+
'bitmsghash.so')
283285
):
284286
init()
285287
except (OSError, subprocess.CalledProcessError):
@@ -299,7 +301,7 @@ def run(target, initialHash):
299301
target = int(target)
300302
if openclpow.openclEnabled():
301303
return _doGPUPoW(target, initialHash)
302-
if bmpow:
304+
if BMPOW:
303305
return _doCPoW(target, initialHash)
304306
if paths.frozen == "macosx_app" or not paths.frozen:
305307
# on my (Peter Surda) Windows 10, Windows Defender
@@ -323,14 +325,14 @@ def getTarget(payloadLength, ttl, nonceTrialsPerByte, payloadLengthExtraBytes):
323325

324326

325327
def calculate(
326-
payload, ttl,
327-
nonceTrialsPerByte=networkDefaultProofOfWorkNonceTrialsPerByte,
328-
payloadLengthExtraBytes=networkDefaultPayloadLengthExtraBytes
328+
payload, ttl,
329+
nonceTrialsPerByte=networkDefaultProofOfWorkNonceTrialsPerByte,
330+
payloadLengthExtraBytes=networkDefaultPayloadLengthExtraBytes
329331
):
330332
"""Do the PoW for the payload and TTL with optional difficulty params"""
331-
return run(getTarget(
332-
len(payload), ttl, nonceTrialsPerByte, payloadLengthExtraBytes),
333-
hashlib.sha512(payload).digest())
333+
return run(getTarget(len(payload),ttl, nonceTrialsPerByte,
334+
payloadLengthExtraBytes),
335+
hashlib.sha512(payload).digest())
334336

335337

336338
def resetPoW():
@@ -344,42 +346,42 @@ def resetPoW():
344346
def init():
345347
"""Initialise PoW"""
346348
# pylint: disable=broad-exception-caught,global-statement
347-
global bitmsglib, bmpow
349+
global BITMSGLIB, BMPOW
348350

349351
openclpow.initCL()
350352
if sys.platform.startswith('win'):
351-
bitmsglib = (
353+
BITMSGLIB = (
352354
'bitmsghash32.dll' if ctypes.sizeof(ctypes.c_voidp) == 4 else
353355
'bitmsghash64.dll')
354-
libfile = os.path.join(paths.codePath(), 'bitmsghash', bitmsglib)
356+
libfile = os.path.join(paths.codePath(), 'bitmsghash', BITMSGLIB)
355357
try:
356358
# MSVS
357359
bso = ctypes.WinDLL(
358-
os.path.join(paths.codePath(), 'bitmsghash', bitmsglib))
359-
logger.info('Loaded C PoW DLL (stdcall) %s', bitmsglib)
360-
bmpow = bso.BitmessagePOW
361-
bmpow.restype = ctypes.c_ulonglong
360+
os.path.join(paths.codePath(), 'bitmsghash', BITMSGLIB))
361+
logger.info('Loaded C PoW DLL (stdcall) %s', BITMSGLIB)
362+
BMPOW = bso.BitmessagePOW
363+
BMPOW.restype = ctypes.c_ulonglong
362364
_doCPoW(2**63, "")
363365
logger.info(
364-
'Successfully tested C PoW DLL (stdcall) %s', bitmsglib)
366+
'Successfully tested C PoW DLL (stdcall) %s', BITMSGLIB)
365367
except ValueError:
366368
try:
367369
# MinGW
368370
bso = ctypes.CDLL(libfile)
369-
logger.info('Loaded C PoW DLL (cdecl) %s', bitmsglib)
370-
bmpow = bso.BitmessagePOW
371-
bmpow.restype = ctypes.c_ulonglong
371+
logger.info('Loaded C PoW DLL (cdecl) %s', BITMSGLIB)
372+
BMPOW = bso.BitmessagePOW
373+
BMPOW.restype = ctypes.c_ulonglong
372374
_doCPoW(2**63, "")
373375
logger.info(
374-
'Successfully tested C PoW DLL (cdecl) %s', bitmsglib)
376+
'Successfully tested C PoW DLL (cdecl) %s', BITMSGLIB)
375377
except Exception as e:
376378
logger.error('Error: %s', e, exc_info=True)
377379
except Exception as e:
378380
logger.error('Error: %s', e, exc_info=True)
379381
else:
380382
try:
381383
bso = ctypes.CDLL(
382-
os.path.join(paths.codePath(), 'bitmsghash', bitmsglib))
384+
os.path.join(paths.codePath(), 'bitmsghash', BITMSGLIB))
383385
except OSError:
384386
import glob
385387
try:
@@ -391,15 +393,15 @@ def init():
391393
except Exception:
392394
bso = None
393395
else:
394-
logger.info('Loaded C PoW DLL %s', bitmsglib)
396+
logger.info('Loaded C PoW DLL %s', BITMSGLIB)
395397
if bso:
396398
try:
397-
bmpow = bso.BitmessagePOW
398-
bmpow.restype = ctypes.c_ulonglong
399+
BMPOW = bso.BitmessagePOW
400+
BMPOW.restype = ctypes.c_ulonglong
399401
except Exception:
400402
logger.warning(
401-
'Failed to setup bmpow lib %s', bso, exc_info=True)
403+
'Failed to setup BMPOW lib %s', bso, exc_info=True)
402404
return
403405

404-
if bmpow is None:
406+
if BMPOW is None:
405407
buildCPoW()

0 commit comments

Comments
 (0)