run autopep8 on src

This commit is contained in:
Kashiko Koibumi 2024-05-17 01:53:27 +09:00
parent 1b3ce71f19
commit 24b83aae2a
No known key found for this signature in database
GPG Key ID: 8F06E069E37C40C4
27 changed files with 63 additions and 32 deletions

2
run-autopep8.sh Executable file
View File

@ -0,0 +1,2 @@
#!/bin/sh
autopep8 --in-place --recursive src

View File

@ -328,6 +328,7 @@ class testmode(object): # pylint: disable=too-few-public-methods
class command(object): # pylint: disable=too-few-public-methods class command(object): # pylint: disable=too-few-public-methods
"""Decorator for API command method""" """Decorator for API command method"""
def __init__(self, *aliases): def __init__(self, *aliases):
self.aliases = aliases self.aliases = aliases

View File

@ -12,6 +12,7 @@ from pybitmessage.defaults import (
class AddressGenerator(object): class AddressGenerator(object):
""""Base class for address generation and validation""" """"Base class for address generation and validation"""
def __init__(self): def __init__(self):
pass pass

View File

@ -9,6 +9,27 @@ The PyBitmessage startup script
# Right now, PyBitmessage only support connecting to stream 1. It doesn't # Right now, PyBitmessage only support connecting to stream 1. It doesn't
# yet contain logic to expand into further streams. # yet contain logic to expand into further streams.
from threads import (
set_thread_name, printLock,
addressGenerator, objectProcessor, singleCleaner, singleWorker, sqlThread)
from singleinstance import singleinstance
from inventory import Inventory
from helper_startup import (
adjustHalfOpenConnectionsLimit, fixSocket, start_proxyconfig)
from debug import logger # this should go before any threads
from bmconfigparser import config
from testmode_init import populate_api_test_data
import state
import shutdown
import network
import defaults
import traceback
import time
import threading
import signal
import multiprocessing
import getopt
import depends
import os import os
import sys import sys
@ -18,34 +39,13 @@ except ImportError:
from pybitmessage import pathmagic from pybitmessage import pathmagic
app_dir = pathmagic.setup() app_dir = pathmagic.setup()
import depends
depends.check_dependencies() depends.check_dependencies()
import getopt
import multiprocessing
# Used to capture a Ctrl-C keypress so that Bitmessage can shutdown gracefully. # Used to capture a Ctrl-C keypress so that Bitmessage can shutdown gracefully.
import signal
import threading
import time
import traceback
import defaults
# Network subsystem # Network subsystem
import network
import shutdown
import state
from testmode_init import populate_api_test_data
from bmconfigparser import config
from debug import logger # this should go before any threads
from helper_startup import (
adjustHalfOpenConnectionsLimit, fixSocket, start_proxyconfig)
from inventory import Inventory
from singleinstance import singleinstance
# Synchronous threads # Synchronous threads
from threads import (
set_thread_name, printLock,
addressGenerator, objectProcessor, singleCleaner, singleWorker, sqlThread)
def signal_handler(signum, frame): def signal_handler(signum, frame):
@ -81,6 +81,7 @@ def signal_handler(signum, frame):
class Main(object): class Main(object):
"""Main PyBitmessage class""" """Main PyBitmessage class"""
def start(self): def start(self):
"""Start main application""" """Start main application"""
# pylint: disable=too-many-statements,too-many-branches,too-many-locals # pylint: disable=too-many-statements,too-many-branches,too-many-locals

View File

@ -128,7 +128,7 @@ class BMConfigParser(SafeConfigParser):
shutil.copyfile(fileName, fileNameBak) shutil.copyfile(fileName, fileNameBak)
# The backup succeeded. # The backup succeeded.
fileNameExisted = True fileNameExisted = True
except(IOError, Exception): except (IOError, Exception):
# The backup failed. This can happen if the file # The backup failed. This can happen if the file
# didn't exist before. # didn't exist before.
fileNameExisted = False fileNameExisted = False

View File

@ -43,6 +43,7 @@ class objectProcessor(threading.Thread):
The objectProcessor thread, of which there is only one, receives network The objectProcessor thread, of which there is only one, receives network
objects (msg, broadcast, pubkey, getpubkey) from the receiveDataThreads. objects (msg, broadcast, pubkey, getpubkey) from the receiveDataThreads.
""" """
def __init__(self): def __init__(self):
threading.Thread.__init__(self, name="objectProcessor") threading.Thread.__init__(self, name="objectProcessor")
random.seed() random.seed()

View File

@ -1080,10 +1080,10 @@ class singleWorker(StoppableThread):
" more difficult than you are" " more difficult than you are"
" willing to do. {2}" " willing to do. {2}"
).format(str(float(requiredAverageProofOfWorkNonceTrialsPerByte) ).format(str(float(requiredAverageProofOfWorkNonceTrialsPerByte)
/ defaults.networkDefaultProofOfWorkNonceTrialsPerByte), / defaults.networkDefaultProofOfWorkNonceTrialsPerByte),
str(float(requiredPayloadLengthExtraBytes) str(float(requiredPayloadLengthExtraBytes)
/ defaults.networkDefaultPayloadLengthExtraBytes), / defaults.networkDefaultPayloadLengthExtraBytes),
l10n.formatTimestamp())))) l10n.formatTimestamp()))))
continue continue
else: # if we are sending a message to ourselves or a chan.. else: # if we are sending a message to ourselves or a chan..
self.logger.info('Sending a message.') self.logger.info('Sending a message.')

