formatting and shorten line length

This commit is contained in:
lakshyacis 2020-01-17 18:57:36 +05:30
parent b6a81f1252
commit 3211fca953
No known key found for this signature in database
GPG Key ID: D2C539C8EC63E9EB
8 changed files with 109 additions and 70 deletions

View File

@ -2,7 +2,6 @@
Operations with addresses Operations with addresses
""" """
# pylint: disable=redefined-outer-name,inconsistent-return-statements # pylint: disable=redefined-outer-name,inconsistent-return-statements
import hashlib import hashlib
from binascii import hexlify, unhexlify from binascii import hexlify, unhexlify
from struct import pack, unpack from struct import pack, unpack
@ -180,7 +179,8 @@ def decodeAddress(address):
returns (status, address version number, stream number, returns (status, address version number, stream number,
data (almost certainly a ripe hash)) data (almost certainly a ripe hash))
""" """
# pylint: disable=too-many-return-statements,too-many-statements,too-many-branches # pylint: disable=too-many-return-statements,too-many-statements
# pylint: disable=too-many-branches
address = str(address).strip() address = str(address).strip()

View File

@ -1,15 +1,11 @@
# pylint: disable=too-many-locals,too-many-lines,no-self-use,too-many-public-methods,too-many-branches
# pylint: disable=too-many-statements
# Copyright (c) 2012-2016 Jonathan Warren
# Copyright (c) 2012-2020 The Bitmessage developers
""" """
This is not what you run to run the Bitmessage API. Instead, enable the API This is not what you run to run the Bitmessage API. Instead, enable the API
( https://bitmessage.org/wiki/API ) and optionally enable daemon mode ( https://bitmessage.org/wiki/API ) and optionally enable daemon mode
( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py. ( https://bitmessage.org/wiki/Daemon ) then run bitmessagemain.py.
""" """
# Copyright (c) 2012-2016 Jonathan Warren
# Copyright (c) 2012-2020 The Bitmessage developers
# pylint: disable=too-many-lines,no-self-use,unused-variable,unused-argument
import base64 import base64
import errno import errno
import hashlib import hashlib
@ -33,7 +29,13 @@ import queues
import shared import shared
import shutdown import shutdown
import state import state
from addresses import addBMIfNotPresent, calculateInventoryHash, decodeAddress, decodeVarint, varintDecodeError from addresses import (
addBMIfNotPresent,
calculateInventoryHash,
decodeAddress,
decodeVarint,
varintDecodeError
)
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from debug import logger from debug import logger
from helper_ackPayload import genAckPayload from helper_ackPayload import genAckPayload
@ -136,9 +138,11 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
""" """
This is one of several classes that constitute the API This is one of several classes that constitute the API
This class was written by Vaibhav Bhatia. Modified by Jonathan Warren (Atheros). This class was written by Vaibhav Bhatia.
Modified by Jonathan Warren (Atheros).
http://code.activestate.com/recipes/501148-xmlrpc-serverclient-which-does-cookie-handling-and/ http://code.activestate.com/recipes/501148-xmlrpc-serverclient-which-does-cookie-handling-and/
""" """
# pylint: disable=too-many-public-methods
def do_POST(self): def do_POST(self):
""" """
@ -175,7 +179,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
# SimpleXMLRPCDispatcher. To maintain backwards compatibility, # SimpleXMLRPCDispatcher. To maintain backwards compatibility,
# check to see if a subclass implements _dispatch and dispatch # check to see if a subclass implements _dispatch and dispatch
# using that method if present. # using that method if present.
response = self.server._marshaled_dispatch( # pylint: disable=protected-access # pylint: disable=protected-access
response = self.server._marshaled_dispatch(
data, getattr(self, '_dispatch', None) data, getattr(self, '_dispatch', None)
) )
except BaseException: # This should only happen if the module is buggy except BaseException: # This should only happen if the module is buggy
@ -213,8 +218,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
_, encstr = self.headers.get('Authorization').split() _, encstr = self.headers.get('Authorization').split()
emailid, password = encstr.decode('base64').split(':') emailid, password = encstr.decode('base64').split(':')
return ( return (
emailid == BMConfigParser().get('bitmessagesettings', 'apiusername') and emailid == BMConfigParser().get(
password == BMConfigParser().get('bitmessagesettings', 'apipassword') 'bitmessagesettings', 'apiusername') and
password == BMConfigParser().get(
'bitmessagesettings', 'apipassword')
) )
else: else:
logger.warning( logger.warning(
@ -251,10 +258,14 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
if status == 'invalidcharacters': if status == 'invalidcharacters':
raise APIError(9, 'Invalid characters in address: ' + address) raise APIError(9, 'Invalid characters in address: ' + address)
if status == 'versiontoohigh': if status == 'versiontoohigh':
raise APIError(10, 'Address version number too high (or zero) in address: ' + address) raise APIError(
10,
'Address version number too high (or zero) in address: ' +
address)
if status == 'varintmalformed': if status == 'varintmalformed':
raise APIError(26, 'Malformed varint in address: ' + address) raise APIError(26, 'Malformed varint in address: ' + address)
raise APIError(7, 'Could not decode address: %s : %s' % (address, status)) raise APIError(
7, 'Could not decode address: %s : %s' % (address, status))
if addressVersionNumber < 2 or addressVersionNumber > 4: if addressVersionNumber < 2 or addressVersionNumber > 4:
raise APIError( raise APIError(
11, 'The address version number currently must be 2, 3 or 4.' 11, 'The address version number currently must be 2, 3 or 4.'
@ -272,10 +283,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
def HandleListAddresses(self, method): def HandleListAddresses(self, method):
"""Handle a request to list addresses""" """Handle a request to list addresses"""
data = '{"addresses":[' data = '{"addresses":['
for addressInKeysFile in BMConfigParser().addresses(): for addressInKeysFile in BMConfigParser().addresses():
status, addressVersionNumber, streamNumber, hash01 = decodeAddress( # pylint: disable=unused-variable status, addressVersionNumber, streamNumber, hash01 = decodeAddress(
addressInKeysFile) addressInKeysFile)
if len(data) > 20: if len(data) > 20:
data += ',' data += ','
@ -379,16 +389,19 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
elif len(params) == 3: elif len(params) == 3:
label, eighteenByteRipe, totalDifficulty = params label, eighteenByteRipe, totalDifficulty = params
nonceTrialsPerByte = int( nonceTrialsPerByte = int(
defaults.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) defaults.networkDefaultProofOfWorkNonceTrialsPerByte *
totalDifficulty)
payloadLengthExtraBytes = BMConfigParser().get( payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes') 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
elif len(params) == 4: elif len(params) == 4:
label, eighteenByteRipe, totalDifficulty, \ label, eighteenByteRipe, totalDifficulty, \
smallMessageDifficulty = params smallMessageDifficulty = params
nonceTrialsPerByte = int( nonceTrialsPerByte = int(
defaults.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) defaults.networkDefaultProofOfWorkNonceTrialsPerByte *
totalDifficulty)
payloadLengthExtraBytes = int( payloadLengthExtraBytes = int(
defaults.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty) defaults.networkDefaultPayloadLengthExtraBytes *
smallMessageDifficulty)
else: else:
raise APIError(0, 'Too many parameters!') raise APIError(0, 'Too many parameters!')
label = self._decode(label, "base64") label = self._decode(label, "base64")
@ -406,6 +419,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
def HandleCreateDeterministicAddresses(self, params): def HandleCreateDeterministicAddresses(self, params):
"""Handle a request to create a deterministic address""" """Handle a request to create a deterministic address"""
# pylint: disable=too-many-branches, too-many-statements
if not params: if not params:
raise APIError(0, 'I need parameters!') raise APIError(0, 'I need parameters!')
@ -461,7 +475,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
passphrase, numberOfAddresses, addressVersionNumber, \ passphrase, numberOfAddresses, addressVersionNumber, \
streamNumber, eighteenByteRipe, totalDifficulty = params streamNumber, eighteenByteRipe, totalDifficulty = params
nonceTrialsPerByte = int( nonceTrialsPerByte = int(
defaults.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) defaults.networkDefaultProofOfWorkNonceTrialsPerByte *
totalDifficulty)
payloadLengthExtraBytes = BMConfigParser().get( payloadLengthExtraBytes = BMConfigParser().get(
'bitmessagesettings', 'defaultpayloadlengthextrabytes') 'bitmessagesettings', 'defaultpayloadlengthextrabytes')
@ -470,9 +485,11 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
streamNumber, eighteenByteRipe, totalDifficulty, \ streamNumber, eighteenByteRipe, totalDifficulty, \
smallMessageDifficulty = params smallMessageDifficulty = params
nonceTrialsPerByte = int( nonceTrialsPerByte = int(
defaults.networkDefaultProofOfWorkNonceTrialsPerByte * totalDifficulty) defaults.networkDefaultProofOfWorkNonceTrialsPerByte *
totalDifficulty)
payloadLengthExtraBytes = int( payloadLengthExtraBytes = int(
defaults.networkDefaultPayloadLengthExtraBytes * smallMessageDifficulty) defaults.networkDefaultPayloadLengthExtraBytes *
smallMessageDifficulty)
else: else:
raise APIError(0, 'Too many parameters!') raise APIError(0, 'Too many parameters!')
if not passphrase: if not passphrase:
@ -606,9 +623,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
label = str_chan + ' ' + passphrase label = str_chan + ' ' + passphrase
except BaseException: except BaseException:
label = str_chan + ' ' + repr(passphrase) label = str_chan + ' ' + repr(passphrase)
status, addressVersionNumber, streamNumber, toRipe = (
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( # pylint: disable=unused-variable self._verifyAddress(suppliedAddress))
suppliedAddress)
suppliedAddress = addBMIfNotPresent(suppliedAddress) suppliedAddress = addBMIfNotPresent(suppliedAddress)
queues.apiAddressGeneratorReturnQueue.queue.clear() queues.apiAddressGeneratorReturnQueue.queue.clear()
queues.addressGeneratorQueue.put(( queues.addressGeneratorQueue.put((
@ -631,8 +647,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
raise APIError(0, 'I need parameters.') raise APIError(0, 'I need parameters.')
elif len(params) == 1: elif len(params) == 1:
address, = params address, = params
# pylint: disable=unused-variable status, addressVersionNumber, streamNumber, toRipe = (
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address) self._verifyAddress(address))
address = addBMIfNotPresent(address) address = addBMIfNotPresent(address)
if not BMConfigParser().has_section(address): if not BMConfigParser().has_section(address):
raise APIError( raise APIError(
@ -653,8 +669,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
raise APIError(0, 'I need parameters.') raise APIError(0, 'I need parameters.')
elif len(params) == 1: elif len(params) == 1:
address, = params address, = params
# pylint: disable=unused-variable status, addressVersionNumber, streamNumber, toRipe = (
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address) self._verifyAddress(address))
address = addBMIfNotPresent(address) address = addBMIfNotPresent(address)
if not BMConfigParser().has_section(address): if not BMConfigParser().has_section(address):
raise APIError( raise APIError(
@ -666,7 +682,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
shared.reloadMyAddressHashes() shared.reloadMyAddressHashes()
return 'success' return 'success'
def HandleGetAllInboxMessages(self, params): # pylint: disable=unused-argument def HandleGetAllInboxMessages(self, params):
"""Handle a request to get all inbox messages""" """Handle a request to get all inbox messages"""
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -694,7 +710,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}' data += ']}'
return data return data
def HandleGetAllInboxMessageIds(self, params): # pylint: disable=unused-argument def HandleGetAllInboxMessageIds(self, params):
"""Handle a request to get all inbox message IDs""" """Handle a request to get all inbox message IDs"""
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -753,7 +769,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}' data += ']}'
return data return data
def HandleGetAllSentMessages(self, params): # pylint: disable=unused-argument def HandleGetAllSentMessages(self, params):
"""Handle a request to get all sent messages""" """Handle a request to get all sent messages"""
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -782,7 +798,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}' data += ']}'
return data return data
def HandleGetAllSentMessageIds(self, params): # pylint: disable=unused-argument def HandleGetAllSentMessageIds(self, params):
"""Handle a request to get all sent message IDs""" """Handle a request to get all sent message IDs"""
queryreturn = sqlQuery( queryreturn = sqlQuery(
@ -873,7 +889,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data = '{"sentMessages":[' data = '{"sentMessages":['
for row in queryreturn: for row in queryreturn:
msgid, toAddress, fromAddress, subject, lastactiontime, message, \ msgid, toAddress, fromAddress, subject, lastactiontime, message, \
encodingtype, status, ackdata = row # pylint: disable=unused-variable encodingtype, status, ackdata = row
subject = shared.fixPotentiallyInvalidUTF8Data(subject) subject = shared.fixPotentiallyInvalidUTF8Data(subject)
message = shared.fixPotentiallyInvalidUTF8Data(message) message = shared.fixPotentiallyInvalidUTF8Data(message)
if len(data) > 25: if len(data) > 25:
@ -952,7 +968,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid) sqlExecute('''UPDATE sent SET folder='trash' WHERE msgid=?''', msgid)
return 'Trashed sent message (assuming message existed).' return 'Trashed sent message (assuming message existed).'
def HandleSendMessage(self, params): def HandleSendMessage(self, params): # pylint: disable=too-many-locals
"""Handle a request to send a message""" """Handle a request to send a message"""
if not params: if not params:
@ -983,7 +999,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
TTL = 28 * 24 * 60 * 60 TTL = 28 * 24 * 60 * 60
toAddress = addBMIfNotPresent(toAddress) toAddress = addBMIfNotPresent(toAddress)
fromAddress = addBMIfNotPresent(fromAddress) fromAddress = addBMIfNotPresent(fromAddress)
# pylint: disable=unused-variable
status, addressVersionNumber, streamNumber, toRipe = \ status, addressVersionNumber, streamNumber, toRipe = \
self._verifyAddress(toAddress) self._verifyAddress(toAddress)
self._verifyAddress(fromAddress) self._verifyAddress(fromAddress)
@ -1157,10 +1172,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
queues.UISignalQueue.put(('rerenderSubscriptions', '')) queues.UISignalQueue.put(('rerenderSubscriptions', ''))
return 'Deleted subscription if it existed.' return 'Deleted subscription if it existed.'
def ListSubscriptions(self, params): # pylint: disable=unused-argument def ListSubscriptions(self, params):
"""Handle a request to list susbcriptions""" """Handle a request to list susbcriptions"""
# pylint: disable=unused-variable
queryreturn = sqlQuery( queryreturn = sqlQuery(
"SELECT label, address, enabled FROM subscriptions") "SELECT label, address, enabled FROM subscriptions")
data = {'subscriptions': []} data = {'subscriptions': []}
@ -1195,12 +1209,15 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
) )
with shared.printLock: with shared.printLock:
print( print(
'(For msg message via API) Doing proof of work. Total required difficulty:', '(For msg message via API) Doing proof of work.'
'Total required difficulty:',
float( float(
requiredAverageProofOfWorkNonceTrialsPerByte requiredAverageProofOfWorkNonceTrialsPerByte
) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte, ) / defaults.networkDefaultProofOfWorkNonceTrialsPerByte,
'Required small message difficulty:', 'Required small message difficulty:',
float(requiredPayloadLengthExtraBytes) / defaults.networkDefaultPayloadLengthExtraBytes, float(
requiredPayloadLengthExtraBytes
) / defaults.networkDefaultPayloadLengthExtraBytes,
) )
powStartTime = time.time() powStartTime = time.time()
initialHash = hashlib.sha512(encryptedPayload).digest() initialHash = hashlib.sha512(encryptedPayload).digest()
@ -1209,8 +1226,9 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
print '(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce print '(For msg message via API) Found proof of work', trialValue, 'Nonce:', nonce
try: try:
print( print(
'POW took', int(time.time() - powStartTime), 'seconds.', 'POW took', int(time.time() - powStartTime),
nonce / (time.time() - powStartTime), 'nonce trials per second.', 'seconds.', nonce / (time.time() - powStartTime),
'nonce trials per second.',
) )
except BaseException: except BaseException:
pass pass
@ -1237,7 +1255,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
sqlExecute("UPDATE sent SET folder='trash' WHERE ackdata=?", ackdata) sqlExecute("UPDATE sent SET folder='trash' WHERE ackdata=?", ackdata)
return 'Trashed sent message (assuming message existed).' return 'Trashed sent message (assuming message existed).'
def HandleDissimatePubKey(self, params): # pylint: disable=unused-argument def HandleDissimatePubKey(self, params):
"""Handle a request to disseminate a public key""" """Handle a request to disseminate a public key"""
# The device issuing this command to PyBitmessage supplies a pubkey # The device issuing this command to PyBitmessage supplies a pubkey
@ -1266,7 +1284,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
pubkeyReadPosition += 8 pubkeyReadPosition += 8
else: else:
pubkeyReadPosition += 4 pubkeyReadPosition += 4
# pylint: disable=unused-variable
addressVersion, addressVersionLength = decodeVarint( addressVersion, addressVersionLength = decodeVarint(
payload[pubkeyReadPosition:pubkeyReadPosition + 10]) payload[pubkeyReadPosition:pubkeyReadPosition + 10])
pubkeyReadPosition += addressVersionLength pubkeyReadPosition += addressVersionLength
@ -1325,7 +1342,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
data += ']}' data += ']}'
return data return data
def HandleClientStatus(self, params): # pylint: disable=unused-argument def HandleClientStatus(self, params):
"""Handle a request to get the status of the client""" """Handle a request to get the status of the client"""
connections_num = len(network.stats.connectedHostsList()) connections_num = len(network.stats.connectedHostsList())

View File

@ -9,7 +9,6 @@ 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.
import os import os
import sys import sys
@ -46,14 +45,15 @@ from inventory import Inventory
from knownnodes import readKnownNodes from knownnodes import readKnownNodes
# Network objects and threads # Network objects and threads
from network import ( from network import (
BMConnectionPool, Dandelion, BMConnectionPool, Dandelion, AddrThread, AnnounceThread, BMNetworkThread,
AddrThread, AnnounceThread, BMNetworkThread, InvThread, ReceiveQueueThread, InvThread, ReceiveQueueThread, DownloadThread, UploadThread
DownloadThread, UploadThread) )
from singleinstance import singleinstance from singleinstance import singleinstance
# Synchronous threads # Synchronous threads
from threads import ( from threads import (
set_thread_name, set_thread_name, addressGenerator, objectProcessor, singleCleaner,
addressGenerator, objectProcessor, singleCleaner, singleWorker, sqlThread) singleWorker, sqlThread
)
def connectToStream(streamNumber): def connectToStream(streamNumber):
@ -90,7 +90,8 @@ def _fixSocket():
addressToString = ctypes.windll.ws2_32.WSAAddressToStringA addressToString = ctypes.windll.ws2_32.WSAAddressToStringA
def inet_ntop(family, host): def inet_ntop(family, host):
"""Converting an IP address in packed binary format to string format""" """Converting an IP address in packed
binary format to string format"""
if family == socket.AF_INET: if family == socket.AF_INET:
if len(host) != 4: if len(host) != 4:
raise ValueError("invalid IPv4 host") raise ValueError("invalid IPv4 host")
@ -112,7 +113,8 @@ def _fixSocket():
stringToAddress = ctypes.windll.ws2_32.WSAStringToAddressA stringToAddress = ctypes.windll.ws2_32.WSAStringToAddressA
def inet_pton(family, host): def inet_pton(family, host):
"""Converting an IP address in string format to a packed binary format""" """Converting an IP address in string format
to a packed binary format"""
buf = "\0" * 28 buf = "\0" * 28
lengthBuf = pack("I", len(buf)) lengthBuf = pack("I", len(buf))
if stringToAddress(str(host), if stringToAddress(str(host),
@ -153,8 +155,8 @@ def signal_handler(signum, frame):
if thread.name not in ("PyBitmessage", "MainThread"): if thread.name not in ("PyBitmessage", "MainThread"):
return return
logger.error("Got signal %i", signum) logger.error("Got signal %i", signum)
# there are possible non-UI variants to run bitmessage which should shutdown # there are possible non-UI variants to run bitmessage
# especially test-mode # which should shutdown especially test-mode
if shared.thisapp.daemon or not state.enableGUI: if shared.thisapp.daemon or not state.enableGUI:
shutdown.doCleanShutdown() shutdown.doCleanShutdown()
else: else:
@ -386,10 +388,13 @@ class Main(object):
while state.shutdown == 0: while state.shutdown == 0:
time.sleep(1) time.sleep(1)
if ( if (
state.testmode and time.time() - state.last_api_response >= 30): state.testmode and time.time() -
state.last_api_response >= 30
):
self.stop() self.stop()
elif not state.enableGUI: elif not state.enableGUI:
from tests import core as test_core # pylint: disable=relative-import # pylint: disable=relative-import
from tests import core as test_core
test_core_result = test_core.run() test_core_result = test_core.run()
state.enableGUI = True state.enableGUI = True
self.stop() self.stop()

View File

@ -47,6 +47,7 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
Singleton class inherited from :class:`ConfigParser.SafeConfigParser` Singleton class inherited from :class:`ConfigParser.SafeConfigParser`
with additional methods specific to bitmessage config. with additional methods specific to bitmessage config.
""" """
# pylint: disable=too-many-ancestors
_temp = {} _temp = {}
@ -95,7 +96,8 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
return False return False
def safeGetInt(self, section, field, default=0): def safeGetInt(self, section, field, default=0):
"""Return value as integer, default on exceptions, 0 if default missing""" """Return value as integer, default on exceptions,
0 if default missing"""
try: try:
return self.getint(section, field) return self.getint(section, field)
except (ConfigParser.NoSectionError, ConfigParser.NoOptionError, except (ConfigParser.NoSectionError, ConfigParser.NoOptionError,
@ -111,7 +113,8 @@ class BMConfigParser(ConfigParser.SafeConfigParser):
return default return default
def items(self, section, raw=False, variables=None): def items(self, section, raw=False, variables=None):
"""Return section variables as parent, but override the "raw" argument to always True""" """Return section variables as parent,
but override the "raw" argument to always True"""
# pylint: disable=arguments-differ # pylint: disable=arguments-differ
return ConfigParser.ConfigParser.items(self, section, True, variables) return ConfigParser.ConfigParser.items(self, section, True, variables)

View File

@ -13,8 +13,14 @@ DATA_FILES = [
('bitmsghash', ['bitmsghash/bitmsghash.cl', 'bitmsghash/bitmsghash.so']), ('bitmsghash', ['bitmsghash/bitmsghash.cl', 'bitmsghash/bitmsghash.so']),
('translations', glob('translations/*.qm')), ('translations', glob('translations/*.qm')),
('ui', glob('bitmessageqt/*.ui')), ('ui', glob('bitmessageqt/*.ui')),
('translations', glob(str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??.qm')), (
('translations', glob(str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??_??.qm')), 'translations',
glob(os.path.join(str(QtCore.QLibraryInfo.location(
QtCore.QLibraryInfo.TranslationsPath)), 'qt_??.qm'))),
(
'translations',
glob(os.path.join(str(QtCore.QLibraryInfo.location(
QtCore.QLibraryInfo.TranslationsPath)), 'qt_??_??.qm'))),
] ]
setup( setup(

View File

@ -36,7 +36,8 @@ class addressGenerator(StoppableThread):
Process the requests for addresses generation Process the requests for addresses generation
from `.queues.addressGeneratorQueue` from `.queues.addressGeneratorQueue`
""" """
# pylint: disable=too-many-locals, too-many-branches, protected-access, too-many-statements # pylint: disable=too-many-locals, too-many-branches
# pylint: disable=protected-access, too-many-statements
while state.shutdown == 0: while state.shutdown == 0:
queueValue = queues.addressGeneratorQueue.get() queueValue = queues.addressGeneratorQueue.get()
nonceTrialsPerByte = 0 nonceTrialsPerByte = 0

View File

@ -1,6 +1,9 @@
""" """
The objectProcessor thread, of which there is only one, processes the network objects The objectProcessor thread, of which there is only one,
processes the network objects
""" """
# pylint: disable=too-many-locals,too-many-return-statements
# pylint: disable=too-many-branches,too-many-statements
import hashlib import hashlib
import logging import logging
import random import random
@ -34,7 +37,6 @@ import tr
from fallback import RIPEMD160Hash from fallback import RIPEMD160Hash
import l10n import l10n
# pylint: disable=too-many-locals, too-many-return-statements, too-many-branches, too-many-statements
logger = logging.getLogger('default') logger = logging.getLogger('default')
@ -647,7 +649,8 @@ class objectProcessor(threading.Thread):
if decodeAddress(toAddress)[1] >= 3 \ if decodeAddress(toAddress)[1] >= 3 \
and not BMConfigParser().safeGetBoolean(toAddress, 'chan'): and not BMConfigParser().safeGetBoolean(toAddress, 'chan'):
# If I'm not friendly with this person: # If I'm not friendly with this person:
if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(fromAddress): if not shared.isAddressInMyAddressBookSubscriptionsListOrWhitelist(
fromAddress):
requiredNonceTrialsPerByte = BMConfigParser().getint( requiredNonceTrialsPerByte = BMConfigParser().getint(
toAddress, 'noncetrialsperbyte') toAddress, 'noncetrialsperbyte')
requiredPayloadLengthExtraBytes = BMConfigParser().getint( requiredPayloadLengthExtraBytes = BMConfigParser().getint(

View File

@ -24,7 +24,9 @@ import queues
import shared import shared
import state import state
import tr import tr
from addresses import calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint from addresses import (
calculateInventoryHash, decodeAddress, decodeVarint, encodeVarint
)
from bmconfigparser import BMConfigParser from bmconfigparser import BMConfigParser
from helper_sql import sqlExecute, sqlQuery from helper_sql import sqlExecute, sqlQuery
from inventory import Inventory from inventory import Inventory
@ -237,11 +239,13 @@ class singleWorker(StoppableThread):
return payload return payload
def doPOWForMyV2Pubkey(self, adressHash): def doPOWForMyV2Pubkey(self, adressHash):
""" This function also broadcasts out the pubkey message once it is done with the POW""" """ This function also broadcasts out the pubkey
message once it is done with the POW"""
# Look up my stream number based on my address hash # Look up my stream number based on my address hash
myAddress = shared.myAddressesByHash[adressHash] myAddress = shared.myAddressesByHash[adressHash]
# status # status
_, addressVersionNumber, streamNumber, adressHash = decodeAddress(myAddress) _, addressVersionNumber, streamNumber, adressHash = (
decodeAddress(myAddress))
# 28 days from now plus or minus five minutes # 28 days from now plus or minus five minutes
TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300)) TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300))