Added conditions for API test cases

This commit is contained in:
jai.s 2020-08-30 00:23:30 +05:30
parent 6bbe8ef22a
commit 53d46dbdf0
No known key found for this signature in database
GPG Key ID: 360CFA25EFC67D12
11 changed files with 115 additions and 105 deletions

View File

@ -183,12 +183,8 @@ class Main(object):
adjustHalfOpenConnectionsLimit() adjustHalfOpenConnectionsLimit()
config = BMConfigParser() config = BMConfigParser()
daemon = config.safeGetBoolean('bitmessagesettings', 'daemon') daemon = config.safeGetBoolean('bitmessagesettings', 'daemon')
print('+++++++++++++++++++++++++++++++++++++++++++++++')
print('config.safeGetBoolean(bitmessagesettings' 'daemon)-{}'.format( print('config.safeGetBoolean(bitmessagesettings' 'daemon)-{}'.format(
config.safeGetBoolean('bitmessagesettings', 'daemon'))) 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",
@ -197,7 +193,6 @@ 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()
@ -210,8 +205,7 @@ 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')):
pass daemon = True
# 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
@ -227,18 +221,12 @@ 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-------------------------') config.safeGetBoolean('bitmessagesettings', 'daemon')
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'
@ -254,7 +242,6 @@ 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.')
@ -266,12 +253,9 @@ 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(
@ -282,7 +266,6 @@ 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
@ -298,7 +281,6 @@ class Main(object):
singleWorkerThread.start() singleWorkerThread.start()
# set_thread_name("singleWorkerThread") # 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.
@ -309,8 +291,6 @@ class Main(object):
# 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(
@ -341,7 +321,6 @@ class Main(object):
singleCleanerThread.start() singleCleanerThread.start()
# set_thread_name("singleCleanerThread") # 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()
@ -355,7 +334,6 @@ class Main(object):
singleAPIThread.start() singleAPIThread.start()
# set_thread_name("singleAPIThread") # 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)
@ -388,7 +366,6 @@ class Main(object):
state.uploadThread.daemon = True state.uploadThread.daemon = True
state.uploadThread.start() state.uploadThread.start()
# set_thread_name("downloadThread") # set_thread_name("downloadThread")
print('------------------383-------------------------')
if config.safeGetBoolean('bitmessagesettings', 'upnp'): if config.safeGetBoolean('bitmessagesettings', 'upnp'):
import upnp import upnp
@ -418,10 +395,7 @@ class Main(object):
# bitmessageqt.run() # bitmessageqt.run()
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)
@ -450,88 +424,58 @@ class Main(object):
@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
print('---------------485-------------------')
# while True: # while True:
# print('---------------489-------------------') # print('---------------489-------------------')
# time.sleep(1) # 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
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 = open(os.devnull) si = open(os.devnull)
so = open(os.devnull, 'a+') so = open(os.devnull, 'a+')
se = open(os.devnull, 'a+') se = open(os.devnull, 'a+')
try: try:
os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(si.fileno(), sys.stdin.fileno())
print('99999999999999999999999999999999999')
os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(so.fileno(), sys.stdout.fileno())
print('8888888888888888888888888888888')
os.dup2(se.fileno(), sys.stderr.fileno()) os.dup2(se.fileno(), sys.stderr.fileno())
print('777777777777777777777777777777777')
except: except:
pass 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

View File

@ -4,6 +4,7 @@ A thread for creating addresses
import hashlib import hashlib
import time import time
from binascii import hexlify from binascii import hexlify
import threading
try: try:
import defaults import defaults
import highlevelcrypto import highlevelcrypto
@ -19,6 +20,7 @@ try:
from network.threads import StoppableThread from network.threads import StoppableThread
except ModuleNotFoundError: except ModuleNotFoundError:
from pybitmessage import defaults from pybitmessage import defaults
from pybitmessage.debug import logger
from pybitmessage import highlevelcrypto from pybitmessage import highlevelcrypto
from pybitmessage import queues from pybitmessage import queues
from pybitmessage import shared from pybitmessage import shared
@ -50,7 +52,12 @@ class addressGenerator(StoppableThread):
# pylint: disable=too-many-locals, too-many-branches # pylint: disable=too-many-locals, too-many-branches
# pylint: disable=protected-access, too-many-statements # pylint: disable=protected-access, too-many-statements
while state.shutdown == 0: while state.shutdown == 0:
logger.info('&&&&&&&&&&&&&&&&&&&&&&&')
logger.info('inside the class_addressGenerator\n')
logger.info('current thread -{}'.format(threading.current_thread().name))
queueValue = queues.addressGeneratorQueue.get() queueValue = queues.addressGeneratorQueue.get()
logger.info('$$$$$$$$$$$$ queueValue $$$$$$$$$$$$-{}'.format(queueValue))
logger.info('&&&&&&&&&&&&&&&&&&&&&&&')
nonceTrialsPerByte = 0 nonceTrialsPerByte = 0
payloadLengthExtraBytes = 0 payloadLengthExtraBytes = 0
live = True live = True
@ -85,6 +92,9 @@ class addressGenerator(StoppableThread):
# the default # the default
numberOfNullBytesDemandedOnFrontOfRipeHash = 1 numberOfNullBytesDemandedOnFrontOfRipeHash = 1
elif len(queueValue) == 9: elif len(queueValue) == 9:
logger.info('&&&&&&&&&&&&&&&&&&&&&&&')
logger.info('---------94--------------')
logger.info('&&&&&&&&&&&&&&&&&&&&&&&\n')
command, addressVersionNumber, streamNumber, label, \ command, addressVersionNumber, streamNumber, label, \
numberOfAddressesToMake, deterministicPassphrase, \ numberOfAddressesToMake, deterministicPassphrase, \
eighteenByteRipe, nonceTrialsPerByte, \ eighteenByteRipe, nonceTrialsPerByte, \
@ -102,9 +112,12 @@ class addressGenerator(StoppableThread):
# the default # the default
numberOfNullBytesDemandedOnFrontOfRipeHash = 1 numberOfNullBytesDemandedOnFrontOfRipeHash = 1
elif queueValue[0] == 'stopThread': elif queueValue[0] == 'stopThread':
logger.info('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
logger.info('queueValue[0] == stopThread is this condition are true')
logger.info('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')
break break
else: else:
self.logger.error( self.logger.info(
'Programming error: A structure with the wrong number' 'Programming error: A structure with the wrong number'
' of values was passed into the addressGeneratorQueue.' ' of values was passed into the addressGeneratorQueue.'
' Here is the queueValue: %r\n', queueValue) ' Here is the queueValue: %r\n', queueValue)
@ -132,6 +145,9 @@ class addressGenerator(StoppableThread):
queues.UISignalQueue.put(( queues.UISignalQueue.put((
'updateStatusBar', "" 'updateStatusBar', ""
)) ))
logger.info('&&&&&&&&&&&&&&&&&&&&&&&')
logger.info('---------144--------------')
logger.info('&&&&&&&&&&&&&&&&&&&&&&&\n')
# This next section is a little bit strange. We're going # This next section is a little bit strange. We're going
# to generate keys over and over until we find one # to generate keys over and over until we find one
# that starts with either \x00 or \x00\x00. Then when # that starts with either \x00 or \x00\x00. Then when
@ -142,6 +158,9 @@ class addressGenerator(StoppableThread):
potentialPrivSigningKey = OpenSSL.rand(32) potentialPrivSigningKey = OpenSSL.rand(32)
potentialPubSigningKey = highlevelcrypto.pointMult( potentialPubSigningKey = highlevelcrypto.pointMult(
potentialPrivSigningKey) potentialPrivSigningKey)
logger.info('&&&&&&&&&&&&&&&&&&&&&&&')
logger.info('---------157--------------')
logger.info('&&&&&&&&&&&&&&&&&&&&&&&\n')
while True: while True:
numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1 numberOfAddressesWeHadToMakeBeforeWeFoundOneWithTheCorrectRipePrefix += 1
potentialPrivEncryptionKey = OpenSSL.rand(32) potentialPrivEncryptionKey = OpenSSL.rand(32)
@ -156,6 +175,9 @@ class addressGenerator(StoppableThread):
'\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash '\x00'.encode('utf-8') * numberOfNullBytesDemandedOnFrontOfRipeHash
): ):
break break
logger.info('&&&&&&&&&&&&&&&&&&&&&&&')
logger.info('---------174--------------')
logger.info('&&&&&&&&&&&&&&&&&&&&&&&\n')
self.logger.info( self.logger.info(
'Generated address with ripe digest: %s', hexlify(ripe)) 'Generated address with ripe digest: %s', hexlify(ripe))
try: try:
@ -170,20 +192,22 @@ class addressGenerator(StoppableThread):
# The user must have a pretty fast computer. # The user must have a pretty fast computer.
# time.time() - startTime equaled zero. # time.time() - startTime equaled zero.
pass pass
logger.info('&&&&&&&&&&&&&&&&&&&&&&&')
logger.info('---------191--------------')
logger.info('&&&&&&&&&&&&&&&&&&&&&&&\n')
address = encodeAddress( address = encodeAddress(
addressVersionNumber, streamNumber, ripe) addressVersionNumber, streamNumber, ripe)
# An excellent way for us to store our keys # An excellent way for us to store our keys
# is in Wallet Import Format. Let us convert now. # is in Wallet Import Format. Let us convert now.
# https://en.bitcoin.it/wiki/Wallet_import_format # https://en.bitcoin.it/wiki/Wallet_import_format
privSigningKey = '\x80'.encode('utf-8')[1:] + potentialPrivSigningKey privSigningKey = '\x80'.encode('raw_unicode_escape') + potentialPrivSigningKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privSigningKey).digest()).digest()[0:4] privSigningKey).digest()).digest()[0:4]
privSigningKeyWIF = arithmetic.changebase( privSigningKeyWIF = arithmetic.changebase(
privSigningKey + checksum, 256, 58) privSigningKey + checksum, 256, 58)
privEncryptionKey = '\x80'.encode('utf-8')[1:] + potentialPrivEncryptionKey privEncryptionKey = '\x80'.encode('raw_unicode_escape') + potentialPrivEncryptionKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privEncryptionKey).digest()).digest()[0:4] privEncryptionKey).digest()).digest()[0:4]
privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKeyWIF = arithmetic.changebase(
@ -267,13 +291,13 @@ class addressGenerator(StoppableThread):
# An excellent way for us to store our keys # An excellent way for us to store our keys
# is in Wallet Import Format. Let us convert now. # is in Wallet Import Format. Let us convert now.
# https://en.bitcoin.it/wiki/Wallet_import_format # https://en.bitcoin.it/wiki/Wallet_import_format
privSigningKey = '\x80'.encode('utf-8')[1:] + potentialPrivSigningKey privSigningKey ='\x80'.encode('raw_unicode_escape') + potentialPrivSigningKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privSigningKey).digest()).digest()[0:4] privSigningKey).digest()).digest()[0:4]
privSigningKeyWIF = arithmetic.changebase( privSigningKeyWIF = arithmetic.changebase(
privSigningKey + checksum, 256, 58) privSigningKey + checksum, 256, 58)
privEncryptionKey = '\x80'.encode('utf-8')[1:] + potentialPrivEncryptionKey privEncryptionKey ='\x80'.encode('raw_unicode_escape') + potentialPrivEncryptionKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privEncryptionKey).digest()).digest()[0:4] privEncryptionKey).digest()).digest()[0:4]
privEncryptionKeyWIF = arithmetic.changebase( privEncryptionKeyWIF = arithmetic.changebase(
@ -333,7 +357,7 @@ class addressGenerator(StoppableThread):
# We fill out this list no matter what although we only # We fill out this list no matter what although we only
# need it if we end up passing the info to the API. # need it if we end up passing the info to the API.
listOfNewAddressesToSendOutThroughTheAPI = [] listOfNewAddressesToSendOutThroughTheAPI = []
logger
for _ in range(numberOfAddressesToMake): for _ in range(numberOfAddressesToMake):
# This next section is a little bit strange. We're # This next section is a little bit strange. We're
# going to generate keys over and over until we find # going to generate keys over and over until we find
@ -365,7 +389,7 @@ class addressGenerator(StoppableThread):
ripe = RIPEMD160Hash(sha.digest()).digest() ripe = RIPEMD160Hash(sha.digest()).digest()
if ( if (
ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] == ripe[:numberOfNullBytesDemandedOnFrontOfRipeHash] ==
'\x00' * numberOfNullBytesDemandedOnFrontOfRipeHash '\x00'.encode() * numberOfNullBytesDemandedOnFrontOfRipeHash
): ):
break break
@ -402,13 +426,13 @@ class addressGenerator(StoppableThread):
# An excellent way for us to store our keys is # An excellent way for us to store our keys is
# in Wallet Import Format. Let us convert now. # in Wallet Import Format. Let us convert now.
# https://en.bitcoin.it/wiki/Wallet_import_format # https://en.bitcoin.it/wiki/Wallet_import_format
privSigningKey = '\x80' + potentialPrivSigningKey privSigningKey = '\x80'.encode('raw_unicode_escape') + potentialPrivSigningKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privSigningKey).digest()).digest()[0:4] privSigningKey).digest()).digest()[0:4]
privSigningKeyWIF = arithmetic.changebase( privSigningKeyWIF = arithmetic.changebase(
privSigningKey + checksum, 256, 58) privSigningKey + checksum, 256, 58)
privEncryptionKey = '\x80' + \ privEncryptionKey = '\x80'.encode('raw_unicode_escape') + \
potentialPrivEncryptionKey potentialPrivEncryptionKey
checksum = hashlib.sha256(hashlib.sha256( checksum = hashlib.sha256(hashlib.sha256(
privEncryptionKey).digest()).digest()[0:4] privEncryptionKey).digest()).digest()[0:4]
@ -502,6 +526,8 @@ class addressGenerator(StoppableThread):
elif command == 'getDeterministicAddress': elif command == 'getDeterministicAddress':
queues.apiAddressGeneratorReturnQueue.put(address) queues.apiAddressGeneratorReturnQueue.put(address)
else: else:
logger.info("Error in the addressGenerator thread. Thread was" +
" given a command it could not understand:{} " .format(command))
raise Exception( raise Exception(
"Error in the addressGenerator thread. Thread was" + "Error in the addressGenerator thread. Thread was" +
" given a command it could not understand: " + command) " given a command it could not understand: " + command)