View File

@ -35,6 +35,7 @@ class SmtpServerChannelException(Exception):
class smtpServerChannel(smtpd.SMTPChannel): class smtpServerChannel(smtpd.SMTPChannel):
"""Asyncore channel for SMTP protocol (server)""" """Asyncore channel for SMTP protocol (server)"""
def smtp_EHLO(self, arg): def smtp_EHLO(self, arg):
"""Process an EHLO""" """Process an EHLO"""
if not arg: if not arg:
@ -73,6 +74,7 @@ class smtpServerChannel(smtpd.SMTPChannel):
class smtpServerPyBitmessage(smtpd.SMTPServer): class smtpServerPyBitmessage(smtpd.SMTPServer):
"""Asyncore SMTP server class""" """Asyncore SMTP server class"""
def handle_accept(self): def handle_accept(self):
"""Accept a connection""" """Accept a connection"""
pair = self.accept() pair = self.accept()
@ -180,6 +182,7 @@ class smtpServerPyBitmessage(smtpd.SMTPServer):
class smtpServer(StoppableThread): class smtpServer(StoppableThread):
"""SMTP server thread""" """SMTP server thread"""
def __init__(self, _=None): def __init__(self, _=None):
super(smtpServer, self).__init__(name="smtpServerThread") super(smtpServer, self).__init__(name="smtpServerThread")
self.server = smtpServerPyBitmessage(('127.0.0.1', LISTENPORT), None) self.server = smtpServerPyBitmessage(('127.0.0.1', LISTENPORT), None)

View File

@ -436,7 +436,7 @@ def check_dependencies(verbose=False, optional=False):
if sys.hexversion < 0x3000000: if sys.hexversion < 0x3000000:
logger.error( logger.error(
'PyBitmessage requires Python 3 or greater') 'PyBitmessage requires Python 3 or greater')
#has_all_dependencies = False # has_all_dependencies = False
sys.exit() sys.exit()
# FIXME: This needs to be uncommented when more of the code is python3 compatible # FIXME: This needs to be uncommented when more of the code is python3 compatible

View File

