python3 fixes
This commit is contained in:
parent
4dea6d5ced
commit
0de9e38415
|
@ -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
|
||||||
|
@ -46,7 +45,8 @@ def decodeBase58(string, alphabet=ALPHABET):
|
||||||
for char in string:
|
for char in string:
|
||||||
num *= base
|
num *= base
|
||||||
num += alphabet.index(char)
|
num += alphabet.index(char)
|
||||||
except: # ValueError
|
# ValueError
|
||||||
|
except:
|
||||||
# character not found (like a space character or a 0)
|
# character not found (like a space character or a 0)
|
||||||
return 0
|
return 0
|
||||||
return num
|
return num
|
||||||
|
@ -85,13 +85,13 @@ def decodeVarint(data):
|
||||||
the minimum amount of data possible or else it is malformed.
|
the minimum amount of data possible or else it is malformed.
|
||||||
Returns a tuple: (theEncodedValue, theSizeOfTheVarintInBytes)
|
Returns a tuple: (theEncodedValue, theSizeOfTheVarintInBytes)
|
||||||
"""
|
"""
|
||||||
|
|
||||||
if not data:
|
if not data:
|
||||||
return (0, 0)
|
return (0, 0)
|
||||||
firstByte, = unpack('>B', data[0:1])
|
firstByte, = unpack('>B', data[0:1])
|
||||||
if firstByte < 253:
|
if firstByte < 253:
|
||||||
# encodes 0 to 252
|
# encodes 0 to 252
|
||||||
return (firstByte, 1) # the 1 is the length of the varint
|
# the 1 is the length of the varint
|
||||||
|
return (firstByte, 1)
|
||||||
if firstByte == 253:
|
if firstByte == 253:
|
||||||
# encodes 253 to 65535
|
# encodes 253 to 65535
|
||||||
if len(data) < 3:
|
if len(data) < 3:
|
||||||
|
@ -180,7 +180,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-return-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()
|
||||||
|
|
||||||
if address[:3] == 'BM-':
|
if address[:3] == 'BM-':
|
||||||
|
@ -237,7 +238,8 @@ def decodeAddress(address):
|
||||||
status = 'success'
|
status = 'success'
|
||||||
if addressVersionNumber == 1:
|
if addressVersionNumber == 1:
|
||||||
return status, addressVersionNumber, streamNumber, data[-24:-4]
|
return status, addressVersionNumber, streamNumber, data[-24:-4]
|
||||||
elif addressVersionNumber == 2 or addressVersionNumber == 3:
|
# elif addressVersionNumber == 2 or addressVersionNumber == 3:
|
||||||
|
elif addressVersionNumber in (2, 3):
|
||||||
embeddedRipeData = \
|
embeddedRipeData = \
|
||||||
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
||||||
if len(embeddedRipeData) == 19:
|
if len(embeddedRipeData) == 19:
|
||||||
|
|
65
src/api.py
65
src/api.py
|
@ -1,15 +1,12 @@
|
||||||
# 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-2019 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.
|
||||||
"""
|
"""
|
||||||
|
# pylint: disable=too-many-locals,too-many-lines,no-self-use,unused-argument
|
||||||
|
# pylint: disable=too-many-statements,too-many-public-methods,too-many-branches
|
||||||
|
# Copyright (c) 2012-2016 Jonathan Warren
|
||||||
|
# Copyright (c) 2012-2019 The Bitmessage developers
|
||||||
import base64
|
import base64
|
||||||
import errno
|
import errno
|
||||||
import hashlib
|
import hashlib
|
||||||
|
@ -58,6 +55,7 @@ class APIError(Exception):
|
||||||
|
|
||||||
class StoppableXMLRPCServer(SimpleXMLRPCServer):
|
class StoppableXMLRPCServer(SimpleXMLRPCServer):
|
||||||
"""A SimpleXMLRPCServer that honours state.shutdown"""
|
"""A SimpleXMLRPCServer that honours state.shutdown"""
|
||||||
|
# pylint:disable=too-few-public-methods
|
||||||
allow_reuse_address = True
|
allow_reuse_address = True
|
||||||
|
|
||||||
def serve_forever(self):
|
def serve_forever(self):
|
||||||
|
@ -150,7 +148,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
Note: this method is the same as in SimpleXMLRPCRequestHandler,
|
Note: this method is the same as in SimpleXMLRPCRequestHandler,
|
||||||
just hacked to handle cookies
|
just hacked to handle cookies
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# Check that the path is legal
|
# Check that the path is legal
|
||||||
if not self.is_rpc_path_valid():
|
if not self.is_rpc_path_valid():
|
||||||
self.report_404()
|
self.report_404()
|
||||||
|
@ -175,10 +172,12 @@ 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
|
# This should only happen if the module is buggy
|
||||||
|
except BaseException:
|
||||||
# internal error, report as HTTP server error
|
# internal error, report as HTTP server error
|
||||||
self.send_response(500)
|
self.send_response(500)
|
||||||
self.end_headers()
|
self.end_headers()
|
||||||
|
@ -251,7 +250,8 @@ 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))
|
||||||
|
@ -275,7 +275,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
|
|
||||||
data = '{"addresses":['
|
data = '{"addresses":['
|
||||||
for addressInKeysFile in BMConfigParser().addresses():
|
for addressInKeysFile in BMConfigParser().addresses():
|
||||||
status, addressVersionNumber, streamNumber, hash01 = decodeAddress( # pylint: disable=unused-variable
|
# pylint: disable=unused-variable
|
||||||
|
status, addressVersionNumber, streamNumber, hash01 = decodeAddress(
|
||||||
addressInKeysFile)
|
addressInKeysFile)
|
||||||
if len(data) > 20:
|
if len(data) > 20:
|
||||||
data += ','
|
data += ','
|
||||||
|
@ -485,7 +486,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
# 0 means "just use the proper addressVersionNumber"
|
# 0 means "just use the proper addressVersionNumber"
|
||||||
if addressVersionNumber == 0:
|
if addressVersionNumber == 0:
|
||||||
addressVersionNumber = 4
|
addressVersionNumber = 4
|
||||||
if addressVersionNumber != 3 and addressVersionNumber != 4:
|
# if addressVersionNumber != 3 and addressVersionNumber != 4:
|
||||||
|
if addressVersionNumber not in (3, 4):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
2, 'The address version number currently must be 3, 4, or 0'
|
2, 'The address version number currently must be 3, 4, or 0'
|
||||||
' (which means auto-select). %i isn\'t supported.' %
|
' (which means auto-select). %i isn\'t supported.' %
|
||||||
|
@ -536,7 +538,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
if not passphrase:
|
if not passphrase:
|
||||||
raise APIError(1, 'The specified passphrase is blank.')
|
raise APIError(1, 'The specified passphrase is blank.')
|
||||||
passphrase = self._decode(passphrase, "base64")
|
passphrase = self._decode(passphrase, "base64")
|
||||||
if addressVersionNumber != 3 and addressVersionNumber != 4:
|
# if addressVersionNumber != 3 and addressVersionNumber != 4:
|
||||||
|
if addressVersionNumber not in (3, 4):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
2, 'The address version number currently must be 3 or 4. %i'
|
2, 'The address version number currently must be 3 or 4. %i'
|
||||||
' isn\'t supported.' % addressVersionNumber)
|
' isn\'t supported.' % addressVersionNumber)
|
||||||
|
@ -606,8 +609,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)
|
||||||
|
# pylint: disable=unused-variable
|
||||||
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress( # pylint: disable=unused-variable
|
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(
|
||||||
suppliedAddress)
|
suppliedAddress)
|
||||||
suppliedAddress = addBMIfNotPresent(suppliedAddress)
|
suppliedAddress = addBMIfNotPresent(suppliedAddress)
|
||||||
queues.apiAddressGeneratorReturnQueue.queue.clear()
|
queues.apiAddressGeneratorReturnQueue.queue.clear()
|
||||||
|
@ -632,7 +635,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
elif len(params) == 1:
|
elif len(params) == 1:
|
||||||
address, = params
|
address, = params
|
||||||
# pylint: disable=unused-variable
|
# pylint: disable=unused-variable
|
||||||
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
|
status, addressVersionNumber, streamNumber, toRipe = \
|
||||||
|
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(
|
||||||
|
@ -654,7 +658,8 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
elif len(params) == 1:
|
elif len(params) == 1:
|
||||||
address, = params
|
address, = params
|
||||||
# pylint: disable=unused-variable
|
# pylint: disable=unused-variable
|
||||||
status, addressVersionNumber, streamNumber, toRipe = self._verifyAddress(address)
|
status, addressVersionNumber, streamNumber, toRipe = \
|
||||||
|
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 +671,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 +699,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 +758,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 +787,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(
|
||||||
|
@ -1157,7 +1162,7 @@ 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
|
# pylint: disable=unused-variable
|
||||||
|
@ -1206,7 +1211,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
initialHash = hashlib.sha512(encryptedPayload).digest()
|
initialHash = hashlib.sha512(encryptedPayload).digest()
|
||||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
trialValue, nonce = proofofwork.run(target, initialHash)
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
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), 'seconds.',
|
||||||
|
@ -1224,7 +1229,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
int(time.time()) + TTL, ''
|
int(time.time()) + TTL, ''
|
||||||
)
|
)
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', hexlify(inventoryHash)
|
print('Broadcasting inv for msg(API disseminatePreEncryptedMsg command):', hexlify(inventoryHash))
|
||||||
queues.invQueue.put((toStreamNumber, inventoryHash))
|
queues.invQueue.put((toStreamNumber, inventoryHash))
|
||||||
|
|
||||||
def HandleTrashSentMessageByAckDAta(self, params):
|
def HandleTrashSentMessageByAckDAta(self, params):
|
||||||
|
@ -1237,7 +1242,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
|
||||||
|
@ -1254,10 +1259,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
target = 2 ** 64 / ((
|
target = 2 ** 64 / ((
|
||||||
len(payload) + defaults.networkDefaultPayloadLengthExtraBytes + 8
|
len(payload) + defaults.networkDefaultPayloadLengthExtraBytes + 8
|
||||||
) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)
|
) * defaults.networkDefaultProofOfWorkNonceTrialsPerByte)
|
||||||
print '(For pubkey message via API) Doing proof of work...'
|
print('(For pubkey message via API) Doing proof of work...')
|
||||||
initialHash = hashlib.sha512(payload).digest()
|
initialHash = hashlib.sha512(payload).digest()
|
||||||
trialValue, nonce = proofofwork.run(target, initialHash)
|
trialValue, nonce = proofofwork.run(target, initialHash)
|
||||||
print '(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce
|
print('(For pubkey message via API) Found proof of work', trialValue, 'Nonce:', nonce)
|
||||||
payload = pack('>Q', nonce) + payload
|
payload = pack('>Q', nonce) + payload
|
||||||
|
|
||||||
pubkeyReadPosition = 8 # bypass the nonce
|
pubkeyReadPosition = 8 # bypass the nonce
|
||||||
|
@ -1279,7 +1284,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
objectType, pubkeyStreamNumber, payload, int(time.time()) + TTL, ''
|
objectType, pubkeyStreamNumber, payload, int(time.time()) + TTL, ''
|
||||||
)
|
)
|
||||||
with shared.printLock:
|
with shared.printLock:
|
||||||
print 'broadcasting inv within API command disseminatePubkey with hash:', hexlify(inventoryHash)
|
print('broadcasting inv within API command disseminatePubkey with hash:', hexlify(inventoryHash))
|
||||||
queues.invQueue.put((pubkeyStreamNumber, inventoryHash))
|
queues.invQueue.put((pubkeyStreamNumber, inventoryHash))
|
||||||
|
|
||||||
def HandleGetMessageDataByDestinationHash(self, params):
|
def HandleGetMessageDataByDestinationHash(self, params):
|
||||||
|
@ -1325,7 +1330,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())
|
||||||
|
|
|
@ -1010,7 +1010,7 @@ def sendMessage(sender="", recv="", broadcast=None, subject="", body="", reply=F
|
||||||
def loadInbox():
|
def loadInbox():
|
||||||
"""Load the list of messages"""
|
"""Load the list of messages"""
|
||||||
sys.stdout = sys.__stdout__
|
sys.stdout = sys.__stdout__
|
||||||
print "Loading inbox messages..."
|
print("Loading inbox messages...")
|
||||||
sys.stdout = printlog
|
sys.stdout = printlog
|
||||||
|
|
||||||
where = "toaddress || fromaddress || subject || message"
|
where = "toaddress || fromaddress || subject || message"
|
||||||
|
@ -1062,7 +1062,7 @@ def loadInbox():
|
||||||
def loadSent():
|
def loadSent():
|
||||||
"""Load the messages that sent"""
|
"""Load the messages that sent"""
|
||||||
sys.stdout = sys.__stdout__
|
sys.stdout = sys.__stdout__
|
||||||
print "Loading sent messages..."
|
print("Loading sent messages...")
|
||||||
sys.stdout = printlog
|
sys.stdout = printlog
|
||||||
|
|
||||||
where = "toaddress || fromaddress || subject || message"
|
where = "toaddress || fromaddress || subject || message"
|
||||||
|
@ -1148,7 +1148,7 @@ def loadSent():
|
||||||
def loadAddrBook():
|
def loadAddrBook():
|
||||||
"""Load address book"""
|
"""Load address book"""
|
||||||
sys.stdout = sys.__stdout__
|
sys.stdout = sys.__stdout__
|
||||||
print "Loading address book..."
|
print("Loading address book...")
|
||||||
sys.stdout = printlog
|
sys.stdout = printlog
|
||||||
|
|
||||||
ret = sqlQuery("SELECT label, address FROM addressbook")
|
ret = sqlQuery("SELECT label, address FROM addressbook")
|
||||||
|
@ -1254,7 +1254,7 @@ def run(stdscr):
|
||||||
def doShutdown():
|
def doShutdown():
|
||||||
"""Shutting the app down"""
|
"""Shutting the app down"""
|
||||||
sys.stdout = sys.__stdout__
|
sys.stdout = sys.__stdout__
|
||||||
print "Shutting down..."
|
print("Shutting down...")
|
||||||
sys.stdout = printlog
|
sys.stdout = printlog
|
||||||
shutdown.doCleanShutdown()
|
shutdown.doCleanShutdown()
|
||||||
sys.stdout = sys.__stdout__
|
sys.stdout = sys.__stdout__
|
||||||
|
|
|
@ -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
|
||||||
import ctypes
|
import ctypes
|
||||||
|
@ -30,7 +29,8 @@ import state
|
||||||
import shutdown
|
import shutdown
|
||||||
|
|
||||||
from bmconfigparser import BMConfigParser
|
from bmconfigparser import BMConfigParser
|
||||||
from debug import logger # this should go before any threads
|
# this should go before any threads
|
||||||
|
from debug import logger
|
||||||
from helper_startup import (
|
from helper_startup import (
|
||||||
isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections
|
isOurOperatingSystemLimitedToHavingVeryFewHalfOpenConnections
|
||||||
)
|
)
|
||||||
|
@ -156,11 +156,11 @@ def signal_handler(signum, frame):
|
||||||
if shared.thisapp.daemon or not state.enableGUI:
|
if shared.thisapp.daemon or not state.enableGUI:
|
||||||
shutdown.doCleanShutdown()
|
shutdown.doCleanShutdown()
|
||||||
else:
|
else:
|
||||||
print ('# Thread: {}({})'.format(thread.name, thread.ident))
|
print('# Thread: {}({})'.format(thread.name, thread.ident))
|
||||||
for filename, lineno, name, line in traceback.extract_stack(frame):
|
for filename, lineno, name, line in traceback.extract_stack(frame):
|
||||||
print ("File: '{}', line {}, in {}" .format(filename, lineno, name))
|
print("File: '{}', line {}, in {}" .format(filename, lineno, name))
|
||||||
if line:
|
if line:
|
||||||
print (' {}'.format(line.strip()))
|
print(' {}'.format(line.strip()))
|
||||||
print('Unfortunately you cannot use Ctrl+C when running the UI \
|
print('Unfortunately you cannot use Ctrl+C when running the UI \
|
||||||
because the UI captures the signal.')
|
because the UI captures the signal.')
|
||||||
|
|
||||||
|
@ -189,8 +189,9 @@ class Main(object):
|
||||||
'Started proxy config plugin %s in %s sec',
|
'Started proxy config plugin %s in %s sec',
|
||||||
proxy_type, time.time() - proxyconfig_start)
|
proxy_type, time.time() - proxyconfig_start)
|
||||||
|
|
||||||
def start(self): # pylint: disable=too-many-statements, too-many-branches, too-many-locals
|
def start(self):
|
||||||
"""Start main application"""
|
"""Start main application"""
|
||||||
|
# pylint: disable=too-many-statements, too-many-branches, too-many-locals
|
||||||
_fixSocket()
|
_fixSocket()
|
||||||
|
|
||||||
config = BMConfigParser()
|
config = BMConfigParser()
|
||||||
|
@ -218,7 +219,8 @@ class Main(object):
|
||||||
if os.path.isfile(os.path.join(
|
if os.path.isfile(os.path.join(
|
||||||
state.appdata, 'unittest.lock')):
|
state.appdata, 'unittest.lock')):
|
||||||
daemon = True
|
daemon = True
|
||||||
state.enableGUI = False # run without a UI
|
# run without a UI
|
||||||
|
state.enableGUI = False
|
||||||
# Fallback: in case when no api command was issued
|
# Fallback: in case when no api command was issued
|
||||||
state.last_api_response = time.time()
|
state.last_api_response = time.time()
|
||||||
# Apply special settings
|
# Apply special settings
|
||||||
|
@ -234,7 +236,8 @@ class Main(object):
|
||||||
)
|
)
|
||||||
|
|
||||||
if daemon:
|
if daemon:
|
||||||
state.enableGUI = False # run without a UI
|
# run without a UI
|
||||||
|
state.enableGUI = False
|
||||||
|
|
||||||
# is the application already running? If yes then exit.
|
# is the application already running? If yes then exit.
|
||||||
if state.enableGUI and not state.curses and not state.kivy and not depends.check_pyqt():
|
if state.enableGUI and not state.curses and not state.kivy and not depends.check_pyqt():
|
||||||
|
@ -281,7 +284,6 @@ class Main(object):
|
||||||
|
|
||||||
readKnownNodes()
|
readKnownNodes()
|
||||||
|
|
||||||
|
|
||||||
# Not needed if objproc is disabled
|
# Not needed if objproc is disabled
|
||||||
if state.enableObjProc:
|
if state.enableObjProc:
|
||||||
|
|
||||||
|
@ -340,7 +342,8 @@ class Main(object):
|
||||||
shared.reloadBroadcastSendersForWhichImWatching()
|
shared.reloadBroadcastSendersForWhichImWatching()
|
||||||
# API is also objproc dependent
|
# API is also objproc dependent
|
||||||
if config.safeGetBoolean('bitmessagesettings', 'apienabled'):
|
if config.safeGetBoolean('bitmessagesettings', 'apienabled'):
|
||||||
import api # pylint: disable=relative-import
|
# pylint: disable=relative-import
|
||||||
|
import api
|
||||||
singleAPIThread = api.singleAPI()
|
singleAPIThread = api.singleAPI()
|
||||||
# close the main program even if there are threads left
|
# close the main program even if there are threads left
|
||||||
singleAPIThread.daemon = True
|
singleAPIThread.daemon = True
|
||||||
|
@ -405,7 +408,8 @@ class Main(object):
|
||||||
if (state.testmode and time.time() - state.last_api_response >= 30):
|
if (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(self)
|
test_core_result = test_core.run(self)
|
||||||
state.enableGUI = True
|
state.enableGUI = True
|
||||||
self.stop()
|
self.stop()
|
||||||
|
@ -429,13 +433,14 @@ class Main(object):
|
||||||
while True:
|
while True:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
|
||||||
os._exit(0) # pylint: disable=protected-access
|
os._exit(0) # pylint: disable=protected-access
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
# fork not implemented
|
# fork not implemented
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
parentPid = os.getpid()
|
parentPid = os.getpid()
|
||||||
shared.thisapp.lock() # relock
|
# relock
|
||||||
|
shared.thisapp.lock()
|
||||||
|
|
||||||
os.umask(0)
|
os.umask(0)
|
||||||
try:
|
try:
|
||||||
|
@ -450,14 +455,16 @@ class Main(object):
|
||||||
# wait until child ready
|
# wait until child ready
|
||||||
while True:
|
while True:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
# pylint: disable=protected-access
|
||||||
os._exit(0) # pylint: disable=protected-access
|
os._exit(0)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
# fork not implemented
|
# fork not implemented
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
shared.thisapp.lock() # relock
|
# relock
|
||||||
shared.thisapp.lockPid = None # indicate we're the final child
|
shared.thisapp.lock()
|
||||||
|
# indicate we're the final child
|
||||||
|
shared.thisapp.lockPid = None
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
sys.stderr.flush()
|
sys.stderr.flush()
|
||||||
if not sys.platform.startswith('win'):
|
if not sys.platform.startswith('win'):
|
||||||
|
@ -480,7 +487,6 @@ class Main(object):
|
||||||
# signal.signal(signal.SIGINT, signal.SIG_DFL)
|
# signal.signal(signal.SIGINT, signal.SIG_DFL)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|
||||||
def usage():
|
def usage():
|
||||||
"""Displaying the usages"""
|
"""Displaying the usages"""
|
||||||
print('Usage: ' + sys.argv[0] + ' [OPTIONS]')
|
print('Usage: ' + sys.argv[0] + ' [OPTIONS]')
|
||||||
|
|
|
@ -1,7 +1,7 @@
|
||||||
"""
|
"""
|
||||||
BMConfigParser class definition and default configuration settings
|
BMConfigParser class definition and default configuration settings
|
||||||
"""
|
"""
|
||||||
|
# pylint: disable=no-self-use, arguments-differ
|
||||||
import configparser
|
import configparser
|
||||||
import shutil
|
import shutil
|
||||||
import os
|
import os
|
||||||
|
@ -45,7 +45,7 @@ BMConfigDefaults = {
|
||||||
class BMConfigParser(configparser.ConfigParser):
|
class BMConfigParser(configparser.ConfigParser):
|
||||||
"""Singleton class inherited from ConfigParsedadfeConfigParser
|
"""Singleton class inherited from ConfigParsedadfeConfigParser
|
||||||
with additional methods specific to bitmessage config."""
|
with additional methods specific to bitmessage config."""
|
||||||
|
# pylint: disable=too-many-ancestors
|
||||||
_temp = {}
|
_temp = {}
|
||||||
|
|
||||||
def set(self, section, option, value=None):
|
def set(self, section, option, value=None):
|
||||||
|
@ -56,7 +56,8 @@ class BMConfigParser(configparser.ConfigParser):
|
||||||
raise ValueError("Invalid value %s" % value)
|
raise ValueError("Invalid value %s" % value)
|
||||||
return configparser.ConfigParser.set(self, section, option, value)
|
return configparser.ConfigParser.set(self, section, option, value)
|
||||||
|
|
||||||
def get(self, section, option, raw=False, variables=None): # pylint: disable=arguments-differ
|
def get(self, section, option, raw=False, variables=None):
|
||||||
|
# pylint: disable=unused-argument
|
||||||
try:
|
try:
|
||||||
if section == "bitmessagesettings" and option == "timeformat":
|
if section == "bitmessagesettings" and option == "timeformat":
|
||||||
return configparser.ConfigParser.get(
|
return configparser.ConfigParser.get(
|
||||||
|
@ -84,24 +85,26 @@ class BMConfigParser(configparser.ConfigParser):
|
||||||
self._temp[section] = {option: value}
|
self._temp[section] = {option: value}
|
||||||
|
|
||||||
def safeGetBoolean(self, section, field):
|
def safeGetBoolean(self, section, field):
|
||||||
|
"""Return value as boolean, False on exceptions"""
|
||||||
config = configparser.ConfigParser()
|
config = configparser.ConfigParser()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
#Used in the python2.7
|
# Used in the python2.7
|
||||||
# return self.getboolean(section, field)
|
# return self.getboolean(section, field)
|
||||||
#Used in the python3.5.2
|
# Used in the python3.5.2
|
||||||
return config.getboolean(section, field)
|
return config.getboolean(section, field)
|
||||||
except (configparser.NoSectionError, configparser.NoOptionError,
|
except (configparser.NoSectionError, configparser.NoOptionError,
|
||||||
ValueError, AttributeError):
|
ValueError, AttributeError):
|
||||||
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"""
|
||||||
config = configparser.ConfigParser()
|
config = configparser.ConfigParser()
|
||||||
|
|
||||||
try:
|
try:
|
||||||
#Used in the python2.7
|
# Used in the python2.7
|
||||||
# return self.getint(section, field)
|
# return self.getint(section, field)
|
||||||
#Used in the python3.5.2
|
# Used in the python3.5.2
|
||||||
return config.getint(section, field)
|
return config.getint(section, field)
|
||||||
except (configparser.NoSectionError, configparser.NoOptionError,
|
except (configparser.NoSectionError, configparser.NoOptionError,
|
||||||
ValueError, AttributeError):
|
ValueError, AttributeError):
|
||||||
|
@ -116,12 +119,14 @@ class BMConfigParser(configparser.ConfigParser):
|
||||||
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 configparser.ConfigParser.items(self, section, True, variables)
|
return configparser.ConfigParser.items(self, section, True, variables)
|
||||||
|
|
||||||
def addresses(self):
|
def addresses(self):
|
||||||
|
"""Return a list of local bitmessage addresses (from section labels)"""
|
||||||
return [x for x in BMConfigParser().sections() if x.startswith('BM-')]
|
return [x for x in BMConfigParser().sections() if x.startswith('BM-')]
|
||||||
|
|
||||||
|
|
||||||
def read(self, filenames):
|
def read(self, filenames):
|
||||||
configparser.ConfigParser.read(self, filenames)
|
configparser.ConfigParser.read(self, filenames)
|
||||||
for section in self.sections():
|
for section in self.sections():
|
||||||
|
@ -167,7 +172,8 @@ class BMConfigParser(configparser.ConfigParser):
|
||||||
def validate(self, section, option, value):
|
def validate(self, section, option, value):
|
||||||
"""Input validator interface (using factory pattern)"""
|
"""Input validator interface (using factory pattern)"""
|
||||||
try:
|
try:
|
||||||
return getattr(self, 'validate_{}_{}'.format(section, option))(value)
|
return getattr(self, 'validate_{}_{}'.format(
|
||||||
|
section, option))(value)
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
|
@ -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(
|
||||||
('translations', glob(str(QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??_??.qm')),
|
str(
|
||||||
|
QtCore.QLibraryInfo.location(
|
||||||
|
QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??.qm')),
|
||||||
|
('translations', glob(
|
||||||
|
str(
|
||||||
|
QtCore.QLibraryInfo.location(
|
||||||
|
QtCore.QLibraryInfo.TranslationsPath)) + '/qt_??_??.qm')),
|
||||||
]
|
]
|
||||||
|
|
||||||
setup(
|
setup(
|
||||||
|
|
Reference in New Issue
Block a user