View File

@ -278,7 +278,7 @@ class singleWorker(StoppableThread):
TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300)) TTL = int(28 * 24 * 60 * 60 + helper_random.randomrandrange(-300, 300))
embeddedTime = int(time.time() + TTL) embeddedTime = int(time.time() + TTL)
payload = pack('>Q', (embeddedTime)) payload = pack('>Q', (embeddedTime))
payload += '\x00\x00\x00\x01' # object type: pubkey payload += '\x00\x00\x00\x01'.encode() # object type: pubkey
payload += encodeVarint(addressVersionNumber) # Address version number payload += encodeVarint(addressVersionNumber) # Address version number
payload += encodeVarint(streamNumber) payload += encodeVarint(streamNumber)
# bitfield of features supported by me (see the wiki). # bitfield of features supported by me (see the wiki).
@ -352,7 +352,7 @@ class singleWorker(StoppableThread):
# expiresTime time. # expiresTime time.
payload = pack('>Q', (embeddedTime)) payload = pack('>Q', (embeddedTime))
payload += '\x00\x00\x00\x01' # object type: pubkey payload += '\x00\x00\x00\x01'.encode() # object type: pubkey
payload += encodeVarint(addressVersionNumber) # Address version number payload += encodeVarint(addressVersionNumber) # Address version number
payload += encodeVarint(streamNumber) payload += encodeVarint(streamNumber)
# bitfield of features supported by me (see the wiki). # bitfield of features supported by me (see the wiki).

