Add some error handling

This commit is contained in:
Arinerron 2018-04-18 19:16:10 -07:00
parent ded179bcad
commit 1332e9ee9e
No known key found for this signature in database
GPG Key ID: 99383627861C62F0
2 changed files with 130 additions and 99 deletions

View File

@ -36,6 +36,7 @@ class Core:
''' '''
Initialize Core Onionr library Initialize Core Onionr library
''' '''
try:
self.queueDB = 'data/queue.db' self.queueDB = 'data/queue.db'
self.peerDB = 'data/peers.db' self.peerDB = 'data/peers.db'
self.blockDB = 'data/blocks.db' self.blockDB = 'data/blocks.db'
@ -57,7 +58,10 @@ class Core:
self._utils = onionrutils.OnionrUtils(self) self._utils = onionrutils.OnionrUtils(self)
# Initialize the crypto object # Initialize the crypto object
self._crypto = onionrcrypto.OnionrCrypto(self) self._crypto = onionrcrypto.OnionrCrypto(self)
except Exception as error:
logger.error('Failed to initialize core Onionr library.', error=error)
logger.fatal('Cannot recover from error.')
exit(1)
return return
def addPeer(self, peerID, name=''): def addPeer(self, peerID, name=''):

View File

@ -41,15 +41,19 @@ class OnionrUtils:
return return
def getTimeBypassToken(self): def getTimeBypassToken(self):
try:
if os.path.exists('data/time-bypass.txt'): if os.path.exists('data/time-bypass.txt'):
with open('data/time-bypass.txt', 'r') as bypass: with open('data/time-bypass.txt', 'r') as bypass:
self.timingToken = bypass.read() self.timingToken = bypass.read()
except Exception as error:
logger.error('Failed to fetch time bypass token.', error=error)
def sendPM(self, pubkey, message): def sendPM(self, pubkey, message):
''' '''
High level function to encrypt a message to a peer and insert it as a block High level function to encrypt a message to a peer and insert it as a block
''' '''
try:
encrypted = self._core._crypto.pubKeyEncrypt(message, pubkey, anonymous=True, encodedData=True).decode() encrypted = self._core._crypto.pubKeyEncrypt(message, pubkey, anonymous=True, encodedData=True).decode()
block = self._core.insertBlock(encrypted, header='pm') block = self._core.insertBlock(encrypted, header='pm')
@ -57,6 +61,8 @@ class OnionrUtils:
logger.error('Could not send PM') logger.error('Could not send PM')
else: else:
logger.info('Sent PM, hash: ' + block) logger.info('Sent PM, hash: ' + block)
except Exception as error:
logger.error('Failed to send PM.', error=error)
return return
@ -80,6 +86,7 @@ class OnionrUtils:
''' '''
Merge ed25519 key list to our database Merge ed25519 key list to our database
''' '''
try:
retVal = False retVal = False
if newKeyList != False: if newKeyList != False:
for key in newKeyList.split(','): for key in newKeyList.split(','):
@ -87,12 +94,16 @@ class OnionrUtils:
if self._core.addPeer(key): if self._core.addPeer(key):
retVal = True retVal = True
return retVal return retVal
except Exception as error:
logger.error('Failed to merge keys.', error=error)
return False
def mergeAdders(self, newAdderList): def mergeAdders(self, newAdderList):
''' '''
Merge peer adders list to our database Merge peer adders list to our database
''' '''
try:
retVal = False retVal = False
if newAdderList != False: if newAdderList != False:
for adder in newAdderList.split(','): for adder in newAdderList.split(','):
@ -104,12 +115,20 @@ class OnionrUtils:
else: else:
logger.debug(adder + " is either our address or already in our DB") logger.debug(adder + " is either our address or already in our DB")
return retVal return retVal
except Exception as error:
logger.error('Failed to merge adders.', error=error)
return False
def getMyAddress(self): def getMyAddress(self):
try:
myAddressFile = open("data/hs/hostname", 'r') myAddressFile = open("data/hs/hostname", 'r')
myAddress = myAddressFile.read() myAddress = myAddressFile.read()
myAddressFile.close() myAddressFile.close()
return myAddress.strip() return myAddress.strip()
except Exception as error:
logger.error('Failed to read my address.', error=error)
return ''
def localCommand(self, command): def localCommand(self, command):
''' '''
@ -121,7 +140,8 @@ class OnionrUtils:
# TODO: URL encode parameters, just as an extra measure. May not be needed, but should be added regardless. # TODO: URL encode parameters, just as an extra measure. May not be needed, but should be added regardless.
try: try:
retData = requests.get('http://' + open('data/host.txt', 'r').read() + ':' + str(config.get('client')['port']) + '/client/?action=' + command + '&token=' + str(config.get('client')['client_hmac']) + '&timingToken=' + self.timingToken).text retData = requests.get('http://' + open('data/host.txt', 'r').read() + ':' + str(config.get('client')['port']) + '/client/?action=' + command + '&token=' + str(config.get('client')['client_hmac']) + '&timingToken=' + self.timingToken).text
except requests.ConnectionError: except Exception as error:
logger.error('Failed to make local request (command: ' + str(command) + ').', error=error)
retData = False retData = False
return retData return retData
@ -179,6 +199,7 @@ class OnionrUtils:
''' '''
Return a sha3_256 hash of the blocks DB Return a sha3_256 hash of the blocks DB
''' '''
try:
with open(self._core.blockDB, 'rb') as data: with open(self._core.blockDB, 'rb') as data:
data = data.read() data = data.read()
hasher = hashlib.sha3_256() hasher = hashlib.sha3_256()
@ -186,6 +207,8 @@ class OnionrUtils:
dataHash = hasher.hexdigest() dataHash = hasher.hexdigest()
return dataHash return dataHash
except Exception as error:
logger.error('Failed to get block DB hash.', error=error)
def hasBlock(self, hash): def hasBlock(self, hash):
''' '''
@ -224,7 +247,9 @@ class OnionrUtils:
return retVal return retVal
def validatePubKey(self, key): def validatePubKey(self, key):
'''Validate if a string is a valid base32 encoded Ed25519 key''' '''
Validate if a string is a valid base32 encoded Ed25519 key
'''
retVal = False retVal = False
try: try:
nacl.signing.SigningKey(seed=key, encoder=nacl.encoding.Base32Encoder) nacl.signing.SigningKey(seed=key, encoder=nacl.encoding.Base32Encoder)
@ -241,6 +266,7 @@ class OnionrUtils:
''' '''
Validate if an address is a valid tor or i2p hidden service Validate if an address is a valid tor or i2p hidden service
''' '''
try:
idLength = len(id) idLength = len(id)
retVal = True retVal = True
idNoDomain = '' idNoDomain = ''
@ -280,6 +306,8 @@ class OnionrUtils:
retVal = False retVal = False
return retVal return retVal
except:
return False
def loadPMs(self): def loadPMs(self):
''' '''
@ -298,8 +326,7 @@ class OnionrUtils:
try: try:
message = self._core._crypto.pubKeyDecrypt(message.replace('-pm-', ''), encodedData=True, anonymous=True) message = self._core._crypto.pubKeyDecrypt(message.replace('-pm-', ''), encodedData=True, anonymous=True)
except nacl.exceptions.CryptoError as e: except nacl.exceptions.CryptoError as e:
#logger.debug('Unable to decrypt ' + i) logger.debug('Unable to decrypt ' + i, error=e)
#logger.debug(str(e))
pass pass
else: else:
logger.info('Recieved message: ' + message.decode()) logger.info('Recieved message: ' + message.decode())