@ -37,12 +37,14 @@ class MsgDecodeException(Exception):
class DecompressionSizeException(MsgDecodeException): class DecompressionSizeException(MsgDecodeException):
# pylint: disable=super-init-not-called # pylint: disable=super-init-not-called
"""Decompression resulted in too much data (attack protection)""" """Decompression resulted in too much data (attack protection)"""
def __init__(self, size): def __init__(self, size):
self.size = size self.size = size
class MsgEncode(object): class MsgEncode(object):
"""Message encoder class""" """Message encoder class"""
def __init__(self, message, encoding=BITMESSAGE_ENCODING_SIMPLE): def __init__(self, message, encoding=BITMESSAGE_ENCODING_SIMPLE):
self.data = None self.data = None
self.encoding = encoding self.encoding = encoding
@ -86,6 +88,7 @@ class MsgEncode(object):
class MsgDecode(object): class MsgDecode(object):
"""Message decoder class""" """Message decoder class"""
def __init__(self, encoding, data): def __init__(self, encoding, data):
self.encoding = encoding self.encoding = encoding
if self.encoding == BITMESSAGE_ENCODING_EXTENDED: if self.encoding == BITMESSAGE_ENCODING_EXTENDED:

View File

@ -21,6 +21,7 @@ class Inventory:
Inventory class which uses storage backends Inventory class which uses storage backends
to manage the inventory. to manage the inventory.
""" """
def __init__(self): def __init__(self):
self._moduleName = config.safeGet("inventory", "storage") self._moduleName = config.safeGet("inventory", "storage")
self._realInventory = create_inventory_instance(self._moduleName) self._realInventory = create_inventory_instance(self._moduleName)

View File

@ -5,6 +5,7 @@ logger = logging.getLogger('default')
class MsgBase(object): # pylint: disable=too-few-public-methods class MsgBase(object): # pylint: disable=too-few-public-methods
"""Base class for message types""" """Base class for message types"""
def __init__(self): def __init__(self):
self.data = {"": type(self).__name__.lower()} self.data = {"": type(self).__name__.lower()}

View File

@ -12,7 +12,7 @@ def start(config, state):
"""Start network threads""" """Start network threads"""
import state import state
from .announcethread import AnnounceThread from .announcethread import AnnounceThread
import network.connectionpool as connectionpool # pylint: disable=relative-import import network.connectionpool as connectionpool # pylint: disable=relative-import
from .addrthread import AddrThread from .addrthread import AddrThread
from .dandelion import Dandelion from .dandelion import Dandelion
from .downloadthread import DownloadThread from .downloadthread import DownloadThread

View File

@ -564,12 +564,12 @@ class dispatcher(object):
try: try:
kqueue_poller.pollster.control([select.kevent( kqueue_poller.pollster.control([select.kevent(
fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE)], 0) fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE)], 0)
except(AttributeError, KeyError, TypeError, IOError, OSError): except (AttributeError, KeyError, TypeError, IOError, OSError):
pass pass
try: try:
kqueue_poller.pollster.control([select.kevent( kqueue_poller.pollster.control([select.kevent(
fd, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE)], 0) fd, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE)], 0)
except(AttributeError, KeyError, TypeError, IOError, OSError): except (AttributeError, KeyError, TypeError, IOError, OSError):
pass pass
try: try:
epoll_poller.pollster.unregister(fd) epoll_poller.pollster.unregister(fd)
@ -726,7 +726,7 @@ class dispatcher(object):
# XXX unresolved # XXX unresolved
# cheap inheritance, used to pass all other attribute # cheap inheritance, used to pass all other attribute
# references to the underlying socket object. # references to the underlying socket object.
#def __getattr__(self, attr): # def __getattr__(self, attr):
# try: # try:
# retattr = getattr(self.socket, attr) # retattr = getattr(self.socket, attr)
# except AttributeError: # except AttributeError:

View File