View File

@ -52,8 +52,7 @@ helper_startup.loadConfig()
# logging.config.fileConfig interface # logging.config.fileConfig interface
# examples are here: # examples are here:
# https://bitmessage.org/forum/index.php/topic,4820.msg11163.html#msg11163 # https://bitmessage.org/forum/index.php/topic,4820.msg11163.html#msg11163
log_level = 'WARNING' log_level = 'INFO'
def log_uncaught_exceptions(ex_cls, ex, tb): def log_uncaught_exceptions(ex_cls, ex, tb):
"""The last resort logging function used for sys.excepthook""" """The last resort logging function used for sys.excepthook"""
@ -69,14 +68,19 @@ def configureLogging():
sys.excepthook = log_uncaught_exceptions sys.excepthook = log_uncaught_exceptions
fail_msg = '' fail_msg = ''
try: try:
logging_config = os.path.join(state.appdata, 'logging.dat') logger = logging.getLogger(state.appdata+'/logging.dat')
logging.config.fileConfig( logger.setLevel(logging.DEBUG)
logging_config, disable_existing_loggers=False) # create console handler and set level to debug
return ( logging_streamHandler = logging.StreamHandler()
False, logging_streamHandler.setLevel(logging.DEBUG)
'Loaded logger configuration from %s' % logging_config # create formatter
) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# add formatter to ch
logging_streamHandler.setFormatter(formatter)
# add ch to logger
logger.addHandler(logging_streamHandler)
except (OSError, configparser.NoSectionError): except (OSError, configparser.NoSectionError):
logging_config = os.path.join(state.appdata, 'logging.dat')
if os.path.isfile(logging_config): if os.path.isfile(logging_config):
fail_msg = \ fail_msg = \
'Failed to load logger configuration from %s, using default' \ 'Failed to load logger configuration from %s, using default' \
@ -142,23 +146,14 @@ def resetLogging():
"""Reconfigure logging in runtime when state.appdata dir changed""" """Reconfigure logging in runtime when state.appdata dir changed"""
# pylint: disable=global-statement, used-before-assignment # pylint: disable=global-statement, used-before-assignment
global logger global logger
try: for i in logger.handlers:
for i in logger.handlers: logger.removeHandler(i)
logger.removeHandler(i) i.flush()
iresetLogging.flush() i.close()
i.close() configureLogging()
configureLogging()
except:
pass
logger = logging.getLogger('default') logger = logging.getLogger('default')
preconfigured, msg = configureLogging()
# !
try:
preconfigured, msg = configureLogging()
if msg:
logger.log(logging.WARNING if preconfigured else logging.INFO, msg)
except:
pass
logger = logging.getLogger('default') logger = logging.getLogger('default')
if msg:
logger.log(logging.WARNING if preconfigured else logging.INFO, msg)

