Changed path to src to pybitmessage
This commit is contained in:
parent
dac95989b4
commit
c7700507e1
|
@ -1,7 +1,7 @@
|
||||||
# This is an example of how to connect to and use the Bitmessage API.
|
# This is an example of how to connect to and use the Bitmessage API.
|
||||||
# See https://bitmessage.org/wiki/API_Reference
|
# See https://bitmessage.org/wiki/API_Reference
|
||||||
|
|
||||||
import xmlrpclib
|
import xmlrpc.client as xmlrpclib
|
||||||
import json
|
import json
|
||||||
import time
|
import time
|
||||||
|
|
||||||
|
@ -9,29 +9,29 @@ if __name__ == '__main__':
|
||||||
|
|
||||||
api = xmlrpclib.ServerProxy("http://bradley:password@localhost:8442/")
|
api = xmlrpclib.ServerProxy("http://bradley:password@localhost:8442/")
|
||||||
|
|
||||||
print 'Let\'s test the API first.'
|
print('Let\'s test the API first.')
|
||||||
inputstr1 = "hello"
|
inputstr1 = "hello"
|
||||||
inputstr2 = "world"
|
inputstr2 = "world"
|
||||||
print api.helloWorld(inputstr1, inputstr2)
|
print(api.helloWorld(inputstr1, inputstr2))
|
||||||
print api.add(2,3)
|
print(api.add(2,3))
|
||||||
|
|
||||||
print 'Let\'s set the status bar message.'
|
print('Let\'s set the status bar message.')
|
||||||
print api.statusBar("new status bar message")
|
print(api.statusBar("new status bar message"))
|
||||||
|
|
||||||
print 'Let\'s list our addresses:'
|
print('Let\'s list our addresses:')
|
||||||
print api.listAddresses()
|
print(api.listAddresses())
|
||||||
|
|
||||||
print 'Let\'s list our address again, but this time let\'s parse the json data into a Python data structure:'
|
print('Let\'s list our address again, but this time let\'s parse the json data into a Python data structure:')
|
||||||
jsonAddresses = json.loads(api.listAddresses())
|
jsonAddresses = json.loads(api.listAddresses())
|
||||||
print jsonAddresses
|
print(jsonAddresses)
|
||||||
print 'Now that we have our address data in a nice Python data structure, let\'s look at the first address (index 0) and print its label:'
|
print('Now that we have our address data in a nice Python data structure, let\'s look at the first address (index 0) and print its label:')
|
||||||
print jsonAddresses['addresses'][0]['label']
|
print(jsonAddresses['addresses'][0]['label'])
|
||||||
|
|
||||||
print 'Uncomment the next two lines to create a new random address with a slightly higher difficulty setting than normal.'
|
print('Uncomment the next two lines to create a new random address with a slightly higher difficulty setting than normal.')
|
||||||
#addressLabel = 'new address label'.encode('base64')
|
#addressLabel = 'new address label'.encode('base64')
|
||||||
#print api.createRandomAddress(addressLabel,False,1.05,1.1111)
|
#print api.createRandomAddress(addressLabel,False,1.05,1.1111)
|
||||||
|
|
||||||
print 'Uncomment these next four lines to create new deterministic addresses.'
|
print('Uncomment these next four lines to create new deterministic addresses.')
|
||||||
#passphrase = 'asdfasdfqwser'.encode('base64')
|
#passphrase = 'asdfasdfqwser'.encode('base64')
|
||||||
#jsonDeterministicAddresses = api.createDeterministicAddresses(passphrase, 2, 4, 1, False)
|
#jsonDeterministicAddresses = api.createDeterministicAddresses(passphrase, 2, 4, 1, False)
|
||||||
#print jsonDeterministicAddresses
|
#print jsonDeterministicAddresses
|
||||||
|
@ -46,18 +46,18 @@ if __name__ == '__main__':
|
||||||
#print 'Uncomment this line to unsubscribe from an address.'
|
#print 'Uncomment this line to unsubscribe from an address.'
|
||||||
#print api.deleteSubscription('2D94G5d8yp237GGqAheoecBYpdehdT3dha')
|
#print api.deleteSubscription('2D94G5d8yp237GGqAheoecBYpdehdT3dha')
|
||||||
|
|
||||||
print 'Let\'s now print all of our inbox messages:'
|
print('Let\'s now print all of our inbox messages:')
|
||||||
print api.getAllInboxMessages()
|
print(api.getAllInboxMessages())
|
||||||
inboxMessages = json.loads(api.getAllInboxMessages())
|
inboxMessages = json.loads(api.getAllInboxMessages())
|
||||||
print inboxMessages
|
print(inboxMessages)
|
||||||
|
|
||||||
print 'Uncomment this next line to decode the actual message data in the first message:'
|
print('Uncomment this next line to decode the actual message data in the first message:')
|
||||||
#print inboxMessages['inboxMessages'][0]['message'].decode('base64')
|
#print inboxMessages['inboxMessages'][0]['message'].decode('base64')
|
||||||
|
|
||||||
print 'Uncomment this next line in the code to delete a message'
|
print('Uncomment this next line in the code to delete a message')
|
||||||
#print api.trashMessage('584e5826947242a82cb883c8b39ac4a14959f14c228c0fbe6399f73e2cba5b59')
|
#print api.trashMessage('584e5826947242a82cb883c8b39ac4a14959f14c228c0fbe6399f73e2cba5b59')
|
||||||
|
|
||||||
print 'Uncomment these lines to send a message. The example addresses are invalid; you will have to put your own in.'
|
print('Uncomment these lines to send a message. The example addresses are invalid; you will have to put your own in.')
|
||||||
#subject = 'subject!'.encode('base64')
|
#subject = 'subject!'.encode('base64')
|
||||||
#message = 'Hello, this is the message'.encode('base64')
|
#message = 'Hello, this is the message'.encode('base64')
|
||||||
#ackData = api.sendMessage('BM-Gtsm7PUabZecs3qTeXbNPmqx3xtHCSXF', 'BM-2DCutnUZG16WiW3mdAm66jJUSCUv88xLgS', subject,message)
|
#ackData = api.sendMessage('BM-Gtsm7PUabZecs3qTeXbNPmqx3xtHCSXF', 'BM-2DCutnUZG16WiW3mdAm66jJUSCUv88xLgS', subject,message)
|
||||||
|
@ -66,7 +66,7 @@ if __name__ == '__main__':
|
||||||
# time.sleep(2)
|
# time.sleep(2)
|
||||||
# print 'Current status:', api.getStatus(ackData)
|
# print 'Current status:', api.getStatus(ackData)
|
||||||
|
|
||||||
print 'Uncomment these lines to send a broadcast. The example address is invalid; you will have to put your own in.'
|
print('Uncomment these lines to send a broadcast. The example address is invalid; you will have to put your own in.')
|
||||||
#subject = 'subject within broadcast'.encode('base64')
|
#subject = 'subject within broadcast'.encode('base64')
|
||||||
#message = 'Hello, this is the message within a broadcast.'.encode('base64')
|
#message = 'Hello, this is the message within a broadcast.'.encode('base64')
|
||||||
#print api.sendBroadcast('BM-onf6V1RELPgeNN6xw9yhpAiNiRexSRD4e', subject,message)
|
#print api.sendBroadcast('BM-onf6V1RELPgeNN6xw9yhpAiNiRexSRD4e', subject,message)
|
||||||
|
|
|
@ -1,4 +1,3 @@
|
||||||
python_prctl
|
|
||||||
psutil
|
psutil
|
||||||
pycrypto
|
pycrypto
|
||||||
qrcode
|
qrcode
|
||||||
|
|
3
setup.py
3
setup.py
|
@ -1,4 +1,4 @@
|
||||||
#!/usr/bin/env python2.7
|
#!/usr/bin/env python3.7
|
||||||
|
|
||||||
import os
|
import os
|
||||||
import shutil
|
import shutil
|
||||||
|
@ -9,7 +9,6 @@ from setuptools.command.install import install
|
||||||
|
|
||||||
from src.version import softwareVersion
|
from src.version import softwareVersion
|
||||||
|
|
||||||
|
|
||||||
EXTRAS_REQUIRE = {
|
EXTRAS_REQUIRE = {
|
||||||
'gir': ['pygobject'],
|
'gir': ['pygobject'],
|
||||||
'notify2': ['notify2'],
|
'notify2': ['notify2'],
|
||||||
|
|
|
@ -151,9 +151,9 @@ def encodeAddress(version, stream, ripe):
|
||||||
'Programming error in encodeAddress: The length of'
|
'Programming error in encodeAddress: The length of'
|
||||||
' a given ripe hash was not 20.'
|
' a given ripe hash was not 20.'
|
||||||
)
|
)
|
||||||
if ripe[:2] == '\x00\x00':
|
if ripe[:2] == '\x00\x00'.encode():
|
||||||
ripe = ripe[2:]
|
ripe = ripe[2:]
|
||||||
elif ripe[:1] == '\x00':
|
elif ripe[:1] == '\x00'.encode():
|
||||||
ripe = ripe[1:]
|
ripe = ripe[1:]
|
||||||
elif version == 4:
|
elif version == 4:
|
||||||
if len(ripe) != 20:
|
if len(ripe) != 20:
|
||||||
|
@ -245,7 +245,7 @@ def decodeAddress(address):
|
||||||
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
||||||
if len(embeddedRipeData) == 19:
|
if len(embeddedRipeData) == 19:
|
||||||
return status, addressVersionNumber, streamNumber, \
|
return status, addressVersionNumber, streamNumber, \
|
||||||
'\x00' + embeddedRipeData
|
'\x00'.encode() + embeddedRipeData
|
||||||
elif len(embeddedRipeData) == 20:
|
elif len(embeddedRipeData) == 20:
|
||||||
return status, addressVersionNumber, streamNumber, \
|
return status, addressVersionNumber, streamNumber, \
|
||||||
embeddedRipeData
|
embeddedRipeData
|
||||||
|
@ -260,7 +260,7 @@ def decodeAddress(address):
|
||||||
elif addressVersionNumber == 4:
|
elif addressVersionNumber == 4:
|
||||||
embeddedRipeData = \
|
embeddedRipeData = \
|
||||||
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
data[bytesUsedByVersionNumber + bytesUsedByStreamNumber:-4]
|
||||||
if embeddedRipeData[0:1] == '\x00':
|
if embeddedRipeData[0:1] == '\x00'.encode():
|
||||||
# In order to enforce address non-malleability, encoded
|
# In order to enforce address non-malleability, encoded
|
||||||
# RIPE data must have NULL bytes removed from the front
|
# RIPE data must have NULL bytes removed from the front
|
||||||
return 'encodingproblem', 0, 0, ''
|
return 'encodingproblem', 0, 0, ''
|
||||||
|
|
72
src/api.py
72
src/api.py
|
@ -18,7 +18,8 @@ from binascii import hexlify, unhexlify
|
||||||
|
|
||||||
from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
|
from xmlrpc.server import SimpleXMLRPCRequestHandler, SimpleXMLRPCServer
|
||||||
from struct import pack
|
from struct import pack
|
||||||
|
#decode('base64') is depracted on the python3
|
||||||
|
from base64 import b64decode
|
||||||
|
|
||||||
try:
|
try:
|
||||||
import defaults
|
import defaults
|
||||||
|
@ -45,29 +46,29 @@ try:
|
||||||
from network.threads import StoppableThread
|
from network.threads import StoppableThread
|
||||||
from version import softwareVersion
|
from version import softwareVersion
|
||||||
except:
|
except:
|
||||||
from . import defaults
|
from pybitmessage import defaults
|
||||||
from . import helper_inbox
|
from pybitmessage import helper_inbox
|
||||||
from . import helper_sent
|
from pybitmessage import helper_sent
|
||||||
from .network import stats
|
from pybitmessage.network import stats
|
||||||
from . import proofofwork
|
from pybitmessage import proofofwork
|
||||||
from . import queues
|
from pybitmessage import queues
|
||||||
from . import shared
|
from pybitmessage import shared
|
||||||
from .import shutdown
|
from pybitmessage import shutdown
|
||||||
from .import state
|
from pybitmessage import state
|
||||||
from .addresses import (
|
from pybitmessage.addresses import (
|
||||||
addBMIfNotPresent,
|
addBMIfNotPresent,
|
||||||
calculateInventoryHash,
|
calculateInventoryHash,
|
||||||
decodeAddress,
|
decodeAddress,
|
||||||
decodeVarint,
|
decodeVarint,
|
||||||
varintDecodeError
|
varintDecodeError
|
||||||
)
|
)
|
||||||
from .bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from .debug import logger
|
from pybitmessage.debug import logger
|
||||||
from .helper_ackPayload import genAckPayload
|
from pybitmessage.helper_ackPayload import genAckPayload
|
||||||
from .helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure
|
from pybitmessage.helper_sql import SqlBulkExecute, sqlExecute, sqlQuery, sqlStoredProcedure
|
||||||
from .inventory import Inventory
|
from pybitmessage.inventory import Inventory
|
||||||
from .network.threads import StoppableThread
|
from pybitmessage.network.threads import StoppableThread
|
||||||
from .version import softwareVersion
|
from pybitmessage.version import softwareVersion
|
||||||
|
|
||||||
str_chan = '[chan]'
|
str_chan = '[chan]'
|
||||||
|
|
||||||
|
@ -115,7 +116,7 @@ class singleAPI(StoppableThread):
|
||||||
except BaseException:
|
except BaseException:
|
||||||
pass
|
pass
|
||||||
|
|
||||||
def run(self):
|
def run(self):
|
||||||
port = BMConfigParser().getint('bitmessagesettings', 'apiport')
|
port = BMConfigParser().getint('bitmessagesettings', 'apiport')
|
||||||
try:
|
try:
|
||||||
getattr(errno, 'WSAEADDRINUSE')
|
getattr(errno, 'WSAEADDRINUSE')
|
||||||
|
@ -127,6 +128,13 @@ class singleAPI(StoppableThread):
|
||||||
logger.warning(
|
logger.warning(
|
||||||
'Failed to start API listener on port %s', port)
|
'Failed to start API listener on port %s', port)
|
||||||
port = random.randint(32767, 65535)
|
port = random.randint(32767, 65535)
|
||||||
|
print('pppppppppppppppppppppppppppppp')
|
||||||
|
print('port-{}'.format(port))
|
||||||
|
print('pppppppppppppppppppppppppppppp')
|
||||||
|
print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
|
||||||
|
print('bbbbbbbbbbbbbbbbbbbbbbbbbbbbb')
|
||||||
|
print(BMConfigParser().get('bitmessagesettings', 'apiinterface'))
|
||||||
|
print('bbbbbbbbbbbbbbbbbbbbbbbbbbbbb')
|
||||||
se = StoppableXMLRPCServer(
|
se = StoppableXMLRPCServer(
|
||||||
(BMConfigParser().get(
|
(BMConfigParser().get(
|
||||||
'bitmessagesettings', 'apiinterface'),
|
'bitmessagesettings', 'apiinterface'),
|
||||||
|
@ -142,6 +150,7 @@ class singleAPI(StoppableThread):
|
||||||
'bitmessagesettings', 'apiport', str(port))
|
'bitmessagesettings', 'apiport', str(port))
|
||||||
BMConfigParser().save()
|
BMConfigParser().save()
|
||||||
break
|
break
|
||||||
|
|
||||||
se.register_introspection_functions()
|
se.register_introspection_functions()
|
||||||
|
|
||||||
apiNotifyPath = BMConfigParser().safeGet(
|
apiNotifyPath = BMConfigParser().safeGet(
|
||||||
|
@ -181,6 +190,9 @@ 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
|
||||||
"""
|
"""
|
||||||
|
print('post post post post')
|
||||||
|
print('is this method are')
|
||||||
|
print('post post post post')
|
||||||
# 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()
|
||||||
|
@ -198,7 +210,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
chunk_size = min(size_remaining, max_chunk_size)
|
chunk_size = min(size_remaining, max_chunk_size)
|
||||||
L.append(self.rfile.read(chunk_size))
|
L.append(self.rfile.read(chunk_size))
|
||||||
size_remaining -= len(L[-1])
|
size_remaining -= len(L[-1])
|
||||||
data = ''.join(L)
|
data = bytes().join(L)
|
||||||
|
|
||||||
# In previous versions of SimpleXMLRPCServer, _dispatch
|
# In previous versions of SimpleXMLRPCServer, _dispatch
|
||||||
# could be overridden in this class, instead of in
|
# could be overridden in this class, instead of in
|
||||||
|
@ -239,11 +251,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
|
|
||||||
def APIAuthenticateClient(self):
|
def APIAuthenticateClient(self):
|
||||||
"""Predicate to check for valid API credentials in the request header"""
|
"""Predicate to check for valid API credentials in the request header"""
|
||||||
|
|
||||||
if 'Authorization' in self.headers:
|
if 'Authorization' in self.headers:
|
||||||
# handle Basic authentication
|
# handle Basic authentication
|
||||||
_, encstr = self.headers.get('Authorization').split()
|
_, encstr = self.headers.get('Authorization').split()
|
||||||
emailid, password = encstr.decode('base64').split(':')
|
emailid, password = b64decode(encstr).decode().split(':')
|
||||||
return (
|
return (
|
||||||
emailid == BMConfigParser().get(
|
emailid == BMConfigParser().get(
|
||||||
'bitmessagesettings', 'apiusername') and
|
'bitmessagesettings', 'apiusername') and
|
||||||
|
@ -350,11 +361,11 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
data = '{"addresses":['
|
data = '{"addresses":['
|
||||||
for row in queryreturn:
|
for row in queryreturn:
|
||||||
label, address = row
|
label, address = row
|
||||||
label = shared.fixPotentiallyInvalidUTF8Data(label)
|
# label = shared.fixPotentiallyInvalidUTF8Data(label)
|
||||||
if len(data) > 20:
|
if len(data) > 20:
|
||||||
data += ','
|
data += ','
|
||||||
data += json.dumps({
|
data += json.dumps({
|
||||||
'label': base64.b64encode(label),
|
'label': base64.b64encode(label).decode(),
|
||||||
'address': address}, indent=4, separators=(',', ': '))
|
'address': address}, indent=4, separators=(',', ': '))
|
||||||
data += ']}'
|
data += ']}'
|
||||||
return data
|
return data
|
||||||
|
@ -572,7 +583,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
|
|
||||||
def HandleGetDeterministicAddress(self, params):
|
def HandleGetDeterministicAddress(self, params):
|
||||||
"""Handle a request to get a deterministic address"""
|
"""Handle a request to get a deterministic address"""
|
||||||
|
|
||||||
if len(params) != 3:
|
if len(params) != 3:
|
||||||
raise APIError(0, 'I need exactly 3 parameters.')
|
raise APIError(0, 'I need exactly 3 parameters.')
|
||||||
passphrase, addressVersionNumber, streamNumber = params
|
passphrase, addressVersionNumber, streamNumber = params
|
||||||
|
@ -580,7 +590,7 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
eighteenByteRipe = False
|
eighteenByteRipe = False
|
||||||
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.data, "base64")
|
||||||
# if addressVersionNumber != 3 and addressVersionNumber != 4:
|
# if addressVersionNumber != 3 and addressVersionNumber != 4:
|
||||||
if addressVersionNumber not in (3, 4):
|
if addressVersionNumber not in (3, 4):
|
||||||
raise APIError(
|
raise APIError(
|
||||||
|
@ -1438,7 +1448,6 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
|
|
||||||
def HandleShutdown(self, params):
|
def HandleShutdown(self, params):
|
||||||
"""Handle a request to shutdown the node"""
|
"""Handle a request to shutdown the node"""
|
||||||
|
|
||||||
if not params:
|
if not params:
|
||||||
# backward compatible trick because False == 0 is True
|
# backward compatible trick because False == 0 is True
|
||||||
state.shutdown = False
|
state.shutdown = False
|
||||||
|
@ -1514,7 +1523,10 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
def _dispatch(self, method, params):
|
def _dispatch(self, method, params):
|
||||||
# pylint: disable=attribute-defined-outside-init
|
# pylint: disable=attribute-defined-outside-init
|
||||||
self.cookies = []
|
self.cookies = []
|
||||||
|
print('111111111111111111111')
|
||||||
|
print('inside the _dispatch')
|
||||||
|
print('print the method name are -{}'.format(method))
|
||||||
|
print('1111111111111111111111')
|
||||||
validuser = self.APIAuthenticateClient()
|
validuser = self.APIAuthenticateClient()
|
||||||
if not validuser:
|
if not validuser:
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
|
@ -1523,11 +1535,13 @@ class MySimpleXMLRPCRequestHandler(SimpleXMLRPCRequestHandler):
|
||||||
try:
|
try:
|
||||||
return self._handle_request(method, params)
|
return self._handle_request(method, params)
|
||||||
except APIError as e:
|
except APIError as e:
|
||||||
|
print('except 11111111111111111111')
|
||||||
return str(e)
|
return str(e)
|
||||||
except varintDecodeError as e:
|
except varintDecodeError as e:
|
||||||
|
print('except 222222222222222222222')
|
||||||
logger.error(e)
|
logger.error(e)
|
||||||
return "API Error 0026: Data contains a malformed varint. Some details: %s" % e
|
return "API Error 0026: Data contains a malformed varint. Some details: %s" % e
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
print('except 333333333333333333333')
|
||||||
logger.exception(e)
|
logger.exception(e)
|
||||||
|
|
||||||
return "API Error 0021: Unexpected API Failure - %s" % e
|
return "API Error 0021: Unexpected API Failure - %s" % e
|
||||||
|
|
|
@ -1406,7 +1406,9 @@ def clientStatus():
|
||||||
|
|
||||||
def shutdown():
|
def shutdown():
|
||||||
"""Shutdown the API"""
|
"""Shutdown the API"""
|
||||||
|
print('00000000000000000000000000000000000')
|
||||||
|
print('inside the the api method')
|
||||||
|
print('00000000000000000000000000000000000')
|
||||||
try:
|
try:
|
||||||
api.shutdown()
|
api.shutdown()
|
||||||
except socket.error:
|
except socket.error:
|
||||||
|
|
|
@ -33,17 +33,17 @@ try:
|
||||||
from helper_sql import sqlExecute, sqlQuery
|
from helper_sql import sqlExecute, sqlQuery
|
||||||
from inventory import Inventory
|
from inventory import Inventory
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import l10n
|
from pybitmessage import l10n
|
||||||
from ..network import stats
|
from pybitmessage.network import stats
|
||||||
from .. import queues
|
from pybitmessage import queues
|
||||||
from .. import shared
|
from pybitmessage import shared
|
||||||
from .. import shutdown
|
from pybitmessage import shutdown
|
||||||
|
|
||||||
from ..addresses import addBMIfNotPresent, decodeAddress
|
from pybitmessage.addresses import addBMIfNotPresent, decodeAddress
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from ..helper_ackPayload import genAckPayload
|
from pybitmessage.helper_ackPayload import genAckPayload
|
||||||
from ..helper_sql import sqlExecute, sqlQuery
|
from pybitmessage.helper_sql import sqlExecute, sqlQuery
|
||||||
from ..inventory import Inventory
|
from pybitmessage.inventory import Inventory
|
||||||
|
|
||||||
# pylint: disable=global-statement
|
# pylint: disable=global-statement
|
||||||
|
|
||||||
|
|
|
@ -4,7 +4,7 @@ Sql queries for bitmessagekivy
|
||||||
try:
|
try:
|
||||||
from helper_sql import sqlQuery
|
from helper_sql import sqlQuery
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..helper_sql import sqlQuery
|
from pybitmessage.helper_sql import sqlQuery
|
||||||
|
|
||||||
def search_sql(
|
def search_sql(
|
||||||
xAddress="toaddress", account=None, folder="inbox", where=None,
|
xAddress="toaddress", account=None, folder="inbox", where=None,
|
||||||
|
|
|
@ -21,11 +21,11 @@ try:
|
||||||
from bmconfigparser import BMConfigParser
|
from bmconfigparser import BMConfigParser
|
||||||
from helper_sql import sqlExecute, sqlQuery
|
from helper_sql import sqlExecute, sqlQuery
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..bitmessagekivy import identiconGeneration
|
from pybitmessage.bitmessagekivy import identiconGeneration
|
||||||
from ..bitmessagekivy import kivy_helper_search
|
from pybitmessage.bitmessagekivy import kivy_helper_search
|
||||||
from ..bitmessagekivy.uikivysignaler import UIkivySignaler
|
from pybitmessage.bitmessagekivy.uikivysignaler import UIkivySignaler
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from ..helper_sql import sqlExecute, sqlQuery
|
from pybitmessage.helper_sql import sqlExecute, sqlQuery
|
||||||
from kivymd.app import MDApp
|
from kivymd.app import MDApp
|
||||||
from kivy.clock import Clock
|
from kivy.clock import Clock
|
||||||
from kivy.core.clipboard import Clipboard
|
from kivy.core.clipboard import Clipboard
|
||||||
|
@ -81,10 +81,10 @@ try:
|
||||||
import state
|
import state
|
||||||
from addresses import decodeAddress
|
from addresses import decodeAddress
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import queues
|
from pybitmessage import queues
|
||||||
from ..semaphores import kivyuisignaler
|
from pybitmessage.semaphores import kivyuisignaler
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..addresses import decodeAddress
|
from pybitmessage.addresses import decodeAddress
|
||||||
|
|
||||||
|
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
|
@ -8,9 +8,9 @@ try:
|
||||||
import state
|
import state
|
||||||
from semaphores import kivyuisignaler
|
from semaphores import kivyuisignaler
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import queues
|
from pybitmessage import queues
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..semaphores import kivyuisignaler
|
from pybitmessage.semaphores import kivyuisignaler
|
||||||
|
|
||||||
class UIkivySignaler(Thread):
|
class UIkivySignaler(Thread):
|
||||||
"""Kivy ui signaler"""
|
"""Kivy ui signaler"""
|
||||||
|
|
|
@ -181,10 +181,14 @@ class Main(object):
|
||||||
# pylint: disable=too-many-statements,too-many-branches,too-many-locals
|
# pylint: disable=too-many-statements,too-many-branches,too-many-locals
|
||||||
_fixSocket()
|
_fixSocket()
|
||||||
adjustHalfOpenConnectionsLimit()
|
adjustHalfOpenConnectionsLimit()
|
||||||
|
|
||||||
config = BMConfigParser()
|
config = BMConfigParser()
|
||||||
daemon = config.safeGetBoolean('bitmessagesettings', 'daemon')
|
daemon = config.safeGetBoolean('bitmessagesettings', 'daemon')
|
||||||
|
print('+++++++++++++++++++++++++++++++++++++++++++++++')
|
||||||
|
print('config.safeGetBoolean(bitmessagesettings' 'daemon)-{}'.format(
|
||||||
|
config.safeGetBoolean('bitmessagesettings', 'daemon')))
|
||||||
|
print('daemon -{}'.format(daemon))
|
||||||
|
print('+++++++++++++++++++++++++++++++++++++++++++++++')
|
||||||
|
print('------------------192-------------------------')
|
||||||
try:
|
try:
|
||||||
opts, _ = getopt.getopt(
|
opts, _ = getopt.getopt(
|
||||||
sys.argv[1:], "hcdt",
|
sys.argv[1:], "hcdt",
|
||||||
|
@ -193,7 +197,7 @@ class Main(object):
|
||||||
except getopt.GetoptError:
|
except getopt.GetoptError:
|
||||||
self.usage()
|
self.usage()
|
||||||
sys.exit(2)
|
sys.exit(2)
|
||||||
|
print('------------------196-------------------------')
|
||||||
for opt, _ in opts:
|
for opt, _ in opts:
|
||||||
if opt in ("-h", "--help"):
|
if opt in ("-h", "--help"):
|
||||||
self.usage()
|
self.usage()
|
||||||
|
@ -206,7 +210,8 @@ class Main(object):
|
||||||
state.testmode = True
|
state.testmode = True
|
||||||
if os.path.isfile(os.path.join(
|
if os.path.isfile(os.path.join(
|
||||||
state.appdata, 'unittest.lock')):
|
state.appdata, 'unittest.lock')):
|
||||||
daemon = True
|
pass
|
||||||
|
# daemon = True
|
||||||
# run without a UI
|
# run without a UI
|
||||||
state.enableGUI = False
|
state.enableGUI = False
|
||||||
# Fallback: in case when no api command was issued
|
# Fallback: in case when no api command was issued
|
||||||
|
@ -222,12 +227,18 @@ class Main(object):
|
||||||
'bitmessagesettings', 'apinotifypath',
|
'bitmessagesettings', 'apinotifypath',
|
||||||
os.path.join(app_dir, 'tests', 'apinotify_handler.py')
|
os.path.join(app_dir, 'tests', 'apinotify_handler.py')
|
||||||
)
|
)
|
||||||
|
print('------------------225-------------------------')
|
||||||
|
print('+++++++++++++++++++++++++++++++++++++++++++++++')
|
||||||
|
print('config.safeGetBoolean(bitmessagesettings' 'daemon)-{}'.format(
|
||||||
|
config.safeGetBoolean('bitmessagesettings', 'daemon')))
|
||||||
|
print('daemon -{}'.format(daemon))
|
||||||
|
print('+++++++++++++++++++++++++++++++++++++++++++++++')
|
||||||
if daemon:
|
if daemon:
|
||||||
# run without a UI
|
# run without a UI
|
||||||
state.enableGUI = False
|
state.enableGUI = False
|
||||||
|
|
||||||
# is the application already running? If yes then exit.
|
# is the application already running? If yes then exit.
|
||||||
|
print('------------------232-------------------------')
|
||||||
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():
|
||||||
sys.exit(
|
sys.exit(
|
||||||
'PyBitmessage requires PyQt unless you want'
|
'PyBitmessage requires PyQt unless you want'
|
||||||
|
@ -243,7 +254,7 @@ class Main(object):
|
||||||
)
|
)
|
||||||
# is the application already running? If yes then exit.
|
# is the application already running? If yes then exit.
|
||||||
state.thisapp = singleinstance("", daemon)
|
state.thisapp = singleinstance("", daemon)
|
||||||
|
print('------------------248-------------------------')
|
||||||
if daemon:
|
if daemon:
|
||||||
with printLock:
|
with printLock:
|
||||||
print('Running as a daemon. Send TERM signal to end.')
|
print('Running as a daemon. Send TERM signal to end.')
|
||||||
|
@ -256,9 +267,11 @@ class Main(object):
|
||||||
state.dandelion = config.safeGet('network', 'dandelion')
|
state.dandelion = config.safeGet('network', 'dandelion')
|
||||||
# dandelion requires outbound connections, without them,
|
# dandelion requires outbound connections, without them,
|
||||||
# stem objects will get stuck forever
|
# stem objects will get stuck forever
|
||||||
|
print('------------------261-------------------------')
|
||||||
|
|
||||||
if state.dandelion and not (config.safeGet('bitmessagesettings', 'sendoutgoingconnections') == 'True'):
|
if state.dandelion and not (config.safeGet('bitmessagesettings', 'sendoutgoingconnections') == 'True'):
|
||||||
state.dandelion = 0
|
state.dandelion = 0
|
||||||
|
print('------------------265-------------------------')
|
||||||
if state.testmode or config.safeGetBoolean(
|
if state.testmode or config.safeGetBoolean(
|
||||||
'bitmessagesettings', 'extralowdifficulty'):
|
'bitmessagesettings', 'extralowdifficulty'):
|
||||||
defaults.networkDefaultProofOfWorkNonceTrialsPerByte = int(
|
defaults.networkDefaultProofOfWorkNonceTrialsPerByte = int(
|
||||||
|
@ -269,6 +282,7 @@ class Main(object):
|
||||||
readKnownNodes()
|
readKnownNodes()
|
||||||
|
|
||||||
# Not needed if objproc is disabled
|
# Not needed if objproc is disabled
|
||||||
|
print('------------------276-------------------------')
|
||||||
if state.enableObjProc:
|
if state.enableObjProc:
|
||||||
|
|
||||||
# Start the address generation thread
|
# Start the address generation thread
|
||||||
|
@ -276,23 +290,27 @@ class Main(object):
|
||||||
# close the main program even if there are threads left
|
# close the main program even if there are threads left
|
||||||
addressGeneratorThread.daemon = True
|
addressGeneratorThread.daemon = True
|
||||||
addressGeneratorThread.start()
|
addressGeneratorThread.start()
|
||||||
|
# set_thread_name("addressGeneratorThread")
|
||||||
# Start the thread that calculates POWs
|
# Start the thread that calculates POWs
|
||||||
singleWorkerThread = singleWorker()
|
singleWorkerThread = singleWorker()
|
||||||
# close the main program even if there are threads left
|
# close the main program even if there are threads left
|
||||||
singleWorkerThread.daemon = True
|
singleWorkerThread.daemon = True
|
||||||
singleWorkerThread.start()
|
singleWorkerThread.start()
|
||||||
|
# set_thread_name("singleWorkerThread")
|
||||||
# Start the SQL thread
|
# Start the SQL thread
|
||||||
|
print('------------------292-------------------------')
|
||||||
sqlLookup = sqlThread()
|
sqlLookup = sqlThread()
|
||||||
# DON'T close the main program even if there are threads left.
|
# DON'T close the main program even if there are threads left.
|
||||||
# The closeEvent should command this thread to exit gracefully.
|
# The closeEvent should command this thread to exit gracefully.
|
||||||
sqlLookup.daemon = False
|
sqlLookup.daemon = False
|
||||||
sqlLookup.start()
|
sqlLookup.start()
|
||||||
|
# set_thread_name("sqlLookup")
|
||||||
Inventory() # init
|
Inventory() # init
|
||||||
# init, needs to be early because other thread may access it early
|
# init, needs to be early because other thread may access it early
|
||||||
Dandelion()
|
Dandelion()
|
||||||
# Enable object processor and SMTP only if objproc enabled
|
# Enable object processor and SMTP only if objproc enabled
|
||||||
|
print('------------------303-------------------------')
|
||||||
|
|
||||||
if state.enableObjProc:
|
if state.enableObjProc:
|
||||||
# SMTP delivery thread
|
# SMTP delivery thread
|
||||||
if daemon and config.safeGet(
|
if daemon and config.safeGet(
|
||||||
|
@ -300,14 +318,14 @@ class Main(object):
|
||||||
from class_smtpDeliver import smtpDeliver
|
from class_smtpDeliver import smtpDeliver
|
||||||
smtpDeliveryThread = smtpDeliver()
|
smtpDeliveryThread = smtpDeliver()
|
||||||
smtpDeliveryThread.start()
|
smtpDeliveryThread.start()
|
||||||
|
# set_thread_name("smtpDeliveryThread")
|
||||||
# SMTP daemon thread
|
# SMTP daemon thread
|
||||||
if daemon and config.safeGetBoolean(
|
if daemon and config.safeGetBoolean(
|
||||||
'bitmessagesettings', 'smtpd'):
|
'bitmessagesettings', 'smtpd'):
|
||||||
from class_smtpServer import smtpServer
|
from class_smtpServer import smtpServer
|
||||||
smtpServerThread = smtpServer()
|
smtpServerThread = smtpServer()
|
||||||
smtpServerThread.start()
|
smtpServerThread.start()
|
||||||
|
# set_thread_name("smtpServerThread")
|
||||||
# Start the thread that calculates POWs
|
# Start the thread that calculates POWs
|
||||||
objectProcessorThread = objectProcessor()
|
objectProcessorThread = objectProcessor()
|
||||||
# DON'T close the main program even the thread remains.
|
# DON'T close the main program even the thread remains.
|
||||||
|
@ -315,12 +333,15 @@ class Main(object):
|
||||||
# each object.
|
# each object.
|
||||||
objectProcessorThread.daemon = False
|
objectProcessorThread.daemon = False
|
||||||
objectProcessorThread.start()
|
objectProcessorThread.start()
|
||||||
|
# set_thread_name("objectProcessorThread")
|
||||||
# Start the cleanerThread
|
# Start the cleanerThread
|
||||||
singleCleanerThread = singleCleaner()
|
singleCleanerThread = singleCleaner()
|
||||||
# close the main program even if there are threads left
|
# close the main program even if there are threads left
|
||||||
singleCleanerThread.daemon = True
|
singleCleanerThread.daemon = True
|
||||||
singleCleanerThread.start()
|
singleCleanerThread.start()
|
||||||
|
# set_thread_name("singleCleanerThread")
|
||||||
# Not needed if objproc disabled
|
# Not needed if objproc disabled
|
||||||
|
print('------------------335-------------------------')
|
||||||
if state.enableObjProc:
|
if state.enableObjProc:
|
||||||
shared.reloadMyAddressHashes()
|
shared.reloadMyAddressHashes()
|
||||||
shared.reloadBroadcastSendersForWhichImWatching()
|
shared.reloadBroadcastSendersForWhichImWatching()
|
||||||
|
@ -332,37 +353,48 @@ class Main(object):
|
||||||
# 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
|
||||||
singleAPIThread.start()
|
singleAPIThread.start()
|
||||||
|
# set_thread_name("singleAPIThread")
|
||||||
# start network components if networking is enabled
|
# start network components if networking is enabled
|
||||||
|
print('------------------351-------------------------')
|
||||||
if state.enableNetwork:
|
if state.enableNetwork:
|
||||||
start_proxyconfig()
|
start_proxyconfig()
|
||||||
BMConnectionPool().connectToStream(1)
|
BMConnectionPool().connectToStream(1)
|
||||||
asyncoreThread = BMNetworkThread()
|
asyncoreThread = BMNetworkThread()
|
||||||
asyncoreThread.daemon = True
|
asyncoreThread.daemon = True
|
||||||
|
# set_thread_name("asyncoreThread")
|
||||||
asyncoreThread.start()
|
asyncoreThread.start()
|
||||||
for i in range(config.safeGet('threads', 'receive')):
|
for i in range(config.safeGet('threads', 'receive')):
|
||||||
receiveQueueThread = ReceiveQueueThread(i)
|
receiveQueueThread = ReceiveQueueThread(i)
|
||||||
receiveQueueThread.daemon = True
|
receiveQueueThread.daemon = True
|
||||||
receiveQueueThread.start()
|
receiveQueueThread.start()
|
||||||
|
# set_thread_name("receiveQueueThread_{}".format(i))
|
||||||
announceThread = AnnounceThread()
|
announceThread = AnnounceThread()
|
||||||
announceThread.daemon = True
|
announceThread.daemon = True
|
||||||
announceThread.start()
|
announceThread.start()
|
||||||
|
# set_thread_name("announceThread")
|
||||||
state.invThread = InvThread()
|
state.invThread = InvThread()
|
||||||
state.invThread.daemon = True
|
state.invThread.daemon = True
|
||||||
state.invThread.start()
|
state.invThread.start()
|
||||||
|
# set_thread_name("invThread")
|
||||||
state.addrThread = AddrThread()
|
state.addrThread = AddrThread()
|
||||||
state.addrThread.daemon = True
|
state.addrThread.daemon = True
|
||||||
state.addrThread.start()
|
state.addrThread.start()
|
||||||
|
# set_thread_name("addrThread")
|
||||||
state.downloadThread = DownloadThread()
|
state.downloadThread = DownloadThread()
|
||||||
state.downloadThread.daemon = True
|
state.downloadThread.daemon = True
|
||||||
state.downloadThread.start()
|
state.downloadThread.start()
|
||||||
|
# set_thread_name("downloadThread")
|
||||||
state.uploadThread = UploadThread()
|
state.uploadThread = UploadThread()
|
||||||
state.uploadThread.daemon = True
|
state.uploadThread.daemon = True
|
||||||
state.uploadThread.start()
|
state.uploadThread.start()
|
||||||
|
# set_thread_name("downloadThread")
|
||||||
|
print('------------------383-------------------------')
|
||||||
|
|
||||||
if config.safeGetBoolean('bitmessagesettings', 'upnp'):
|
if config.safeGetBoolean('bitmessagesettings', 'upnp'):
|
||||||
import upnp
|
import upnp
|
||||||
upnpThread = upnp.uPnPThread()
|
upnpThread = upnp.uPnPThread()
|
||||||
upnpThread.start()
|
upnpThread.start()
|
||||||
|
# set_thread_name("upnpThread")
|
||||||
else:
|
else:
|
||||||
# Populate with hardcoded value (same as connectToStream above)
|
# Populate with hardcoded value (same as connectToStream above)
|
||||||
state.streamsInWhichIAmParticipating.append(1)
|
state.streamsInWhichIAmParticipating.append(1)
|
||||||
|
@ -387,6 +419,9 @@ class Main(object):
|
||||||
else:
|
else:
|
||||||
config.remove_option('bitmessagesettings', 'dontconnect')
|
config.remove_option('bitmessagesettings', 'dontconnect')
|
||||||
|
|
||||||
|
print('2222222222222222222222222222222222222222222222222222')
|
||||||
|
print('bitmessagemain is the excaution are coming to this part')
|
||||||
|
print('2222222222222222222222222222222222222222222222222222')
|
||||||
if daemon:
|
if daemon:
|
||||||
while state.shutdown == 0:
|
while state.shutdown == 0:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
@ -395,73 +430,108 @@ class Main(object):
|
||||||
and time.time() - state.last_api_response >= 30
|
and time.time() - state.last_api_response >= 30
|
||||||
):
|
):
|
||||||
self.stop()
|
self.stop()
|
||||||
elif not state.enableGUI:
|
else:
|
||||||
state.enableGUI = True
|
state.enableGUI = True
|
||||||
# pylint: disable=relative-import
|
# pylint: disable=relative-import
|
||||||
from tests import core as test_core
|
try:
|
||||||
test_core_result = test_core.run()
|
from tests import core as test_core
|
||||||
state.enableGUI = True
|
test_core_result = test_core.run()
|
||||||
self.stop()
|
state.enableGUI = True
|
||||||
test_core.cleanup()
|
self.stop()
|
||||||
sys.exit(
|
test_core.cleanup()
|
||||||
'Core tests failed!'
|
sys.exit(
|
||||||
if test_core_result.errors or test_core_result.failures
|
'Core tests failed!'
|
||||||
else 0
|
if test_core_result.errors or test_core_result.failures
|
||||||
)
|
else 0
|
||||||
|
)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def daemonize():
|
def daemonize():
|
||||||
"""Running as a daemon. Send signal in end."""
|
"""Running as a daemon. Send signal in end."""
|
||||||
|
print('---------------441-------------------')
|
||||||
grandfatherPid = os.getpid()
|
grandfatherPid = os.getpid()
|
||||||
|
print('---------------444-------------------')
|
||||||
parentPid = None
|
parentPid = None
|
||||||
try:
|
try:
|
||||||
|
print('---------------447-------------------')
|
||||||
if os.fork():
|
if os.fork():
|
||||||
# unlock
|
# unlock
|
||||||
|
print('---------------450-------------------')
|
||||||
state.thisapp.cleanup()
|
state.thisapp.cleanup()
|
||||||
|
print('---------------452-------------------')
|
||||||
# wait until grandchild ready
|
# wait until grandchild ready
|
||||||
|
print('---------------454-------------------')
|
||||||
while True:
|
while True:
|
||||||
time.sleep(1)
|
time.sleep(1)
|
||||||
|
print('---------------457-------------------')
|
||||||
os._exit(0) # pylint: disable=protected-access
|
os._exit(0) # pylint: disable=protected-access
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
# fork not implemented
|
# fork not implemented
|
||||||
|
print('---------------461-------------------')
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
|
print('---------------465-------------------')
|
||||||
parentPid = os.getpid()
|
parentPid = os.getpid()
|
||||||
|
print('---------------466-------------------')
|
||||||
state.thisapp.lock() # relock
|
state.thisapp.lock() # relock
|
||||||
|
print('---------------468-------------------')
|
||||||
|
print('---------------469-------------------')
|
||||||
os.umask(0)
|
os.umask(0)
|
||||||
try:
|
try:
|
||||||
|
print('---------------472-------------------')
|
||||||
os.setsid()
|
os.setsid()
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
# setsid not implemented
|
# setsid not implemented
|
||||||
|
print('---------------476-------------------')
|
||||||
pass
|
pass
|
||||||
try:
|
try:
|
||||||
|
print('---------------479-------------------')
|
||||||
if os.fork():
|
if os.fork():
|
||||||
# unlock
|
# unlock
|
||||||
|
print('---------------482-------------------')
|
||||||
state.thisapp.cleanup()
|
state.thisapp.cleanup()
|
||||||
|
print('---------------485-------------------')
|
||||||
# wait until child ready
|
# wait until child ready
|
||||||
while True:
|
print('---------------485-------------------')
|
||||||
time.sleep(1)
|
|
||||||
|
# while True:
|
||||||
|
# print('---------------489-------------------')
|
||||||
|
# time.sleep(1)
|
||||||
os._exit(0) # pylint: disable=protected-access
|
os._exit(0) # pylint: disable=protected-access
|
||||||
except AttributeError:
|
except AttributeError:
|
||||||
|
print('---------------493-------------------')
|
||||||
# fork not implemented
|
# fork not implemented
|
||||||
pass
|
pass
|
||||||
else:
|
else:
|
||||||
|
print('---------------497-------------------')
|
||||||
state.thisapp.lock() # relock
|
state.thisapp.lock() # relock
|
||||||
|
print('---------------499-------------------')
|
||||||
state.thisapp.lockPid = None # indicate we're the final child
|
state.thisapp.lockPid = None # indicate we're the final child
|
||||||
|
print('---------------501-------------------')
|
||||||
sys.stdout.flush()
|
sys.stdout.flush()
|
||||||
|
print('---------------502-------------------')
|
||||||
sys.stderr.flush()
|
sys.stderr.flush()
|
||||||
|
print('---------------505-------------------')
|
||||||
if not sys.platform.startswith('win'):
|
if not sys.platform.startswith('win'):
|
||||||
si = file(os.devnull, 'r')
|
si = open(os.devnull)
|
||||||
so = file(os.devnull, 'a+')
|
so = open(os.devnull, 'a+')
|
||||||
se = file(os.devnull, 'a+', 0)
|
se = open(os.devnull, 'a+')
|
||||||
os.dup2(si.fileno(), sys.stdin.fileno())
|
try:
|
||||||
os.dup2(so.fileno(), sys.stdout.fileno())
|
os.dup2(si.fileno(), sys.stdin.fileno())
|
||||||
os.dup2(se.fileno(), sys.stderr.fileno())
|
print('99999999999999999999999999999999999')
|
||||||
|
os.dup2(so.fileno(), sys.stdout.fileno())
|
||||||
|
print('8888888888888888888888888888888')
|
||||||
|
os.dup2(se.fileno(), sys.stderr.fileno())
|
||||||
|
print('777777777777777777777777777777777')
|
||||||
|
except:
|
||||||
|
pass
|
||||||
if parentPid:
|
if parentPid:
|
||||||
# signal ready
|
# signal ready
|
||||||
|
print('---------------522-------------------')
|
||||||
os.kill(parentPid, signal.SIGTERM)
|
os.kill(parentPid, signal.SIGTERM)
|
||||||
|
print('---------------524-------------------')
|
||||||
os.kill(grandfatherPid, signal.SIGTERM)
|
os.kill(grandfatherPid, signal.SIGTERM)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
|
|
|
@ -52,42 +52,43 @@ try:
|
||||||
import shutdown
|
import shutdown
|
||||||
from statusbar import BMStatusBar
|
from statusbar import BMStatusBar
|
||||||
import sound
|
import sound
|
||||||
|
import bitmessage_icons_rc # noqa:F401 pylint: disable=unused-import
|
||||||
except Exception:
|
except Exception:
|
||||||
from ..debug import logger
|
from pybitmessage.debug import logger
|
||||||
from ..tr import _translate
|
from pybitmessage.tr import _translate
|
||||||
from ..addresses import decodeAddress, addBMIfNotPresent
|
from pybitmessage.addresses import decodeAddress, addBMIfNotPresent
|
||||||
from .. import shared
|
from pybitmessage import shared
|
||||||
from .bitmessageui import Ui_MainWindow
|
from pybitmessage.bitmessageui import Ui_MainWindow
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from .. import namecoin
|
from pybitmessage import namecoin
|
||||||
from .messageview import MessageView
|
from pybitmessage.bitmessageui.messageview import MessageView
|
||||||
from .migrationwizard import Ui_MigrationWizard
|
from pybitmessage.bitmessageui.migrationwizard import Ui_MigrationWizard
|
||||||
from .foldertree import (
|
from pybitmessage.bitmessageui.foldertree import (
|
||||||
AccountMixin, Ui_FolderWidget, Ui_AddressWidget, Ui_SubscriptionWidget,
|
AccountMixin, Ui_FolderWidget, Ui_AddressWidget, Ui_SubscriptionWidget,
|
||||||
MessageList_AddressWidget, MessageList_SubjectWidget,
|
MessageList_AddressWidget, MessageList_SubjectWidget,
|
||||||
Ui_AddressBookWidgetItemLabel, Ui_AddressBookWidgetItemAddress)
|
Ui_AddressBookWidgetItemLabel, Ui_AddressBookWidgetItemAddress)
|
||||||
from . import settingsmixin
|
from pybitmessage.bitmessageui import settingsmixin
|
||||||
from . import support
|
from pybitmessage.bitmessageui import support
|
||||||
from ..helper_ackPayload import genAckPayload
|
from pybitmessage.helper_ackPayload import genAckPayload
|
||||||
from ..helper_sql import sqlQuery, sqlExecute, sqlExecuteChunked, sqlStoredProcedure
|
from pybitmessage.helper_sql import sqlQuery, sqlExecute, sqlExecuteChunked, sqlStoredProcedure
|
||||||
from .. import helper_search
|
from pybitmessage import helper_search
|
||||||
from .. import l10n
|
from pybitmessage import l10n
|
||||||
from .utils import str_broadcast_subscribers, avatarize
|
from pybitmessage.bitmessageui.utils import str_broadcast_subscribers, avatarize
|
||||||
from .account import (
|
from pybitmessage.bitmessageui.account import (
|
||||||
getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount,
|
getSortedAccounts, getSortedSubscriptions, accountClass, BMAccount,
|
||||||
GatewayAccount, MailchuckAccount, AccountColor)
|
GatewayAccount, MailchuckAccount, AccountColor)
|
||||||
from . import dialogs
|
from pybitmessage.bitmessageui.account import dialogs
|
||||||
from ..network.stats import pendingDownload, pendingUpload
|
from pybitmessage.network.stats import pendingDownload, pendingUpload
|
||||||
from .uisignaler import UISignaler
|
from pybitmessage.bitmessageui.uisignaler import UISignaler
|
||||||
from .. import paths
|
from pybitmessage import paths
|
||||||
from ..proofofwork import getPowType
|
from pybitmessage.proofofwork import getPowType
|
||||||
from .. import queues
|
from pybitmessage import queues
|
||||||
from .. import shutdown
|
from pybitmessage import shutdown
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from .statusbar import BMStatusBar
|
from pybitmessage.bitmessageui.statusbar import BMStatusBar
|
||||||
from . import sound
|
from pybitmessage.bitmessageui import sound
|
||||||
|
from pybitmessage import bitmessage_icons_rc
|
||||||
# This is needed for tray icon
|
# This is needed for tray icon
|
||||||
import bitmessage_icons_rc # noqa:F401 pylint: disable=unused-import
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from plugins.plugin import get_plugin, get_plugins
|
from plugins.plugin import get_plugin, get_plugins
|
||||||
|
|
|
@ -41,22 +41,22 @@ try:
|
||||||
from network.asyncore_pollchoose import set_rates
|
from network.asyncore_pollchoose import set_rates
|
||||||
from tr import _translate
|
from tr import _translate
|
||||||
except:
|
except:
|
||||||
from .. import debug
|
from pybitmessage import debug
|
||||||
from .. import defaults
|
from pybitmessage import defaults
|
||||||
from .. import knownnodes
|
from pybitmessage import knownnodes
|
||||||
from .. import namecoin
|
from pybitmessage import namecoin
|
||||||
from .. import openclpow
|
from pybitmessage import openclpow
|
||||||
from .. import paths
|
from pybitmessage import paths
|
||||||
from .. import queues
|
from pybitmessage import queues
|
||||||
from .. import shared
|
from pybitmessage import shared
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
# from .. import tempfile
|
# from pybitmessage import tempfile
|
||||||
# import widgets
|
# import widgets
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from ..helper_sql import sqlExecute, sqlStoredProcedure
|
from pybitmessage.helper_sql import sqlExecute, sqlStoredProcedure
|
||||||
from ..helper_startup import start_proxyconfig
|
from pybitmessage.helper_startup import start_proxyconfig
|
||||||
from ..network.asyncore_pollchoose import set_rates
|
from pybitmessage.network.asyncore_pollchoose import set_rates
|
||||||
from ..tr import _translate
|
from pybitmessage.tr import _translate
|
||||||
|
|
||||||
def getSOCKSProxyType(config):
|
def getSOCKSProxyType(config):
|
||||||
"""Get user socksproxytype setting from *config*"""
|
"""Get user socksproxytype setting from *config*"""
|
||||||
|
|
|
@ -27,22 +27,22 @@ try:
|
||||||
from version import softwareVersion
|
from version import softwareVersion
|
||||||
except:
|
except:
|
||||||
|
|
||||||
from .. import account
|
from pybitmessage import account
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from ..debug import logger
|
from pybitmessage.debug import logger
|
||||||
from .. import defaults
|
from pybitmessage import defaults
|
||||||
# from ..foldertree import AccountMixin
|
# from pybitmessage.foldertree import AccountMixin
|
||||||
from ..helper_sql import *
|
from pybitmessage.helper_sql import *
|
||||||
from ..l10n import getTranslationLanguage
|
from pybitmessage.l10n import getTranslationLanguage
|
||||||
from ..openclpow import openclAvailable, openclEnabled
|
from pybitmessage.openclpow import openclAvailable, openclEnabled
|
||||||
from .. import paths
|
from pybitmessage import paths
|
||||||
from .. import proofofwork
|
from pybitmessage import proofofwork
|
||||||
from ..pyelliptic.openssl import OpenSSL
|
from pybitmessage.pyelliptic.openssl import OpenSSL
|
||||||
from .settings import getSOCKSProxyType
|
from pybitmessage.bitmessageui.settings import getSOCKSProxyType
|
||||||
from .. import queues
|
from pybitmessage import queues
|
||||||
from ..network import stats
|
from pybitmessage.network import stats
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..version import softwareVersion
|
from pybitmessage.version import softwareVersion
|
||||||
|
|
||||||
# this is BM support address going to Peter Surda
|
# this is BM support address going to Peter Surda
|
||||||
OLD_SUPPORT_ADDRESS = 'BM-2cTkCtMYkrSPwFTpgcBrMrf5d8oZwvMZWK'
|
OLD_SUPPORT_ADDRESS = 'BM-2cTkCtMYkrSPwFTpgcBrMrf5d8oZwvMZWK'
|
||||||
|
|
|
@ -53,13 +53,13 @@ class BMConfigParser(configparser.ConfigParser):
|
||||||
# pylint: disable=too-many-ancestors
|
# pylint: disable=too-many-ancestors
|
||||||
_temp = {}
|
_temp = {}
|
||||||
|
|
||||||
def set(self, section, option, value=None):
|
def set(self, section, option, vars=None):
|
||||||
if self._optcre is self.OPTCRE or value:
|
if self._optcre is self.OPTCRE or vars:
|
||||||
if not isinstance(value, str):
|
if not isinstance(vars, str):
|
||||||
raise TypeError("option values must be strings")
|
raise TypeError("option vars must be strings")
|
||||||
if not self.validate(section, option, value):
|
if not self.validate(section, option, vars):
|
||||||
raise ValueError("Invalid value %s" % value)
|
raise ValueError("Invalid vars %s" % vars)
|
||||||
return configparser.ConfigParser.set(self, section, option, value)
|
return configparser.ConfigParser.set(self, section, option, vars)
|
||||||
|
|
||||||
def get(self, section, option, raw=False, vars=None):
|
def get(self, section, option, raw=False, vars=None):
|
||||||
# pylint: disable=unused-argument
|
# pylint: disable=unused-argument
|
||||||
|
@ -138,6 +138,10 @@ class BMConfigParser(configparser.ConfigParser):
|
||||||
return ''.join([x for x in BMConfigParser().sections() if x.startswith('BM-') and BMConfigParser().safeGetBoolean(x, 'payment')])
|
return ''.join([x for x in BMConfigParser().sections() if x.startswith('BM-') and BMConfigParser().safeGetBoolean(x, 'payment')])
|
||||||
|
|
||||||
def read(self, filenames):
|
def read(self, filenames):
|
||||||
|
# print('111111111111111111111111111111111')
|
||||||
|
# print('state.appdata-{}'.format(state.appdata))
|
||||||
|
# print('filenames-{}'.format(filenames))
|
||||||
|
# print('111111111111111111111111111111111')
|
||||||
configparser.ConfigParser.read(self, filenames)
|
configparser.ConfigParser.read(self, filenames)
|
||||||
for section in self.sections():
|
for section in self.sections():
|
||||||
for option in self.options(section):
|
for option in self.options(section):
|
||||||
|
@ -158,6 +162,11 @@ class BMConfigParser(configparser.ConfigParser):
|
||||||
continue
|
continue
|
||||||
|
|
||||||
def save(self):
|
def save(self):
|
||||||
|
# print('***********************************')
|
||||||
|
# print('22222222222222222222222222222222222')
|
||||||
|
# print('state.appdata-{}'.format(state.appdata))
|
||||||
|
# # print('filenames-{}'.format(filenames))
|
||||||
|
# print('222222222222222222222222222222222222')
|
||||||
"""Save the runtime config onto the filesystem"""
|
"""Save the runtime config onto the filesystem"""
|
||||||
fileName = os.path.join(state.appdata, 'keys.dat')
|
fileName = os.path.join(state.appdata, 'keys.dat')
|
||||||
fileNameBak = '.'.join([
|
fileNameBak = '.'.join([
|
||||||
|
|
|
@ -6,16 +6,17 @@ Used by :mod:`.bitmessageqt`.
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from helper_sql import sqlQuery
|
from helper_sql import sqlQuery
|
||||||
|
from tr import _translate
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .helper_sql import sqlQuery
|
from pybitmessage.helper_sql import sqlQuery
|
||||||
|
from pybitmessage.tr import _translate
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from PyQt4 import QtGui
|
from PyQt4 import QtGui
|
||||||
haveQt = True
|
haveQt = True
|
||||||
except ImportError:
|
except ImportError:
|
||||||
haveQt = False
|
haveQt = False
|
||||||
# pylint: disable=too-many-arguments
|
# pylint: disable=too-many-arguments
|
||||||
from helper_sql import sqlQuery
|
|
||||||
from tr import _translate
|
|
||||||
|
|
||||||
|
|
||||||
def search_sql(
|
def search_sql(
|
||||||
|
|
|
@ -7,10 +7,11 @@ try:
|
||||||
from bmconfigparser import BMConfigParser
|
from bmconfigparser import BMConfigParser
|
||||||
from singleton import Singleton
|
from singleton import Singleton
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .storage import filesystem
|
from pybitmessage import storage
|
||||||
from .storage import sqlite
|
from pybitmessage.storage import filesystem
|
||||||
from .bmconfigparser import BMConfigParser
|
from pybitmessage.storage import sqlite
|
||||||
from .singleton import Singleton
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
|
from pybitmessage.singleton import Singleton
|
||||||
|
|
||||||
|
|
||||||
@Singleton
|
@Singleton
|
||||||
|
@ -21,6 +22,7 @@ class Inventory(object):
|
||||||
"""
|
"""
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self._moduleName = BMConfigParser().safeGet("inventory", "storage")
|
self._moduleName = BMConfigParser().safeGet("inventory", "storage")
|
||||||
|
print('is I am called the Inventory')
|
||||||
self._inventoryClass = getattr(
|
self._inventoryClass = getattr(
|
||||||
getattr(storage, self._moduleName),
|
getattr(storage, self._moduleName),
|
||||||
"{}Inventory".format(self._moduleName.title())
|
"{}Inventory".format(self._moduleName.title())
|
||||||
|
|
|
@ -13,9 +13,9 @@ try:
|
||||||
from bmconfigparser import BMConfigParser
|
from bmconfigparser import BMConfigParser
|
||||||
from network.node import Peer
|
from network.node import Peer
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from . import state
|
from pybitmessage import state
|
||||||
from .bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from .network.node import Peer
|
from pybitmessage.network.node import Peer
|
||||||
|
|
||||||
knownNodesLock = threading.Lock()
|
knownNodesLock = threading.Lock()
|
||||||
"""Thread lock for knownnodes modification"""
|
"""Thread lock for knownnodes modification"""
|
||||||
|
|
14
src/main.py
14
src/main.py
|
@ -1,14 +1,18 @@
|
||||||
"""This module is for thread start."""
|
"""This module is for thread start."""
|
||||||
import state
|
|
||||||
|
|
||||||
from bitmessagemain import main
|
|
||||||
try:
|
try:
|
||||||
import state
|
import state
|
||||||
|
from bitmessagemain import main
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from . import state
|
from . import state
|
||||||
|
from .bitmessagemain import main
|
||||||
|
# import state
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == '__main__':
|
||||||
state.kivy = True
|
state.kivy = True
|
||||||
print("Kivy Loading......")
|
print("Kivy Loading......")
|
||||||
from bitmessagemain import main
|
try:
|
||||||
main()
|
from bitmessagemain import main
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
from .bitmessagemain import main
|
||||||
|
main()
|
||||||
|
|
|
@ -11,8 +11,8 @@ try:
|
||||||
import paths
|
import paths
|
||||||
|
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import messagetypes
|
from pybitmessage import messagetypes
|
||||||
from .. import paths
|
from pybitmessage import paths
|
||||||
|
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
||||||
|
|
|
@ -1,12 +1,9 @@
|
||||||
import logging
|
import logging
|
||||||
|
|
||||||
# from ..messagetypes import MsgBase
|
|
||||||
# pylint: disable=attribute-defined-outside-init
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from messagetypes import MsgBase
|
from messagetypes import MsgBase
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..messagetypes import MsgBase
|
from pybitmessage.messagetypes import MsgBase
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -2,7 +2,7 @@ import logging
|
||||||
try:
|
try:
|
||||||
from messagetypes import MsgBase
|
from messagetypes import MsgBase
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..messagetypes import MsgBase
|
from pybitmessage.messagetypes import MsgBase
|
||||||
# pylint: disable=attribute-defined-outside-init
|
# pylint: disable=attribute-defined-outside-init
|
||||||
|
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
|
@ -3,7 +3,7 @@ import logging
|
||||||
try:
|
try:
|
||||||
from messagetypes import MsgBase
|
from messagetypes import MsgBase
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..messagetypes import MsgBase
|
from pybitmessage.messagetypes import MsgBase
|
||||||
# pylint: disable=attribute-defined-outside-init
|
# pylint: disable=attribute-defined-outside-init
|
||||||
|
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
|
@ -11,16 +11,16 @@ try:
|
||||||
from network.uploadthread import UploadThread
|
from network.uploadthread import UploadThread
|
||||||
|
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..network.addrthread import AddrThread
|
from pybitmessage.network.addrthread import AddrThread
|
||||||
from ..network.announcethread import AnnounceThread
|
from pybitmessage.network.announcethread import AnnounceThread
|
||||||
from ..network.connectionpool import BMConnectionPool
|
from pybitmessage.network.connectionpool import BMConnectionPool
|
||||||
from ..network.dandelion import Dandelion
|
from pybitmessage.network.dandelion import Dandelion
|
||||||
from ..network.downloadthread import DownloadThread
|
from pybitmessage.network.downloadthread import DownloadThread
|
||||||
from ..network.invthread import InvThread
|
from pybitmessage.network.invthread import InvThread
|
||||||
from ..network.networkthread import BMNetworkThread
|
from pybitmessage.network.networkthread import BMNetworkThread
|
||||||
from ..network.receivequeuethread import ReceiveQueueThread
|
from pybitmessage.network.receivequeuethread import ReceiveQueueThread
|
||||||
from ..network.threads import StoppableThread
|
from pybitmessage.network.threads import StoppableThread
|
||||||
from ..network.uploadthread import UploadThread
|
from pybitmessage.network.uploadthread import UploadThread
|
||||||
|
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
|
|
@ -11,12 +11,12 @@ try:
|
||||||
from queues import addrQueue
|
from queues import addrQueue
|
||||||
from network.threads import StoppableThread
|
from network.threads import StoppableThread
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..helper_random import randomshuffle
|
from pybitmessage.helper_random import randomshuffle
|
||||||
from ..network.assemble import assemble_addr
|
from pybitmessage.network.assemble import assemble_addr
|
||||||
from ..network.connectionpool import BMConnectionPool
|
from pybitmessage.network.connectionpool import BMConnectionPool
|
||||||
from ..queues import addrQueue
|
from pybitmessage.queues import addrQueue
|
||||||
from ..network.threads import StoppableThread
|
from pybitmessage.network.threads import StoppableThread
|
||||||
|
|
||||||
class AddrThread(StoppableThread):
|
class AddrThread(StoppableThread):
|
||||||
"""(Node) address broadcasting thread"""
|
"""(Node) address broadcasting thread"""
|
||||||
|
|
|
@ -10,9 +10,9 @@ try:
|
||||||
import state
|
import state
|
||||||
from network.threads import BusyError, nonBlocking
|
from network.threads import BusyError, nonBlocking
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from . import asyncore_pollchoose as asyncore
|
from pybitmessage.network import asyncore_pollchoose as asyncore
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from .threads import BusyError, nonBlocking
|
from pybitmessage.network.threads import BusyError, nonBlocking
|
||||||
|
|
||||||
|
|
||||||
class ProcessingError(Exception):
|
class ProcessingError(Exception):
|
||||||
|
|
|
@ -13,13 +13,13 @@ try:
|
||||||
from network.threads import StoppableThread
|
from network.threads import StoppableThread
|
||||||
|
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from .assemble import assemble_addr
|
from pybitmessage.network.assemble import assemble_addr
|
||||||
from .connectionpool import BMConnectionPool
|
from pybitmessage.network.connectionpool import BMConnectionPool
|
||||||
from .udp import UDPSocket
|
from pybitmessage.network.udp import UDPSocket
|
||||||
from .node import Peer
|
from pybitmessage.network.node import Peer
|
||||||
from .threads import StoppableThread
|
from pybitmessage.network.threads import StoppableThread
|
||||||
|
|
||||||
|
|
||||||
class AnnounceThread(StoppableThread):
|
class AnnounceThread(StoppableThread):
|
||||||
|
|
|
@ -8,10 +8,10 @@ try:
|
||||||
from network.node import Peer
|
from network.node import Peer
|
||||||
from protocol import CreatePacket, encodeHost
|
from protocol import CreatePacket, encodeHost
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import addresses
|
from pybitmessage import addresses
|
||||||
from .constants import MAX_ADDR_COUNT
|
from pybitmessage.network.constants import MAX_ADDR_COUNT
|
||||||
from .node import Peer
|
from pybitmessage.network.node import Peer
|
||||||
from ..protocol import CreatePacket, encodeHost
|
from pybitmessage.protocol import CreatePacket, encodeHost
|
||||||
|
|
||||||
|
|
||||||
def assemble_addr(peerList):
|
def assemble_addr(peerList):
|
||||||
|
|
|
@ -22,7 +22,7 @@ from threading import current_thread
|
||||||
try:
|
try:
|
||||||
import helper_random
|
import helper_random
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import helper_random
|
from pybitmessage import helper_random
|
||||||
try:
|
try:
|
||||||
from errno import WSAEWOULDBLOCK
|
from errno import WSAEWOULDBLOCK
|
||||||
except (ImportError, AttributeError):
|
except (ImportError, AttributeError):
|
||||||
|
|
|
@ -10,11 +10,11 @@ try:
|
||||||
from inventory import Inventory
|
from inventory import Inventory
|
||||||
from network.dandelion import Dandelion
|
from network.dandelion import Dandelion
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import protocol
|
from pybitmessage import protocol
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..addresses import calculateInventoryHash
|
from pybitmessage.addresses import calculateInventoryHash
|
||||||
from ..inventory import Inventory
|
from pybitmessage.inventory import Inventory
|
||||||
from .dandelion import Dandelion
|
from pybitmessage.network.dandelion import Dandelion
|
||||||
|
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
||||||
|
|
|
@ -31,32 +31,32 @@ try:
|
||||||
from network.proxy import ProxyError
|
from network.proxy import ProxyError
|
||||||
from network.objectracker import missingObjects, ObjectTracker
|
from network.objectracker import missingObjects, ObjectTracker
|
||||||
from network.node import Node, Peer
|
from network.node import Node, Peer
|
||||||
from queues import objectProcessorQueue, portCheckerQueue, invQueue
|
|
||||||
from network.randomtrackingdict import RandomTrackingDict
|
from network.randomtrackingdict import RandomTrackingDict
|
||||||
|
from queues import objectProcessorQueue, portCheckerQueue, invQueue
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import addresses
|
from pybitmessage import addresses
|
||||||
from . import connectionpool
|
from pybitmessage.network import connectionpool
|
||||||
from .. import knownnodes
|
from pybitmessage import knownnodes
|
||||||
from .. import protocol
|
from pybitmessage import protocol
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.inventory import Inventory
|
||||||
from ..inventory import Inventory
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from .advanceddispatcher import AdvancedDispatcher
|
from pybitmessage.network.advanceddispatcher import AdvancedDispatcher
|
||||||
from .bmobject import (
|
from pybitmessage.network.bmobject import (
|
||||||
BMObject, BMObjectAlreadyHaveError, BMObjectExpiredError,
|
BMObject, BMObjectAlreadyHaveError, BMObjectExpiredError,
|
||||||
BMObjectInsufficientPOWError, BMObjectInvalidDataError,
|
BMObjectInsufficientPOWError, BMObjectInvalidDataError,
|
||||||
BMObjectInvalidError, BMObjectUnwantedStreamError
|
BMObjectInvalidError, BMObjectUnwantedStreamError
|
||||||
)
|
)
|
||||||
from .constants import (
|
from pybitmessage.network.constants import (
|
||||||
ADDRESS_ALIVE, MAX_MESSAGE_SIZE, MAX_OBJECT_COUNT,
|
ADDRESS_ALIVE, MAX_MESSAGE_SIZE, MAX_OBJECT_COUNT,
|
||||||
MAX_OBJECT_PAYLOAD_SIZE, MAX_TIME_OFFSET
|
MAX_OBJECT_PAYLOAD_SIZE, MAX_TIME_OFFSET
|
||||||
)
|
)
|
||||||
from .dandelion import Dandelion
|
from pybitmessage.network.dandelion import Dandelion
|
||||||
from .proxy import ProxyError
|
from pybitmessage.network.proxy import ProxyError
|
||||||
from .objectracker import missingObjects, ObjectTracker
|
from pybitmessage.network.objectracker import missingObjects, ObjectTracker
|
||||||
from .node import Node, Peer
|
from pybitmessage.network.node import Node, Peer
|
||||||
from ..queues import objectProcessorQueue, portCheckerQueue, invQueue
|
from pybitmessage.network.randomtrackingdict import RandomTrackingDict
|
||||||
from .randomtrackingdict import RandomTrackingDict
|
from pybitmessage.queues import objectProcessorQueue, portCheckerQueue, invQueue
|
||||||
|
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
||||||
|
|
|
@ -11,11 +11,11 @@ try:
|
||||||
from bmconfigparser import BMConfigParser
|
from bmconfigparser import BMConfigParser
|
||||||
from queues import Queue, portCheckerQueue
|
from queues import Queue, portCheckerQueue
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import knownnodes
|
from pybitmessage import knownnodes
|
||||||
from .. import protocol
|
from pybitmessage import protocol
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from ..queues import Queue, portCheckerQueue
|
from pybitmessage.queues import Queue, portCheckerQueue
|
||||||
|
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
||||||
|
|
|
@ -22,19 +22,19 @@ try:
|
||||||
from network.udp import UDPSocket
|
from network.udp import UDPSocket
|
||||||
from singleton import Singleton
|
from singleton import Singleton
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from . import asyncore_pollchoose as asyncore
|
from pybitmessage.network import asyncore_pollchoose as asyncore
|
||||||
from .. import helper_random
|
from pybitmessage import helper_random
|
||||||
from .. import knownnodes
|
from pybitmessage import knownnodes
|
||||||
from .. import protocol
|
from pybitmessage import protocol
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from .connectionchooser import chooseConnection
|
from pybitmessage.network.connectionchooser import chooseConnection
|
||||||
from .proxy import Proxy
|
from pybitmessage.network.proxy import Proxy
|
||||||
|
|
||||||
from .tcp import (
|
from pybitmessage.network.tcp import (
|
||||||
TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection, bootstrap)
|
TCPServer, Socks5BMConnection, Socks4aBMConnection, TCPConnection, bootstrap)
|
||||||
from .udp import UDPSocket
|
from pybitmessage.network.udp import UDPSocket
|
||||||
from ..singleton import Singleton
|
from pybitmessage.singleton import Singleton
|
||||||
|
|
||||||
from .node import Peer
|
from .node import Peer
|
||||||
|
|
||||||
|
|
|
@ -13,10 +13,10 @@ try:
|
||||||
from queues import invQueue
|
from queues import invQueue
|
||||||
from singleton import Singleton
|
from singleton import Singleton
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from . import connectionpool
|
from pybitmessage.network import connectionpool
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from ..queues import invQueue
|
from pybitmessage.queues import invQueue
|
||||||
from ..singleton import Singleton
|
from pybitmessage.singleton import Singleton
|
||||||
|
|
||||||
# randomise routes after 600 seconds
|
# randomise routes after 600 seconds
|
||||||
REASSIGN_INTERVAL = 600
|
REASSIGN_INTERVAL = 600
|
||||||
|
|
|
@ -14,15 +14,14 @@ try:
|
||||||
from network.threads import StoppableThread
|
from network.threads import StoppableThread
|
||||||
|
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import addresses
|
from pybitmessage import addresses
|
||||||
from .. import helper_random
|
from pybitmessage import helper_random
|
||||||
from .. import protocol
|
from pybitmessage import protocol
|
||||||
from .dandelion import Dandelion
|
from pybitmessage.network.dandelion import Dandelion
|
||||||
from ..inventory import Inventory
|
from pybitmessage.inventory import Inventory
|
||||||
from .connectionpool import BMConnectionPool
|
from pybitmessage.network.connectionpool import BMConnectionPool
|
||||||
from .objectracker import missingObjects
|
from pybitmessage.network.objectracker import missingObjects
|
||||||
#checkded this condition
|
from pybitmessage.network.threads import StoppableThread
|
||||||
from .threads import StoppableThread
|
|
||||||
|
|
||||||
|
|
||||||
class DownloadThread(StoppableThread):
|
class DownloadThread(StoppableThread):
|
||||||
|
|
|
@ -7,7 +7,7 @@ import socket
|
||||||
try:
|
try:
|
||||||
from .tls import TLSDispatcher
|
from .tls import TLSDispatcher
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..network.tls import TLSDispatcher
|
from pybitmessage.network.tls import TLSDispatcher
|
||||||
|
|
||||||
class HTTPRequestHandler(asyncore.dispatcher):
|
class HTTPRequestHandler(asyncore.dispatcher):
|
||||||
"""Handling HTTP request"""
|
"""Handling HTTP request"""
|
||||||
|
|
|
@ -13,13 +13,13 @@ try:
|
||||||
from queues import invQueue
|
from queues import invQueue
|
||||||
from network.threads import StoppableThread
|
from network.threads import StoppableThread
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import addresses
|
from pybitmessage import addresses
|
||||||
from .. import protocol
|
from pybitmessage import protocol
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from .connectionpool import BMConnectionPool
|
from pybitmessage.network.connectionpool import BMConnectionPool
|
||||||
from .dandelion import Dandelion
|
from pybitmessage.network.dandelion import Dandelion
|
||||||
from ..queues import invQueue
|
from pybitmessage.queues import invQueue
|
||||||
from .threads import StoppableThread
|
from pybitmessage.network.threads import StoppableThread
|
||||||
|
|
||||||
def handleExpiredDandelion(expired):
|
def handleExpiredDandelion(expired):
|
||||||
"""For expired dandelion objects, mark all remotes as not having
|
"""For expired dandelion objects, mark all remotes as not having
|
||||||
|
|
|
@ -8,11 +8,11 @@ try:
|
||||||
from queues import excQueue
|
from queues import excQueue
|
||||||
from network.threads import StoppableThread
|
from network.threads import StoppableThread
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from . import asyncore_pollchoose as asyncore
|
from pybitmessage.network import asyncore_pollchoose as asyncore
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from .connectionpool import BMConnectionPool
|
from pybitmessage.network.connectionpool import BMConnectionPool
|
||||||
from ..queues import excQueue
|
from pybitmessage.queues import excQueue
|
||||||
from .threads import StoppableThread
|
from pybitmessage.network.threads import StoppableThread
|
||||||
|
|
||||||
class BMNetworkThread(StoppableThread):
|
class BMNetworkThread(StoppableThread):
|
||||||
"""Main network thread"""
|
"""Main network thread"""
|
||||||
|
|
|
@ -4,13 +4,13 @@ Module for tracking objects
|
||||||
import time
|
import time
|
||||||
from threading import RLock
|
from threading import RLock
|
||||||
try:
|
try:
|
||||||
import network.connectionpool
|
from network.connectionpool import connectionpool
|
||||||
from network.dandelion import Dandelion
|
from network.dandelion import Dandelion
|
||||||
from network.randomtrackingdict import RandomTrackingDict
|
from network.randomtrackingdict import RandomTrackingDict
|
||||||
except:
|
except:
|
||||||
from . import connectionpool
|
from pybitmessage.network import connectionpool
|
||||||
from .dandelion import Dandelion
|
from pybitmessage.network.dandelion import Dandelion
|
||||||
from .randomtrackingdict import RandomTrackingDict
|
from pybitmessage.network.randomtrackingdict import RandomTrackingDict
|
||||||
|
|
||||||
haveBloom = False
|
haveBloom = False
|
||||||
|
|
||||||
|
@ -105,7 +105,7 @@ class ObjectTracker(object):
|
||||||
|
|
||||||
def handleReceivedObject(self, streamNumber, hashid):
|
def handleReceivedObject(self, streamNumber, hashid):
|
||||||
"""Handling received object"""
|
"""Handling received object"""
|
||||||
for i in network.connectionpool.BMConnectionPool().connections():
|
for i in connectionpool.BMConnectionPool().connections():
|
||||||
if not i.fullyEstablished:
|
if not i.fullyEstablished:
|
||||||
continue
|
continue
|
||||||
try:
|
try:
|
||||||
|
|
|
@ -10,13 +10,13 @@ try:
|
||||||
from network.advanceddispatcher import AdvancedDispatcher
|
from network.advanceddispatcher import AdvancedDispatcher
|
||||||
|
|
||||||
from bmconfigparser import BMConfigParser
|
from bmconfigparser import BMConfigParser
|
||||||
|
from network.node import Peer
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from . import asyncore_pollchoose as asyncore
|
from pybitmessage.network import asyncore_pollchoose as asyncore
|
||||||
from .advanceddispatcher import AdvancedDispatcher
|
from pybitmessage.network.advanceddispatcher import AdvancedDispatcher
|
||||||
|
|
||||||
from ..bmconfigparser import BMConfigParser
|
|
||||||
from .node import Peer
|
|
||||||
|
|
||||||
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
|
from pybitmessage.network.node import Peer
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -7,7 +7,7 @@ from time import time
|
||||||
try:
|
try:
|
||||||
import helper_random
|
import helper_random
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import helper_random
|
from pybitmessage import helper_random
|
||||||
class RandomTrackingDict(object):
|
class RandomTrackingDict(object):
|
||||||
"""
|
"""
|
||||||
Dict with randomised order and tracking.
|
Dict with randomised order and tracking.
|
||||||
|
|
|
@ -12,11 +12,11 @@ try:
|
||||||
from queues import receiveDataQueue
|
from queues import receiveDataQueue
|
||||||
from network.threads import StoppableThread
|
from network.threads import StoppableThread
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from .advanceddispatcher import UnknownStateError
|
from pybitmessage.network.advanceddispatcher import UnknownStateError
|
||||||
from .connectionpool import BMConnectionPool
|
from pybitmessage.network.connectionpool import BMConnectionPool
|
||||||
from ..queues import receiveDataQueue
|
from pybitmessage.queues import receiveDataQueue
|
||||||
from .threads import StoppableThread
|
from pybitmessage.network.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
|
||||||
|
|
|
@ -32,28 +32,28 @@ try:
|
||||||
from .node import Peer
|
from .node import Peer
|
||||||
from queues import UISignalQueue, invQueue, receiveDataQueue
|
from queues import UISignalQueue, invQueue, receiveDataQueue
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import addresses
|
from pybitmessage import addresses
|
||||||
from . import asyncore_pollchoose as asyncore
|
from pybitmessage import helper_random
|
||||||
from . import connectionpool
|
from pybitmessage import knownnodes
|
||||||
from .. import helper_random
|
from pybitmessage import protocol
|
||||||
from .. import knownnodes
|
from pybitmessage import shared
|
||||||
from .. import protocol
|
from pybitmessage import state
|
||||||
from .. import shared
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from .. import state
|
from pybitmessage.helper_random import randomBytes
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.inventory import Inventory
|
||||||
from ..helper_random import randomBytes
|
from pybitmessage.network import connectionpool
|
||||||
from ..inventory import Inventory
|
from pybitmessage.network import asyncore_pollchoose as asyncore
|
||||||
from .advanceddispatcher import AdvancedDispatcher
|
from pybitmessage.network.advanceddispatcher import AdvancedDispatcher
|
||||||
from .assemble import assemble_addr
|
from pybitmessage.network.assemble import assemble_addr
|
||||||
from .bmproto import BMProto
|
from pybitmessage.network.bmproto import BMProto
|
||||||
from .constants import MAX_OBJECT_COUNT
|
from pybitmessage.network.constants import MAX_OBJECT_COUNT
|
||||||
from .dandelion import Dandelion
|
from pybitmessage.network.dandelion import Dandelion
|
||||||
from .objectracker import ObjectTracker
|
from pybitmessage.network.objectracker import ObjectTracker
|
||||||
from .socks4a import Socks4aConnection
|
from pybitmessage.network.socks4a import Socks4aConnection
|
||||||
from .socks5 import Socks5Connection
|
from pybitmessage.network.socks5 import Socks5Connection
|
||||||
from .tls import TLSDispatcher
|
from pybitmessage.network.tls import TLSDispatcher
|
||||||
from .node import Peer
|
from pybitmessage.network.node import Peer
|
||||||
from ..queues import UISignalQueue, invQueue, receiveDataQueue
|
from pybitmessage.queues import UISignalQueue, invQueue, receiveDataQueue
|
||||||
# pylint: disable=logging-format-interpolation
|
# pylint: disable=logging-format-interpolation
|
||||||
|
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
|
@ -12,10 +12,10 @@ try:
|
||||||
from network.advanceddispatcher import AdvancedDispatcher
|
from network.advanceddispatcher import AdvancedDispatcher
|
||||||
from queues import receiveDataQueue
|
from queues import receiveDataQueue
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from . import asyncore_pollchoose as asyncore
|
from pybitmessage.network import asyncore_pollchoose as asyncore
|
||||||
from .. import paths
|
from pybitmessage import paths
|
||||||
from .advanceddispatcher import AdvancedDispatcher
|
from pybitmessage.network.advanceddispatcher import AdvancedDispatcher
|
||||||
from ..queues import receiveDataQueue
|
from pybitmessage.queues import receiveDataQueue
|
||||||
|
|
||||||
|
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
|
|
|
@ -9,16 +9,16 @@ try:
|
||||||
import protocol
|
import protocol
|
||||||
from network.bmproto import BMProto
|
from network.bmproto import BMProto
|
||||||
from network.objectracker import ObjectTracker
|
from network.objectracker import ObjectTracker
|
||||||
from .node import Peer
|
from network.node import Peer
|
||||||
import state
|
import state
|
||||||
from queues import receiveDataQueue
|
from queues import receiveDataQueue
|
||||||
|
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from .. import protocol
|
from pybitmessage import protocol
|
||||||
from .. import state
|
from pybitmessage import state
|
||||||
from .bmproto import BMProto
|
from pybitmessage.network.bmproto import BMProto
|
||||||
from .objectracker import ObjectTracker
|
from pybitmessage.network.objectracker import ObjectTracker
|
||||||
from .node import Peer
|
from pybitmessage.network.node import Peer
|
||||||
|
|
||||||
logger = logging.getLogger('default')
|
logger = logging.getLogger('default')
|
||||||
# pylint: disable=logging-format-interpolation
|
# pylint: disable=logging-format-interpolation
|
||||||
|
|
|
@ -14,14 +14,14 @@ try:
|
||||||
from network.threads import StoppableThread
|
from network.threads import StoppableThread
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
|
|
||||||
from .. import helper_random
|
from pybitmessage import helper_random
|
||||||
from .. import protocol
|
from pybitmessage import protocol
|
||||||
from ..inventory import Inventory
|
from pybitmessage.inventory import Inventory
|
||||||
from .connectionpool import BMConnectionPool
|
from pybitmessage.network.connectionpool import BMConnectionPool
|
||||||
from .dandelion import Dandelion
|
from pybitmessage.network.dandelion import Dandelion
|
||||||
from .randomtrackingdict import RandomTrackingDict
|
from pybitmessage.network.randomtrackingdict import RandomTrackingDict
|
||||||
from .threads import StoppableThread
|
|
||||||
|
|
||||||
|
from pybitmessage.network.threads import StoppableThread
|
||||||
class UploadThread(StoppableThread):
|
class UploadThread(StoppableThread):
|
||||||
"""
|
"""
|
||||||
This is a thread that uploads the objects that the peers requested from me
|
This is a thread that uploads the objects that the peers requested from me
|
||||||
|
|
|
@ -1,4 +1,4 @@
|
||||||
#!/usr/bin/env python2.7
|
#!/usr/bin/env python3.7
|
||||||
"""
|
"""
|
||||||
Module for Proof of Work using OpenCL
|
Module for Proof of Work using OpenCL
|
||||||
"""
|
"""
|
||||||
|
|
|
@ -48,7 +48,10 @@ def encode(val, base, minlen=0):
|
||||||
result = code_string[val % base:val % base + 1] + result
|
result = code_string[val % base:val % base + 1] + result
|
||||||
val = val // base
|
val = val // base
|
||||||
if len(result) < minlen:
|
if len(result) < minlen:
|
||||||
result = code_string[0] * (minlen - len(result)) + result
|
try:
|
||||||
|
result = code_string[0] * (minlen - len(result)) + result
|
||||||
|
except TypeError:
|
||||||
|
result = code_string[0:1] * (minlen - len(result)) + result
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|
||||||
|
@ -91,12 +94,16 @@ def base10_double(a):
|
||||||
"""Double the numbers that are of base10"""
|
"""Double the numbers that are of base10"""
|
||||||
if a is None:
|
if a is None:
|
||||||
return None
|
return None
|
||||||
m = ((3 * a[0] * a[0] + A) * inv(2 * a[1], P)) % P
|
m = int((3 * a[0] * a[0] + A) * inv(2 * a[1], P)) % P
|
||||||
x = (m * m - 2 * a[0]) % P
|
x = int(m * m - 2 * a[0]) % P
|
||||||
y = (m * (a[0] - x) - a[1]) % P
|
y = int(m * (a[0] - x) - a[1]) % P
|
||||||
|
# print('++++++++++++++++++++++++++++++++')
|
||||||
|
# print('inside the base10_double')
|
||||||
|
# print('the value of x -{}'.format(x))
|
||||||
|
# print('the value of y -{}'.format(y))
|
||||||
|
# print('++++++++++++++++++++++++++++++++')
|
||||||
return (x, y)
|
return (x, y)
|
||||||
|
|
||||||
|
|
||||||
def base10_multiply(a, n):
|
def base10_multiply(a, n):
|
||||||
"""Multiply the numbers that are of base10"""
|
"""Multiply the numbers that are of base10"""
|
||||||
if n == 0:
|
if n == 0:
|
||||||
|
@ -104,9 +111,9 @@ def base10_multiply(a, n):
|
||||||
if n == 1:
|
if n == 1:
|
||||||
return a
|
return a
|
||||||
if (n % 2) == 0:
|
if (n % 2) == 0:
|
||||||
return base10_double(base10_multiply(a, n / 2))
|
return base10_double(base10_multiply(a, n /2))
|
||||||
if (n % 2) == 1:
|
if (n % 2) == 1:
|
||||||
return base10_add(base10_double(base10_multiply(a, n / 2)), a)
|
return base10_add(base10_double(base10_multiply(a, n /2)), a)
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
@ -117,7 +124,7 @@ def hex_to_point(h):
|
||||||
|
|
||||||
def point_to_hex(p):
|
def point_to_hex(p):
|
||||||
"""Converting point value to hexadecimal"""
|
"""Converting point value to hexadecimal"""
|
||||||
return '04' + encode(p[0], 16, 64) + encode(p[1], 16, 64)
|
return '04'.encode() + encode(p[0], 16, 64) + encode(p[1], 16, 64)
|
||||||
|
|
||||||
|
|
||||||
def multiply(privkey, pubkey):
|
def multiply(privkey, pubkey):
|
||||||
|
|
|
@ -16,9 +16,9 @@ try:
|
||||||
from pyelliptic.openssl import OpenSSL
|
from pyelliptic.openssl import OpenSSL
|
||||||
|
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..pyelliptic.cipher import Cipher
|
from pybitmessage.pyelliptic.cipher import Cipher
|
||||||
from ..pyelliptic.hash import equals, hmac_sha256
|
from pybitmessage.pyelliptic.hash import equals, hmac_sha256
|
||||||
from ..pyelliptic.openssl import OpenSSL
|
from pybitmessage.pyelliptic.openssl import OpenSSL
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
|
@ -16,14 +16,14 @@ try:
|
||||||
from queues import (
|
from queues import (
|
||||||
addressGeneratorQueue, objectProcessorQueue, UISignalQueue, workerQueue)
|
addressGeneratorQueue, objectProcessorQueue, UISignalQueue, workerQueue)
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from . import shared
|
from pybitmessage import shared
|
||||||
from . import state
|
from pybitmessage import state
|
||||||
from .debug import logger
|
from pybitmessage.debug import logger
|
||||||
from .helper_sql import sqlQuery, sqlStoredProcedure
|
from pybitmessage.helper_sql import sqlQuery, sqlStoredProcedure
|
||||||
from .inventory import Inventory
|
from pybitmessage.inventory import Inventory
|
||||||
from .knownnodes import saveKnownNodes
|
from pybitmessage.knownnodes import saveKnownNodes
|
||||||
from .network import StoppableThread
|
from pybitmessage.network import StoppableThread
|
||||||
from .queues import (
|
from pybitmessage.queues import (
|
||||||
addressGeneratorQueue, objectProcessorQueue, UISignalQueue, workerQueue)
|
addressGeneratorQueue, objectProcessorQueue, UISignalQueue, workerQueue)
|
||||||
|
|
||||||
def doCleanShutdown():
|
def doCleanShutdown():
|
||||||
|
|
|
@ -11,8 +11,8 @@ try:
|
||||||
from paths import lookupAppdataFolder
|
from paths import lookupAppdataFolder
|
||||||
from storage.storage import InventoryStorage, InventoryItem
|
from storage.storage import InventoryStorage, InventoryItem
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..paths import lookupAppdataFolder
|
from pybitmessage.paths import lookupAppdataFolder
|
||||||
from ..storage.storage import InventoryStorage, InventoryItem
|
from pybitmessage.storage.storage import InventoryStorage, InventoryItem
|
||||||
|
|
||||||
class FilesystemInventory(InventoryStorage):
|
class FilesystemInventory(InventoryStorage):
|
||||||
"""Filesystem for inventory storage"""
|
"""Filesystem for inventory storage"""
|
||||||
|
|
|
@ -9,8 +9,8 @@ try:
|
||||||
from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute
|
from helper_sql import sqlQuery, SqlBulkExecute, sqlExecute
|
||||||
from storage.storage import InventoryStorage, InventoryItem
|
from storage.storage import InventoryStorage, InventoryItem
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
from ..helper_sql import sqlQuery, SqlBulkExecute, sqlExecute
|
from pybitmessage.helper_sql import sqlQuery, SqlBulkExecute, sqlExecute
|
||||||
from ..storage.storage import InventoryStorage, InventoryItem
|
from pybitmessage.storage.storage import InventoryStorage, InventoryItem
|
||||||
|
|
||||||
|
|
||||||
class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors
|
class SqliteInventory(InventoryStorage): # pylint: disable=too-many-ancestors
|
||||||
|
|
|
@ -11,51 +11,35 @@ import string
|
||||||
import time
|
import time
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
|
try:
|
||||||
|
import knownnodes
|
||||||
|
import protocol
|
||||||
|
import state
|
||||||
|
from bmconfigparser import BMConfigParser
|
||||||
|
from helper_msgcoding import MsgEncode, MsgDecode
|
||||||
|
from helper_startup import start_proxyconfig
|
||||||
|
from network import asyncore_pollchoose as asyncore
|
||||||
|
from network.bmproto import BMProto
|
||||||
|
from network.connectionpool import BMConnectionPool
|
||||||
|
from network.node import Node, Peer
|
||||||
|
from network.tcp import Socks4aBMConnection, Socks5BMConnection, TCPConnection
|
||||||
|
from queues import excQueue
|
||||||
|
from version import softwareVersion
|
||||||
|
|
||||||
from pybitmessage import knownnodes
|
except ModuleNotFoundError:
|
||||||
from pybitmessage import protocol
|
from pybitmessage import knownnodes
|
||||||
from pybitmessage import state
|
from pybitmessage import protocol
|
||||||
from pybitmessage.bmconfigparser import BMConfigParser
|
from pybitmessage import state
|
||||||
from pybitmessage.helper_msgcoding import MsgEncode, MsgDecode
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from pybitmessage.helper_startup import start_proxyconfig
|
from pybitmessage.helper_msgcoding import MsgEncode, MsgDecode
|
||||||
from pybitmessage.network import asyncore_pollchoose as asyncore
|
from pybitmessage.helper_startup import start_proxyconfig
|
||||||
from pybitmessage.network.bmproto import BMProto
|
from pybitmessage.network import asyncore_pollchoose as asyncore
|
||||||
from pybitmessage.network.connectionpool import BMConnectionPool
|
from pybitmessage.network.bmproto import BMProto
|
||||||
from pybitmessage.network.node import Node, Peer
|
from pybitmessage.network.connectionpool import BMConnectionPool
|
||||||
from pybitmessage.network.tcp import Socks4aBMConnection, Socks5BMConnection, TCPConnection
|
from pybitmessage.network.node import Peer
|
||||||
from pybitmessage.queues import excQueue
|
from pybitmessage.network.tcp import Socks4aBMConnection, Socks5BMConnection, TCPConnection
|
||||||
from pybitmessage.version import softwareVersion
|
from pybitmessage.queues import excQueue
|
||||||
|
from pybitmessage.version import softwareVersion
|
||||||
# try:
|
|
||||||
# import knownnodes
|
|
||||||
# import protocol
|
|
||||||
# import state
|
|
||||||
# from bmconfigparser import BMConfigParser
|
|
||||||
# from helper_msgcoding import MsgEncode, MsgDecode
|
|
||||||
# from helper_startup import start_proxyconfig
|
|
||||||
# from network import asyncore_pollchoose as asyncore
|
|
||||||
# from network.bmproto import BMProto
|
|
||||||
# from network.connectionpool import BMConnectionPool
|
|
||||||
# from network.node import Node, Peer
|
|
||||||
# from network.tcp import Socks4aBMConnection, Socks5BMConnection, TCPConnection
|
|
||||||
# from queues import excQueue
|
|
||||||
# from version import softwareVersion
|
|
||||||
|
|
||||||
# except ModuleNotFoundError:
|
|
||||||
# import pdb; pdb.set_trace()
|
|
||||||
# from pybitmessage import knownnodes
|
|
||||||
# from pybitmessage import protocol
|
|
||||||
# from pybitmessage import state
|
|
||||||
# from pybitmessage.bmconfigparser import BMConfigParser
|
|
||||||
# from pybitmessage.helper_msgcoding import MsgEncode, MsgDecode
|
|
||||||
# from pybitmessage.helper_startup import start_proxyconfig
|
|
||||||
# from pybitmessage.network import asyncore_pollchoose as asyncore
|
|
||||||
# from pybitmessage.network.bmproto import BMProto
|
|
||||||
# from pybitmessage.network.connectionpool import BMConnectionPool
|
|
||||||
# from pybitmessage.network.node import Peer
|
|
||||||
# from pybitmessage.network.tcp import Socks4aBMConnection, Socks5BMConnection, TCPConnection
|
|
||||||
# from pybitmessage.queues import excQueue
|
|
||||||
# from pybitmessage.version import softwareVersion
|
|
||||||
try:
|
try:
|
||||||
import stem.version as stem_version
|
import stem.version as stem_version
|
||||||
except ImportError:
|
except ImportError:
|
||||||
|
@ -145,8 +129,8 @@ class TestCore(unittest.TestCase):
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _outdate_knownnodes():
|
def _outdate_knownnodes():
|
||||||
with knownnodes.knownNodesLock:
|
with knownnodes.knownNodesLock:
|
||||||
for nodes in knownnodes.knownNodes.itervalues():
|
for nodes in iter(knownnodes.knownNodes.values()):
|
||||||
for node in nodes.itervalues():
|
for node in iter(nodes.values()):
|
||||||
node['lastseen'] -= 2419205 # older than 28 days
|
node['lastseen'] -= 2419205 # older than 28 days
|
||||||
|
|
||||||
def test_knownnodes_pickle(self):
|
def test_knownnodes_pickle(self):
|
||||||
|
@ -171,10 +155,6 @@ class TestCore(unittest.TestCase):
|
||||||
|
|
||||||
def test_0_cleaner(self):
|
def test_0_cleaner(self):
|
||||||
"""test known nodes starvation leading to IndexError in Asyncore"""
|
"""test known nodes starvation leading to IndexError in Asyncore"""
|
||||||
import sys
|
|
||||||
print('-----------------------------------------')
|
|
||||||
print(sys.version_info)
|
|
||||||
print('-----------------------------------------')
|
|
||||||
self._outdate_knownnodes()
|
self._outdate_knownnodes()
|
||||||
# time.sleep(303) # singleCleaner wakes up every 5 min
|
# time.sleep(303) # singleCleaner wakes up every 5 min
|
||||||
knownnodes.cleanupKnownNodes()
|
knownnodes.cleanupKnownNodes()
|
||||||
|
@ -268,7 +248,7 @@ class TestCore(unittest.TestCase):
|
||||||
decoded = self._decode_msg(msg, "IQQiiQlsLv")
|
decoded = self._decode_msg(msg, "IQQiiQlsLv")
|
||||||
peer, _, ua, streams = self._decode_msg(msg, "IQQiiQlsLv")[4:]
|
peer, _, ua, streams = self._decode_msg(msg, "IQQiiQlsLv")[4:]
|
||||||
self.assertEqual(peer, Node(3, '127.0.0.1', 8444))
|
self.assertEqual(peer, Node(3, '127.0.0.1', 8444))
|
||||||
self.assertEqual(ua, '/PyBitmessage:' + softwareVersion + '/')
|
self.assertEqual(ua, ('/PyBitmessage:' + softwareVersion + '/').encode())
|
||||||
self.assertEqual(streams, [1])
|
self.assertEqual(streams, [1])
|
||||||
# with multiple streams
|
# with multiple streams
|
||||||
msg = protocol.assembleVersionMessage('127.0.0.1', 8444, [1, 2, 3])
|
msg = protocol.assembleVersionMessage('127.0.0.1', 8444, [1, 2, 3])
|
||||||
|
@ -291,3 +271,4 @@ def run():
|
||||||
qt_tests = loader.loadTestsFromModule(bitmessageqt.tests)
|
qt_tests = loader.loadTestsFromModule(bitmessageqt.tests)
|
||||||
suite.addTests(qt_tests)
|
suite.addTests(qt_tests)
|
||||||
return unittest.TextTestRunner(verbosity=2).run(suite)
|
return unittest.TextTestRunner(verbosity=2).run(suite)
|
||||||
|
|
||||||
|
|
|
@ -8,7 +8,7 @@ import time
|
||||||
import xmlrpc.client as xmlrpclib # nosec
|
import xmlrpc.client as xmlrpclib # nosec
|
||||||
|
|
||||||
from .test_process import TestProcessProto, TestProcessShutdown
|
from .test_process import TestProcessProto, TestProcessShutdown
|
||||||
|
from .tests_compatibility import utils
|
||||||
|
|
||||||
class TestAPIProto(TestProcessProto):
|
class TestAPIProto(TestProcessProto):
|
||||||
"""Test case logic for testing API"""
|
"""Test case logic for testing API"""
|
||||||
|
@ -16,11 +16,15 @@ class TestAPIProto(TestProcessProto):
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def setUpClass(cls):
|
def setUpClass(cls):
|
||||||
|
print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
|
||||||
|
print('is this TestAPIProto')
|
||||||
|
print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
|
||||||
|
|
||||||
"""Setup XMLRPC proxy for pybitmessage API"""
|
"""Setup XMLRPC proxy for pybitmessage API"""
|
||||||
super(TestAPIProto, cls).setUpClass()
|
super(TestAPIProto, cls).setUpClass()
|
||||||
cls.addresses = []
|
cls.addresses = []
|
||||||
cls.api = xmlrpclib.ServerProxy(
|
cls.api = xmlrpclib.ServerProxy(
|
||||||
"http://username:password@127.0.0.1:8442/")
|
"http://username:password@127.0.0.1:8442/")
|
||||||
for _ in range(5):
|
for _ in range(5):
|
||||||
if cls._get_readline('.api_started'):
|
if cls._get_readline('.api_started'):
|
||||||
return
|
return
|
||||||
|
@ -31,6 +35,9 @@ class TestAPIShutdown(TestAPIProto, TestProcessShutdown):
|
||||||
"""Separate test case for API command 'shutdown'"""
|
"""Separate test case for API command 'shutdown'"""
|
||||||
def test_shutdown(self):
|
def test_shutdown(self):
|
||||||
"""Shutdown the pybitmessage"""
|
"""Shutdown the pybitmessage"""
|
||||||
|
# try:
|
||||||
|
# self.assertEqual(self.api.shutdown(), 'done')
|
||||||
|
# except Exception:
|
||||||
self.assertEqual(self.api.shutdown(), 'done')
|
self.assertEqual(self.api.shutdown(), 'done')
|
||||||
for _ in range(5):
|
for _ in range(5):
|
||||||
if not self.process.is_running():
|
if not self.process.is_running():
|
||||||
|
@ -38,7 +45,7 @@ class TestAPIShutdown(TestAPIProto, TestProcessShutdown):
|
||||||
time.sleep(2)
|
time.sleep(2)
|
||||||
else:
|
else:
|
||||||
self.fail(
|
self.fail(
|
||||||
'%s has not stopped in 10 sec' % ' '.join(self._process_cmd))
|
'{} has not stopped in 10 sec'.format(' '.join(self._process_cmd)))
|
||||||
|
|
||||||
|
|
||||||
class TestAPI(TestAPIProto):
|
class TestAPI(TestAPIProto):
|
||||||
|
@ -61,6 +68,10 @@ class TestAPI(TestAPIProto):
|
||||||
|
|
||||||
def test_connection(self):
|
def test_connection(self):
|
||||||
"""API command 'helloWorld'"""
|
"""API command 'helloWorld'"""
|
||||||
|
print('---------67--------------------')
|
||||||
|
print('---------68--------------------')
|
||||||
|
print('***********test_connection**********')
|
||||||
|
print('------70------------------------')
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
self.api.helloWorld('hello', 'world'),
|
self.api.helloWorld('hello', 'world'),
|
||||||
'hello-world'
|
'hello-world'
|
||||||
|
@ -122,7 +133,7 @@ class TestAPI(TestAPIProto):
|
||||||
|
|
||||||
def test_create_random_address(self):
|
def test_create_random_address(self):
|
||||||
"""API command 'createRandomAddress': basic BM-address validation"""
|
"""API command 'createRandomAddress': basic BM-address validation"""
|
||||||
addr = self._add_random_address('random_1')
|
addr = self._add_random_address('random_1'.encode())
|
||||||
self.assertRegexpMatches(addr, r'^BM-')
|
self.assertRegexpMatches(addr, r'^BM-')
|
||||||
self.assertRegexpMatches(addr[3:], r'[a-zA-Z1-9]+$')
|
self.assertRegexpMatches(addr[3:], r'[a-zA-Z1-9]+$')
|
||||||
# Whitepaper says "around 36 character"
|
# Whitepaper says "around 36 character"
|
||||||
|
@ -137,17 +148,17 @@ class TestAPI(TestAPIProto):
|
||||||
[]
|
[]
|
||||||
)
|
)
|
||||||
# Add known address
|
# Add known address
|
||||||
self.api.addAddressBookEntry(
|
self.api.addAddressBookEntry('BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK',
|
||||||
'BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK',
|
base64.encodestring(utils.encoded_string(
|
||||||
base64.encodestring('tiger_4')
|
'tiger_4')).decode())
|
||||||
)
|
|
||||||
# Check addressbook entry
|
# Check addressbook entry
|
||||||
entries = json.loads(
|
entries = json.loads(
|
||||||
self.api.listAddressBookEntries()).get('addresses')[0]
|
self.api.listAddressBookEntries()).get('addresses')[0]
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
entries['address'], 'BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK')
|
entries['address'], 'BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK')
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
base64.decodestring(entries['label']), 'tiger_4')
|
base64.decodestring(utils.encoded_string(entries['label'])),
|
||||||
|
utils.encoded_string('tiger_4'))
|
||||||
# Remove known address
|
# Remove known address
|
||||||
self.api.deleteAddressBookEntry(
|
self.api.deleteAddressBookEntry(
|
||||||
'BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK')
|
'BM-2cWzSnwjJ7yRP3nLEWUV5LisTZyREWSzUK')
|
||||||
|
@ -159,7 +170,7 @@ class TestAPI(TestAPIProto):
|
||||||
|
|
||||||
def test_send_broadcast(self):
|
def test_send_broadcast(self):
|
||||||
"""API command 'sendBroadcast': ensure it returns ackData"""
|
"""API command 'sendBroadcast': ensure it returns ackData"""
|
||||||
addr = self._add_random_address('random_2')
|
addr = self._add_random_address('random_2'.encode())
|
||||||
ack = self.api.sendBroadcast(
|
ack = self.api.sendBroadcast(
|
||||||
addr, base64.encodestring('test_subject'),
|
addr, base64.encodestring('test_subject'),
|
||||||
base64.encodestring('test message')
|
base64.encodestring('test message')
|
||||||
|
|
|
@ -37,12 +37,12 @@ class TestBlindSig(unittest.TestCase):
|
||||||
|
|
||||||
# (3) Signature Generation
|
# (3) Signature Generation
|
||||||
signature_blinded = signer_obj.blind_sign(msg_blinded)
|
signature_blinded = signer_obj.blind_sign(msg_blinded)
|
||||||
assert isinstance(signature_blinded, str)
|
assert isinstance(signature_blinded, bytes)
|
||||||
self.assertEqual(len(signature_blinded), 32)
|
self.assertEqual(len(signature_blinded), 32)
|
||||||
|
|
||||||
# (4) Extraction
|
# (4) Extraction
|
||||||
signature = requester_obj.unblind(signature_blinded)
|
signature = requester_obj.unblind(signature_blinded)
|
||||||
assert isinstance(signature, str)
|
assert isinstance(signature, bytes)
|
||||||
self.assertEqual(len(signature), 65)
|
self.assertEqual(len(signature), 65)
|
||||||
|
|
||||||
self.assertNotEqual(signature, signature_blinded)
|
self.assertNotEqual(signature, signature_blinded)
|
||||||
|
@ -164,7 +164,7 @@ class TestBlindSig(unittest.TestCase):
|
||||||
output.extend(pubkey)
|
output.extend(pubkey)
|
||||||
output.extend(signature)
|
output.extend(signature)
|
||||||
signer_obj = child_obj
|
signer_obj = child_obj
|
||||||
verifychain = ECCBlindChain(ca=ca.pubkey(), chain=str(output))
|
verifychain = ECCBlindChain(ca=ca.pubkey(), chain=bytes(output))
|
||||||
self.assertTrue(verifychain.verify(msg=msg, value=1))
|
self.assertTrue(verifychain.verify(msg=msg, value=1))
|
||||||
|
|
||||||
def test_blind_sig_chain_wrong_ca(self): # pylint: disable=too-many-locals
|
def test_blind_sig_chain_wrong_ca(self): # pylint: disable=too-many-locals
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
Test for chatmsg group
|
Test for chatmsg group
|
||||||
"""
|
"""
|
||||||
import unittest
|
import unittest
|
||||||
from ..messagetypes.chatmsg import Chatmsg
|
from pybitmessage.messagetypes.chatmsg import Chatmsg
|
||||||
|
|
||||||
|
|
||||||
class TestCharMessage(unittest.TestCase):
|
class TestCharMessage(unittest.TestCase):
|
||||||
|
@ -10,14 +10,14 @@ class TestCharMessage(unittest.TestCase):
|
||||||
Test case for chat message group
|
Test case for chat message group
|
||||||
"""
|
"""
|
||||||
|
|
||||||
# def test_decode(self):
|
def test_decode(self):
|
||||||
# """Test various types of decode method"""
|
"""Test various types of decode method"""
|
||||||
# from .. import messagetypes
|
from pybitmessage import messagetypes
|
||||||
# result = messagetypes.constructObject({'': 'chatmsg', 'message': 'hello world'})
|
result = messagetypes.constructObject({'': 'chatmsg', 'message': 'hello world'})
|
||||||
# self.assertTrue(isinstance(result.message, str))
|
self.assertTrue(isinstance(result.message, str))
|
||||||
|
|
||||||
# def test_encode(self):
|
def test_encode(self):
|
||||||
# """Test various types of encode method"""
|
"""Test various types of encode method"""
|
||||||
# chat_obj = Chatmsg()
|
chat_obj = Chatmsg()
|
||||||
# result = chat_obj.encode({'message': 'hello world'})
|
result = chat_obj.encode({'message': 'hello world'})
|
||||||
# self.assertTrue(True if result['message'] else False)
|
self.assertTrue(True if result['message'] else False)
|
||||||
|
|
|
@ -5,8 +5,8 @@ Various tests for config
|
||||||
import os
|
import os
|
||||||
import unittest
|
import unittest
|
||||||
|
|
||||||
from ..bmconfigparser import BMConfigParser
|
from pybitmessage.bmconfigparser import BMConfigParser
|
||||||
from .test_process import TestProcessProto
|
from pybitmessage.tests.test_process import TestProcessProto
|
||||||
|
|
||||||
|
|
||||||
class TestConfig(unittest.TestCase):
|
class TestConfig(unittest.TestCase):
|
||||||
|
@ -45,8 +45,9 @@ class TestProcessConfig(TestProcessProto):
|
||||||
"""Test settings in the generated config"""
|
"""Test settings in the generated config"""
|
||||||
self._stop_process()
|
self._stop_process()
|
||||||
config = BMConfigParser()
|
config = BMConfigParser()
|
||||||
|
print('the value of the self.home')
|
||||||
|
print(self.home)
|
||||||
config.read(os.path.join(self.home, 'keys.dat'))
|
config.read(os.path.join(self.home, 'keys.dat'))
|
||||||
|
|
||||||
self.assertEqual(config.safeGetInt(
|
self.assertEqual(config.safeGetInt(
|
||||||
'bitmessagesettings', 'settingsversion'), 10)
|
'bitmessagesettings', 'settingsversion'), 10)
|
||||||
self.assertEqual(config.safeGetInt(
|
self.assertEqual(config.safeGetInt(
|
||||||
|
|
|
@ -74,9 +74,8 @@ class TestAddresses(unittest.TestCase):
|
||||||
"""Test addresses manipulations"""
|
"""Test addresses manipulations"""
|
||||||
def test_privtopub(self):
|
def test_privtopub(self):
|
||||||
"""Generate public keys and check the result"""
|
"""Generate public keys and check the result"""
|
||||||
import pdb; pdb.set_trace()
|
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
arithmetic.privtopub(sample_privatesigningkey),
|
arithmetic.privtopub(sample_privatesigningkey.encode()),
|
||||||
hexlify(sample_pubsigningkey)
|
hexlify(sample_pubsigningkey)
|
||||||
)
|
)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
|
@ -93,7 +92,6 @@ class TestAddresses(unittest.TestCase):
|
||||||
sha.update(sample_pubsigningkey + sample_pubencryptionkey)
|
sha.update(sample_pubsigningkey + sample_pubencryptionkey)
|
||||||
ripe_hash = RIPEMD160Hash(sha.digest()).digest()
|
ripe_hash = RIPEMD160Hash(sha.digest()).digest()
|
||||||
self.assertEqual(ripe_hash, unhexlify(sample_ripe))
|
self.assertEqual(ripe_hash, unhexlify(sample_ripe))
|
||||||
|
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
addresses.encodeAddress(2, 1, ripe_hash), sample_address)
|
addresses.encodeAddress(2, 1, ripe_hash), sample_address)
|
||||||
|
|
||||||
|
|
|
@ -2,7 +2,7 @@
|
||||||
Test for network group
|
Test for network group
|
||||||
"""
|
"""
|
||||||
import unittest
|
import unittest
|
||||||
from .tests_compatibility.utils import encoded_string
|
from pybitmessage.tests.tests_compatibility.utils import encoded_string
|
||||||
|
|
||||||
class TestNetworkGroup(unittest.TestCase):
|
class TestNetworkGroup(unittest.TestCase):
|
||||||
"""
|
"""
|
||||||
|
@ -11,7 +11,7 @@ class TestNetworkGroup(unittest.TestCase):
|
||||||
def test_network_group(self):
|
def test_network_group(self):
|
||||||
"""Test various types of network groups"""
|
"""Test various types of network groups"""
|
||||||
# pylint: disable=import-error
|
# pylint: disable=import-error
|
||||||
from ..protocol import network_group
|
from pybitmessage.protocol import network_group
|
||||||
|
|
||||||
test_ip = '1.2.3.4'
|
test_ip = '1.2.3.4'
|
||||||
self.assertEqual(encoded_string('\x01\x02'), network_group(test_ip))
|
self.assertEqual(encoded_string('\x01\x02'), network_group(test_ip))
|
||||||
|
|
|
@ -49,6 +49,6 @@ class TestOpenSSL(unittest.TestCase):
|
||||||
c = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(a))
|
c = OpenSSL.malloc(0, OpenSSL.BN_num_bytes(a))
|
||||||
OpenSSL.BN_bn2binpad(a, b, OpenSSL.BN_num_bytes(n))
|
OpenSSL.BN_bn2binpad(a, b, OpenSSL.BN_num_bytes(n))
|
||||||
OpenSSL.BN_bn2bin(a, c)
|
OpenSSL.BN_bn2bin(a, c)
|
||||||
if b.raw != c.raw.rjust(OpenSSL.BN_num_bytes(n), chr(0)):
|
if b.raw != c.raw.rjust(OpenSSL.BN_num_bytes(n), bytes(1)):
|
||||||
bad += 1
|
bad += 1
|
||||||
self.assertEqual(bad, 0)
|
self.assertEqual(bad, 0)
|
||||||
|
|
|
@ -17,30 +17,35 @@ except ModuleNotFoundError:
|
||||||
|
|
||||||
def put_signal_file(path, filename):
|
def put_signal_file(path, filename):
|
||||||
"""Creates file, presence of which is a signal about some event."""
|
"""Creates file, presence of which is a signal about some event."""
|
||||||
with open(os.path.join(path, filename), 'w') as outfile:
|
with open(os.path.join(path, filename), 'wb') as outfile:
|
||||||
outfile.write( str(time.time()))
|
outfile.write(str(time.time()).encode())
|
||||||
|
print('************************************************')
|
||||||
|
with open(os.path.join(path, filename), 'r') as outfile:
|
||||||
|
print(outfile.read())
|
||||||
|
print('************************************************')
|
||||||
|
|
||||||
class TestProcessProto(unittest.TestCase):
|
class TestProcessProto(unittest.TestCase):
|
||||||
"""Test case implementing common logic for external testing:
|
"""Test case implementing common logic for external testing:
|
||||||
it starts pybitmessage in setUpClass() and stops it in tearDownClass()
|
it starts pybitmessage in setUpClass() and stops it in tearDownClass()
|
||||||
"""
|
"""
|
||||||
_process_cmd = ['pybitmessage', '-d']
|
_process_cmd = ['pybitmessage', '-d']
|
||||||
_threads_count = 15
|
_threads_count = 15
|
||||||
|
'''
|
||||||
|
debug.log is removed because debug.log are pending to implement on the
|
||||||
|
python3
|
||||||
|
'''
|
||||||
_files = (
|
_files = (
|
||||||
'keys.dat', 'debug.log', 'messages.dat', 'knownnodes.dat',
|
'keys.dat', 'messages.dat', 'knownnodes.dat',
|
||||||
'.api_started', 'unittest.lock'
|
'.api_started', 'unittest.lock'
|
||||||
)
|
)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def setUpClass(cls):
|
def setUpClass(cls):
|
||||||
"""Setup environment and start pybitmessage"""
|
"""Setup environment and start pybitmessage"""
|
||||||
|
|
||||||
cls.home = os.environ['BITMESSAGE_HOME'] = tempfile.gettempdir()
|
cls.home = os.environ['BITMESSAGE_HOME'] = tempfile.gettempdir()
|
||||||
put_signal_file(cls.home, 'unittest.lock')
|
put_signal_file(cls.home, 'unittest.lock')
|
||||||
try:
|
subprocess.call(cls._process_cmd) # nosec
|
||||||
subprocess.call(cls._process_cmd) # nosec
|
|
||||||
except FileNotFoundError:
|
|
||||||
subprocess.call([os.getcwd().rsplit('/',1)[0] + '/pybitmessage','-d'])
|
|
||||||
time.sleep(5)
|
time.sleep(5)
|
||||||
cls.pid = int(cls._get_readline('singleton.lock'))
|
cls.pid = int(cls._get_readline('singleton.lock'))
|
||||||
cls.process = psutil.Process(cls.pid)
|
cls.process = psutil.Process(cls.pid)
|
||||||
|
@ -132,7 +137,7 @@ class TestProcess(TestProcessProto):
|
||||||
continue
|
continue
|
||||||
self.assertIsNot(
|
self.assertIsNot(
|
||||||
self._get_readline(pfile), None,
|
self._get_readline(pfile), None,
|
||||||
'Failed to read file %s' % pfile
|
'Failed to read file {}'.format(pfile)
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_threads(self):
|
def test_threads(self):
|
||||||
|
|
Reference in New Issue
Block a user