@ -28,6 +28,7 @@ logger = logging.getLogger('default')
class Dandelion: # pylint: disable=old-style-class class Dandelion: # pylint: disable=old-style-class
"""Dandelion class for tracking stem/fluff stages.""" """Dandelion class for tracking stem/fluff stages."""
def __init__(self): def __init__(self):
# currently assignable child stems # currently assignable child stems
self.stem = [] self.stem = []

View File

@ -69,6 +69,7 @@ class HTTPRequestHandler(asyncore.dispatcher):
class HTTPSRequestHandler(HTTPRequestHandler, TLSHandshake): class HTTPSRequestHandler(HTTPRequestHandler, TLSHandshake):
"""Handling HTTPS request""" """Handling HTTPS request"""
def __init__(self, sock): def __init__(self, sock):
if not hasattr(self, '_map'): if not hasattr(self, '_map'):
asyncore.dispatcher.__init__(self, sock) # pylint: disable=non-parent-init-called asyncore.dispatcher.__init__(self, sock) # pylint: disable=non-parent-init-called

View File

@ -102,7 +102,7 @@ class ObjectTracker(object):
def handleReceivedObject(self, streamNumber, hashid): def handleReceivedObject(self, streamNumber, hashid):
"""Handling received object""" """Handling received object"""
hashid_bytes = bytes(hashid); hashid_bytes = bytes(hashid)
for i in connectionpool.pool.connections(): for i in connectionpool.pool.connections():
if not i.fullyEstablished: if not i.fullyEstablished:
continue continue

View File

@ -15,6 +15,7 @@ from .threads import StoppableThread
class ReceiveQueueThread(StoppableThread): class ReceiveQueueThread(StoppableThread):
"""This thread processes data received from the network """This thread processes data received from the network
(which is done by the asyncore thread)""" (which is done by the asyncore thread)"""
def __init__(self, num=0): def __init__(self, num=0):
super(ReceiveQueueThread, self).__init__(name="ReceiveQueue_%i" % num) super(ReceiveQueueThread, self).__init__(name="ReceiveQueue_%i" % num)

View File

@ -26,6 +26,7 @@ class Socks4aError(ProxyError):
class Socks4a(Proxy): class Socks4a(Proxy):
"""SOCKS4a proxy class""" """SOCKS4a proxy class"""
def __init__(self, address=None): def __init__(self, address=None):
Proxy.__init__(self, address) Proxy.__init__(self, address)
self.ipaddr = None self.ipaddr = None
@ -73,6 +74,7 @@ class Socks4a(Proxy):
class Socks4aConnection(Socks4a): class Socks4aConnection(Socks4a):
"""Child SOCKS4a class used for making outbound connections.""" """Child SOCKS4a class used for making outbound connections."""
def __init__(self, address): def __init__(self, address):
Socks4a.__init__(self, address=address) Socks4a.__init__(self, address=address)
@ -119,6 +121,7 @@ class Socks4aConnection(Socks4a):
class Socks4aResolver(Socks4a): class Socks4aResolver(Socks4a):
"""DNS resolver class using SOCKS4a""" """DNS resolver class using SOCKS4a"""
def __init__(self, host): def __init__(self, host):
self.host = host self.host = host
self.port = 8444 self.port = 8444

View File

@ -42,6 +42,7 @@ class Socks5Error(ProxyError):
class Socks5(Proxy): class Socks5(Proxy):
"""A socks5 proxy base class""" """A socks5 proxy base class"""
def __init__(self, address=None): def __init__(self, address=None):
Proxy.__init__(self, address) Proxy.__init__(self, address)
self.ipaddr = None self.ipaddr = None
@ -163,6 +164,7 @@ class Socks5(Proxy):
class Socks5Connection(Socks5): class Socks5Connection(Socks5):
"""Child socks5 class used for making outbound connections.""" """Child socks5 class used for making outbound connections."""
def state_auth_done(self): def state_auth_done(self):
"""Request connection to be made""" """Request connection to be made"""
# Now we can request the actual connection # Now we can request the actual connection
@ -199,6 +201,7 @@ class Socks5Connection(Socks5):
class Socks5Resolver(Socks5): class Socks5Resolver(Socks5):
"""DNS resolver class using socks5""" """DNS resolver class using socks5"""
def __init__(self, host): def __init__(self, host):
self.host = host self.host = host
self.port = 8444 self.port = 8444

