From 011500e76e5336a40efc2a4a608e572ee9eabdd0 Mon Sep 17 00:00:00 2001 From: Peter Surda Date: Mon, 27 Apr 2026 08:46:40 +0800 Subject: [PATCH] Code quality --- src/api.py | 49 ++++++++++---------- src/bitmessagemain.py | 1 + src/bitmessageqt/settings.py | 74 +++++++++++++++--------------- src/bmconfigparser.py | 2 +- src/class_addressGenerator.py | 10 ++-- src/class_singleWorker.py | 12 ++--- src/helper_search.py | 16 +++---- src/main-android-live.py | 1 + src/network/asyncore_pollchoose.py | 4 +- src/qidenticon.py | 6 +-- tox.ini | 2 +- 11 files changed, 91 insertions(+), 86 deletions(-) diff --git a/src/api.py b/src/api.py index 7826e6295..fa4b817de 100644 --- a/src/api.py +++ b/src/api.py @@ -57,6 +57,8 @@ For further examples please reference `.tests.test_api`. """ +# pylint: disable=too-many-lines,relative-import + import base64 import errno import hashlib @@ -112,25 +114,25 @@ class ErrorCodes(type): 0: 'Invalid command parameters number', 1: 'The specified passphrase is blank.', 2: 'The address version number currently must be 3, 4, or 0' - ' (which means auto-select).', + ' (which means auto-select).', 3: 'The stream number must be 1 (or 0 which means' - ' auto-select). Others aren\'t supported.', + ' auto-select). Others aren\'t supported.', 4: 'Why would you ask me to generate 0 addresses for you?', 5: 'You have (accidentally?) specified too many addresses to' - ' make. Maximum 999. This check only exists to prevent' - ' mischief; if you really want to create more addresses than' - ' this, contact the Bitmessage developers and we can modify' - ' the check or you can do it yourself by searching the source' - ' code for this message.', + ' make. Maximum 999. This check only exists to prevent' + ' mischief; if you really want to create more addresses than' + ' this, contact the Bitmessage developers and we can modify' + ' the check or you can do it yourself by searching the source' + ' code for this message.', 6: 'The encoding type must be 2 or 3.', 7: 'Could not decode address', 8: 'Checksum failed for address', 9: 'Invalid characters in address', 10: 'Address version number too high (or zero)', 11: 'The address version number currently must be 2, 3 or 4.' - ' Others aren\'t supported. Check the address.', + ' Others aren\'t supported. Check the address.', 12: 'The stream number must be 1. Others aren\'t supported.' - ' Check the address.', + ' Check the address.', 13: 'Could not find this address in your keys.dat file.', 14: 'Your fromAddress is disabled. Cannot send.', 15: 'Invalid ackData object size.', @@ -138,14 +140,14 @@ class ErrorCodes(type): 17: 'Label is not valid UTF-8 data.', 18: 'Chan name does not match address.', 19: 'The length of hash should be 32 bytes (encoded in hex' - ' thus 64 characters).', + ' thus 64 characters).', 20: 'Invalid method:', 21: 'Unexpected API Failure', 22: 'Decode error', 23: 'Bool expected in eighteenByteRipe', 24: 'Chan address is already present.', 25: 'Specified address is not a chan address.' - ' Use deleteAddress API call instead.', + ' Use deleteAddress API call instead.', 26: 'Malformed varint in address: ', 27: 'Message is too long.', 28: 'Invalid parameter' @@ -153,7 +155,7 @@ class ErrorCodes(type): def __new__(mcs, name, bases, namespace): result = super(ErrorCodes, mcs).__new__(mcs, name, bases, namespace) - for code in six.iteritems(mcs._CODES): + for code in six.iteritems(mcs._CODES): # pylint: disable=no-member # beware: the formatting is adjusted for list-table result.__doc__ += """ * - %04i - %s @@ -466,6 +468,7 @@ def APIAuthenticateClient(self): class BMRPCDispatcher(object): """This class is used to dispatch API commands""" + # pylint: disable=inconsistent-return-statements @staticmethod def _decode(text, decode_type): try: @@ -722,8 +725,8 @@ def HandleDeleteWhitelistEntry(self, address): @command('createRandomAddress') def HandleCreateRandomAddress( - self, label, eighteenByteRipe=False, totalDifficulty=0, - smallMessageDifficulty=0 + self, label, eighteenByteRipe=False, totalDifficulty=0, + smallMessageDifficulty=0 ): """ Create one address using the random number generator. @@ -763,9 +766,9 @@ def HandleCreateRandomAddress( @command('createDeterministicAddresses') def HandleCreateDeterministicAddresses( - self, passphrase, numberOfAddresses=1, addressVersionNumber=0, - streamNumber=0, eighteenByteRipe=False, totalDifficulty=0, - smallMessageDifficulty=0 + self, passphrase, numberOfAddresses=1, addressVersionNumber=0, + streamNumber=0, eighteenByteRipe=False, totalDifficulty=0, + smallMessageDifficulty=0 ): """ Create many addresses deterministically using the passphrase. @@ -1190,8 +1193,8 @@ def HandleTrashSentMessage(self, msgid): @command('sendMessage') def HandleSendMessage( - self, toAddress, fromAddress, subject, message, - encodingType=2, TTL=4 * 24 * 60 * 60 + self, toAddress, fromAddress, subject, message, + encodingType=2, TTL=4 * 24 * 60 * 60 ): """ Send the message and return ackdata (hex encoded string). @@ -1242,7 +1245,7 @@ def HandleSendMessage( @command('sendBroadcast') def HandleSendBroadcast( - self, fromAddress, subject, message, encodingType=2, + self, fromAddress, subject, message, encodingType=2, TTL=4 * 24 * 60 * 60): """Send the broadcast message. Similiar to *sendMessage*.""" @@ -1361,9 +1364,9 @@ def ListSubscriptions(self): @command('disseminatePreEncryptedMsg', 'disseminatePreparedObject') def HandleDisseminatePreparedObject( - self, encryptedPayload, - nonceTrialsPerByte=networkDefaultProofOfWorkNonceTrialsPerByte, - payloadLengthExtraBytes=networkDefaultPayloadLengthExtraBytes + self, encryptedPayload, + nonceTrialsPerByte=networkDefaultProofOfWorkNonceTrialsPerByte, + payloadLengthExtraBytes=networkDefaultPayloadLengthExtraBytes ): """ Handle a request to disseminate an encrypted message. diff --git a/src/bitmessagemain.py b/src/bitmessagemain.py index 0402e841f..1fbd9cf5f 100755 --- a/src/bitmessagemain.py +++ b/src/bitmessagemain.py @@ -11,6 +11,7 @@ # yet contain logic to expand into further streams. # flake8: noqa:402 +# pylint: disable=superfluous-parens import os import sys diff --git a/src/bitmessageqt/settings.py b/src/bitmessageqt/settings.py index 2d3af319f..0f778703e 100644 --- a/src/bitmessageqt/settings.py +++ b/src/bitmessageqt/settings.py @@ -176,12 +176,12 @@ def adjust_from_config(self, config): if self._proxy_type: for node, info in six.iteritems( - knownnodes.knownNodes.get( + knownnodes.knownNodes.get( min(connectionpool.pool.streams), []) ): if ( - node.host.endswith('.onion') and len(node.host) > 22 - and not info.get('self') + node.host.endswith('.onion') and len(node.host) > 22 + and not info.get('self') ): break else: @@ -346,9 +346,10 @@ def choose_font(self): if valid: self.save_font_setting(font) + # pylint: disable=too-many-branches,too-many-statements + # pylint: disable=too-many-locals def accept(self): """A callback for accepted event of buttonBox (OK button pressed)""" - # pylint: disable=too-many-branches,too-many-statements super(SettingsDialog, self).accept() if self.firstrun: self.config.remove_option('bitmessagesettings', 'dontconnect') @@ -374,7 +375,7 @@ def accept(self): window_style = str(self.comboBoxStyle.currentText()) if self.app.get_windowstyle() != window_style or self.config.safeGet( - 'bitmessagesettings', 'font' + 'bitmessagesettings', 'font' ) != self.font_setting: self.config.set('bitmessagesettings', 'windowstyle', window_style) self.config.set('bitmessagesettings', 'font', self.font_setting) @@ -455,8 +456,8 @@ def accept(self): self.config.set('bitmessagesettings', 'sockslisten', str( self.checkBoxSocksListen.isChecked())) if ( - self.checkBoxOnionOnly.isChecked() - and not self.config.safeGetBoolean( + self.checkBoxOnionOnly.isChecked() + and not self.config.safeGetBoolean( 'bitmessagesettings', 'onionservicesonly') ): self.net_restart_needed = True @@ -519,40 +520,39 @@ def accept(self): acceptableDifficultyChanged = False - if ( - float(self.lineEditMaxAcceptableTotalDifficulty.text()) >= 1 - or float(self.lineEditMaxAcceptableTotalDifficulty.text()) == 0 - ): + max_total_diff = float( + self.lineEditMaxAcceptableTotalDifficulty.text()) + if max_total_diff >= 1 or max_total_diff == 0: + nonce_trials = str(int( + max_total_diff + * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)) if self.config.get( - 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte' - ) != str(int( - float(self.lineEditMaxAcceptableTotalDifficulty.text()) - * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)): + 'bitmessagesettings', + 'maxacceptablenoncetrialsperbyte' + ) != nonce_trials: # the user changed the max acceptable total difficulty acceptableDifficultyChanged = True self.config.set( - 'bitmessagesettings', 'maxacceptablenoncetrialsperbyte', - str(int( - float(self.lineEditMaxAcceptableTotalDifficulty.text()) - * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)) - ) - if ( - float(self.lineEditMaxAcceptableSmallMessageDifficulty.text()) >= 1 - or float(self.lineEditMaxAcceptableSmallMessageDifficulty.text()) == 0 - ): + 'bitmessagesettings', + 'maxacceptablenoncetrialsperbyte', + nonce_trials) + + max_msg_diff = float( + self.lineEditMaxAcceptableSmallMessageDifficulty.text()) + if max_msg_diff >= 1 or max_msg_diff == 0: + extra_bytes = str(int( + max_msg_diff + * defaults.networkDefaultPayloadLengthExtraBytes)) if self.config.get( - 'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes' - ) != str(int( - float(self.lineEditMaxAcceptableSmallMessageDifficulty.text()) - * defaults.networkDefaultPayloadLengthExtraBytes)): + 'bitmessagesettings', + 'maxacceptablepayloadlengthextrabytes' + ) != extra_bytes: # the user changed the max acceptable small message difficulty acceptableDifficultyChanged = True self.config.set( - 'bitmessagesettings', 'maxacceptablepayloadlengthextrabytes', - str(int( - float(self.lineEditMaxAcceptableSmallMessageDifficulty.text()) - * defaults.networkDefaultPayloadLengthExtraBytes)) - ) + 'bitmessagesettings', + 'maxacceptablepayloadlengthextrabytes', + extra_bytes) if acceptableDifficultyChanged: # It might now be possible to send msgs which were previously # marked as toodifficult. Let us change them to 'msgqueued'. @@ -629,8 +629,8 @@ def accept(self): self.parent.updateStartOnLogon() if ( - state.appdata != paths.lookupExeFolder() - and self.checkBoxPortableMode.isChecked() + state.appdata != paths.lookupExeFolder() + and self.checkBoxPortableMode.isChecked() ): # If we are NOT using portable mode now but the user selected # that we should... @@ -652,8 +652,8 @@ def accept(self): pass if ( - state.appdata == paths.lookupExeFolder() - and not self.checkBoxPortableMode.isChecked() + state.appdata == paths.lookupExeFolder() + and not self.checkBoxPortableMode.isChecked() ): # If we ARE using portable mode now but the user selected # that we shouldn't... diff --git a/src/bmconfigparser.py b/src/bmconfigparser.py index 7d0f07cb3..68fb1e72f 100644 --- a/src/bmconfigparser.py +++ b/src/bmconfigparser.py @@ -128,7 +128,7 @@ def save(self): shutil.copyfile(fileName, fileNameBak) # The backup succeeded. fileNameExisted = True - except(IOError, Exception): + except (IOError, Exception): # The backup failed. This can happen if the file # didn't exist before. fileNameExisted = False diff --git a/src/class_addressGenerator.py b/src/class_addressGenerator.py index 79b76e730..955014cbd 100644 --- a/src/class_addressGenerator.py +++ b/src/class_addressGenerator.py @@ -32,10 +32,10 @@ def stopThread(self): super(addressGenerator, self).stopThread() + # pylint: disable=too-many-arguments,too-many-positional-arguments def save_address( - # pylint: disable=too-many-arguments,too-many-positional-arguments - self, version, stream, ripe, label, signing_key, encryption_key, - nonceTrialsPerByte, payloadLengthExtraBytes + self, version, stream, ripe, label, signing_key, encryption_key, + nonceTrialsPerByte, payloadLengthExtraBytes ): """Write essential address config values and reload cryptors""" address = encodeAddress(version, stream, ripe) @@ -183,8 +183,8 @@ def run(self): ripe = highlevelcrypto.to_ripe( pubSigningKey, potentialPubEncryptionKey) if ( - ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] - == b'\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash + ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] + == b'\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash ): break self.logger.info( diff --git a/src/class_singleWorker.py b/src/class_singleWorker.py index da9d64c6a..e46d9f879 100644 --- a/src/class_singleWorker.py +++ b/src/class_singleWorker.py @@ -221,9 +221,9 @@ def _getKeysForAddress(self, address): @classmethod def _doPOWDefaults( - cls, payload, TTL, - nonceTrialsPerByte=None, payloadLengthExtraBytes=None, - log_prefix='', log_time=False + cls, payload, TTL, + nonceTrialsPerByte=None, payloadLengthExtraBytes=None, + log_prefix='', log_time=False ): if not nonceTrialsPerByte: nonceTrialsPerByte = \ @@ -755,9 +755,9 @@ def sendMsg(self): # in our keys.dat file. elif config.has_section(toaddress): if not sqlExecute( - '''UPDATE sent SET status='doingmsgpow' ''' - ''' WHERE toaddress=? AND status='msgqueued' AND folder='sent' ''', - toaddress + '''UPDATE sent SET status='doingmsgpow' ''' + ''' WHERE toaddress=? AND status='msgqueued' AND folder='sent' ''', + toaddress ): continue status = 'doingmsgpow' diff --git a/src/helper_search.py b/src/helper_search.py index 85a9e9717..0ffdd0107 100644 --- a/src/helper_search.py +++ b/src/helper_search.py @@ -8,8 +8,8 @@ def search_sql( - xAddress='toaddress', account=None, folder='inbox', where=None, - what=None, unreadOnly=False + xAddress='toaddress', account=None, folder='inbox', where=None, + what=None, unreadOnly=False ): """ Search for messages from given account and folder having search term @@ -88,24 +88,24 @@ def check_match( return True if where in ( - _translate("MainWindow", "To"), _translate("MainWindow", "All") + _translate("MainWindow", "To"), _translate("MainWindow", "All") ): if what.lower() not in toAddress.lower(): return False elif where in ( - _translate("MainWindow", "From"), _translate("MainWindow", "All") + _translate("MainWindow", "From"), _translate("MainWindow", "All") ): if what.lower() not in fromAddress.lower(): return False elif where in ( - _translate("MainWindow", "Subject"), - _translate("MainWindow", "All") + _translate("MainWindow", "Subject"), + _translate("MainWindow", "All") ): if what.lower() not in subject.lower(): return False elif where in ( - _translate("MainWindow", "Message"), - _translate("MainWindow", "All") + _translate("MainWindow", "Message"), + _translate("MainWindow", "All") ): if what.lower() not in message.lower(): return False diff --git a/src/main-android-live.py b/src/main-android-live.py index 0ebc996bf..c880280e4 100644 --- a/src/main-android-live.py +++ b/src/main-android-live.py @@ -1,4 +1,5 @@ """This module is for thread start.""" +# pylint: disable=superfluous-parens import state import sys from bitmessagemain import main diff --git a/src/network/asyncore_pollchoose.py b/src/network/asyncore_pollchoose.py index b7d1049b7..2a23bb797 100644 --- a/src/network/asyncore_pollchoose.py +++ b/src/network/asyncore_pollchoose.py @@ -560,12 +560,12 @@ def del_channel(self): try: kqueue_poller.pollster.control([select.kevent( fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE)], 0) - except(AttributeError, KeyError, TypeError, IOError, OSError): + except (AttributeError, KeyError, TypeError, IOError, OSError): pass try: kqueue_poller.pollster.control([select.kevent( fd, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE)], 0) - except(AttributeError, KeyError, TypeError, IOError, OSError): + except (AttributeError, KeyError, TypeError, IOError, OSError): pass try: epoll_poller.pollster.unregister(fd) diff --git a/src/qidenticon.py b/src/qidenticon.py index 13be35780..ef4a46821 100644 --- a/src/qidenticon.py +++ b/src/qidenticon.py @@ -262,9 +262,9 @@ def decode(self, code, twoColor): else: secondColor = foreColor - return (middleType, middleInvert, 0),\ - (cornerType, cornerInvert, cornerTurn),\ - (sideType, sideInvert, sideTurn),\ + return (middleType, middleInvert, 0), \ + (cornerType, cornerInvert, cornerTurn), \ + (sideType, sideInvert, sideTurn), \ foreColor, secondColor, swap_cross diff --git a/tox.ini b/tox.ini index 9cd8c412b..2df0a9d5c 100644 --- a/tox.ini +++ b/tox.ini @@ -66,7 +66,7 @@ basepython = python3 deps = pycodestyle commands = - - pycodestyle --config=tox.ini pybitmessage + pycodestyle --config=tox.ini pybitmessage [testenv:bandit-py27] skip_install = true