View File

@ -40,6 +40,8 @@ def sqlQuery(sqlStatement, *args):
sqlSubmitQueue.put('') sqlSubmitQueue.put('')
elif isinstance(args[0], (list, tuple)): elif isinstance(args[0], (list, tuple)):
sqlSubmitQueue.put(args[0]) sqlSubmitQueue.put(args[0])
elif isinstance(args[0], memoryview):
sqlSubmitQueue.put(bytes(args[0]))
else: else:
sqlSubmitQueue.put(args) sqlSubmitQueue.put(args)
queryreturn, _ = sqlReturnQueue.get() queryreturn, _ = sqlReturnQueue.get()

View File

@ -1,8 +1,12 @@
# pylint: disable=missing-docstring # pylint: disable=missing-docstring
import asyncore import asyncore
from .http import HttpConnection try:
from .tls import TLSDispatcher from .http import HttpConnection
from .tls import TLSDispatcher
except:
from pybitmessage.network.http import HttpConnection
from pybitmessage.network.tls import TLSDispatcher
""" """
self.sslSock = ssl.wrap_socket( self.sslSock = ssl.wrap_socket(
self.sock, self.sock,

View File

@ -8,7 +8,7 @@ import struct
try: try:
from network.proxy import Proxy, ProxyError, GeneralProxyError from network.proxy import Proxy, ProxyError, GeneralProxyError
except ModuleNotFoundError: except ModuleNotFoundError:
from .proxy import Proxy, ProxyError, GeneralProxyError from pybitmessage.network.proxy import Proxy, ProxyError, GeneralProxyError
class Socks4aError(ProxyError): class Socks4aError(ProxyError):

View File

@ -131,3 +131,8 @@ thisapp = None
"""Singleton instance""" """Singleton instance"""
imageDir = None imageDir = None
import tempfile
import os
tmp = os.environ['BITMESSAGE_HOME'] = tempfile.gettempdir()
log_file = os.path.join(tmp, 'debuging.log')
dst = open(log_file,'a')

View File

@ -10,6 +10,7 @@ import xmlrpc.client as xmlrpclib # nosec
from .test_process import TestProcessProto, TestProcessShutdown from .test_process import TestProcessProto, TestProcessShutdown
from .tests_compatibility import utils from .tests_compatibility import utils
from pybitmessage.debug import logger
class TestAPIProto(TestProcessProto): class TestAPIProto(TestProcessProto):
"""Test case logic for testing API""" """Test case logic for testing API"""
_process_cmd = ['pybitmessage', '-t'] _process_cmd = ['pybitmessage', '-t']
@ -49,6 +50,9 @@ class TestAPIShutdown(TestAPIProto, TestProcessShutdown):
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():
logger.info('-----------------------------------------')
logger.info('test_shutdown test_shutdown test_shutdown inside the break condition')
logger.info('-----------------------------------------')
break break
time.sleep(2) time.sleep(2)
else: else:
@ -139,6 +143,7 @@ class TestAPI(TestAPIProto):
r'API Error 0003:' r'API Error 0003:'
) )
#currently working on this condition
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'.encode()) addr = self._add_random_address('random_1'.encode())