View File

@ -40,10 +40,12 @@ if (
else: else:
sslProtocolCiphers = "AECDH-AES256-SHA" sslProtocolCiphers = "AECDH-AES256-SHA"
class TLSDispatcher(AdvancedDispatcher): class TLSDispatcher(AdvancedDispatcher):
"""TLS functionality for classes derived from AdvancedDispatcher""" """TLS functionality for classes derived from AdvancedDispatcher"""
# pylint: disable=too-many-instance-attributes, too-many-arguments # pylint: disable=too-many-instance-attributes, too-many-arguments
# pylint: disable=super-init-not-called # pylint: disable=super-init-not-called
def __init__(self, _=None, sock=None, certfile=None, keyfile=None, def __init__(self, _=None, sock=None, certfile=None, keyfile=None,
server_side=False, ciphers=sslProtocolCiphers): server_side=False, ciphers=sslProtocolCiphers):
self.want_read = self.want_write = True self.want_read = self.want_write = True

View File

@ -22,6 +22,7 @@ class Cipher(object):
ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb') ctx2 = pyelliptic.Cipher("secretkey", iv, 0, ciphername='aes-256-cfb')
print ctx2.ciphering(ciphertext) print ctx2.ciphering(ciphertext)
""" """
def __init__(self, key, iv, do, ciphername='aes-256-cbc'): def __init__(self, key, iv, do, ciphername='aes-256-cbc'):
""" """
do == 1 => Encrypt; do == 0 => Decrypt do == 1 => Encrypt; do == 0 => Decrypt

View File

@ -100,6 +100,7 @@ class _OpenSSL(object):
Wrapper for OpenSSL using ctypes Wrapper for OpenSSL using ctypes
""" """
# pylint: disable=too-many-statements, too-many-instance-attributes # pylint: disable=too-many-statements, too-many-instance-attributes
def __init__(self, library): def __init__(self, library):
""" """
Build the wrapper Build the wrapper

View File

@ -43,6 +43,7 @@ Returns an instance of :class:`QPixmap` which have generated identicon image.
from six.moves import range from six.moves import range
from PyQt6 import QtCore, QtGui from PyQt6 import QtCore, QtGui
class IdenticonRendererBase(object): class IdenticonRendererBase(object):
"""Encapsulate methods around rendering identicons""" """Encapsulate methods around rendering identicons"""

View File

@ -21,6 +21,7 @@ class singleinstance(object):
Implements a single instance application by creating a lock file Implements a single instance application by creating a lock file
at appdata. at appdata.
""" """
def __init__(self, flavor_id="", daemon=False): def __init__(self, flavor_id="", daemon=False):
self.initialized = False self.initialized = False
self.counter = 0 self.counter = 0

View File

@ -11,6 +11,7 @@ from .storage import InventoryItem, InventoryStorage
class SqliteInventory(InventoryStorage): class SqliteInventory(InventoryStorage):
"""Inventory using SQLite""" """Inventory using SQLite"""
def __init__(self): def __init__(self):
super(SqliteInventory, self).__init__() super(SqliteInventory, self).__init__()
# of objects (like msg payloads and pubkey payloads) # of objects (like msg payloads and pubkey payloads)

View File

@ -15,6 +15,7 @@ class translateClass:
when we are in daemon mode and not using any QT functions. when we are in daemon mode and not using any QT functions.
""" """
# pylint: disable=old-style-class,too-few-public-methods # pylint: disable=old-style-class,too-few-public-methods
def __init__(self, context, text): def __init__(self, context, text):
self.context = context self.context = context
self.text = text self.text = text