View File

@ -58,10 +58,10 @@ handlers=default
except ImportError: except ImportError:
self.fail('There is no package pybitmessage. Things gone wrong.') self.fail('There is no package pybitmessage. Things gone wrong.')
finally: finally:
os.remove(log_config) pass
# os.remove(log_config)
logger_ = logging.getLogger('default') logger_ = logging.getLogger('default')
self.assertEqual(logger, logger_) self.assertEqual(logger, logger_)
logger_.info('Testing the logger...') logger_.info('Testing the logger...')
self.assertRegex(open(log_file).read(), pattern) self.assertRegex(open(log_file).read(), pattern)

View File

@ -31,7 +31,7 @@ class TestProcessProto(unittest.TestCase):
_process_cmd = ['pybitmessage', '-d'] _process_cmd = ['pybitmessage', '-d']
_threads_count = 15 _threads_count = 15
_files = ( _files = (
'keys.dat', 'debug.log', 'messages.dat', 'knownnodes.dat', 'keys.dat', 'messages.dat', 'knownnodes.dat',
'.api_started', 'unittest.lock','singleton.lock' '.api_started', 'unittest.lock','singleton.lock'
) )
@ -65,8 +65,38 @@ class TestProcessProto(unittest.TestCase):
@classmethod @classmethod
def _cleanup_files(cls): def _cleanup_files(cls):
print('the printing _cleanup_files -{}'.format(cls._files))
for pfile in cls._files: for pfile in cls._files:
try: try:
if pfile == 'debug.log':
print('***************************')
print('72727272727272772727272727')
print('going to open the debug.log file-{}'.format(pfile))
print(os.path.join(cls.home, pfile))
print('75757575757575757575757')
import pdb; pdb.set_trace()
try:
with open(os.path.join(cls.home, pfile), 'r') as outfile:
print(outfile.readlines())
print('with with with with ')
print('is coming inside the open function')
print('with with with with ')
except:
print('!!!!!!!!!!!!!!!!!!!!!!!!!')
print('expectation are occured ')
print('!!!!!!!!!!!!!!!!!!!!!!!!!')
print('***************************')
print('----------------------------')
print(' pfile pfile pfile -{}'.format(pfile))
try:
with open(os.path.join(cls.home, pfile), 'r') as outfile:
pass
# print(outfile.read())
print('----------------------------')
except:
print('``````````````````````````````````````')
print('exceptation are occured while working opening th file-{}'.format(pfile))
print('``````````````````````````````````````')
os.remove(os.path.join(cls.home, pfile)) os.remove(os.path.join(cls.home, pfile))
except OSError: except OSError:
pass pass
@ -79,7 +109,6 @@ class TestProcessProto(unittest.TestCase):
print('######################################') print('######################################')
try: try:
if not cls._stop_process(): if not cls._stop_process():
print(open(os.path.join(cls.home, 'debug.log'), 'rb').read())
cls.process.kill() cls.process.kill()
except (psutil.NoSuchProcess, FileNotFoundError, AttributeError) as e: except (psutil.NoSuchProcess, FileNotFoundError, AttributeError) as e:
pass pass