Merge branch 'crypto' of github.com:beardog108/onionr into crypto

This commit is contained in:
Kevin Froman 2018-04-18 21:03:59 -05:00
commit 417b2d7a79
9 changed files with 86 additions and 71 deletions

View File

@ -215,7 +215,7 @@ class API:
return resp return resp
if not os.environ.get("WERKZEUG_RUN_MAIN") == "true": if not os.environ.get("WERKZEUG_RUN_MAIN") == "true":
logger.info('Starting client on ' + self.host + ':' + str(bindPort) + '...') logger.info('Starting client on ' + self.host + ':' + str(bindPort) + '...', timestamp=True)
try: try:
app.run(host=self.host, port=bindPort, debug=True, threaded=True) app.run(host=self.host, port=bindPort, debug=True, threaded=True)

View File

@ -41,4 +41,4 @@ if __name__ == "__main__":
bitcoin = OnionrBTC(torPort) bitcoin = OnionrBTC(torPort)
while True: while True:
print(bitcoin.node.getBlockHash(bitcoin.node.getLastBlockHeight())) # Using print on purpose, do not change to logger print(bitcoin.node.getBlockHash(bitcoin.node.getLastBlockHeight())) # Using print on purpose, do not change to logger
time.sleep(5) time.sleep(5)

View File

@ -36,12 +36,12 @@ class OnionrCommunicate:
self.highFailureAmount = 7 self.highFailureAmount = 7
''' '''
logger.info('Starting Bitcoin Node... with Tor socks port:' + str(sys.argv[2])) logger.info('Starting Bitcoin Node... with Tor socks port:' + str(sys.argv[2]), timestamp=True)
try: try:
self.bitcoin = btc.OnionrBTC(torP=int(sys.argv[2])) self.bitcoin = btc.OnionrBTC(torP=int(sys.argv[2]))
except _gdbm.error: except _gdbm.error:
pass pass
logger.info('Bitcoin Node started, on block: ' + self.bitcoin.node.getBlockHash(self.bitcoin.node.getLastBlockHeight())) logger.info('Bitcoin Node started, on block: ' + self.bitcoin.node.getBlockHash(self.bitcoin.node.getLastBlockHeight()), timestamp=True)
''' '''
#except: #except:
#logger.fatal('Failed to start Bitcoin Node, exiting...') #logger.fatal('Failed to start Bitcoin Node, exiting...')
@ -89,16 +89,16 @@ class OnionrCommunicate:
blockProcessTimer = 0 blockProcessTimer = 0
if command != False: if command != False:
if command[0] == 'shutdown': if command[0] == 'shutdown':
logger.info('Daemon recieved exit command.') logger.info('Daemon recieved exit command.', timestamp=True)
break break
elif command[0] == 'anounceNode': elif command[0] == 'anounceNode':
announceAmount = 1 announceAmount = 1
announceVal = False announceVal = False
for i in command[1]: for i in command[1]:
logger.info('Announcing our node to ' + command[1][i]) logger.info('Announcing our node to ' + command[1][i], timestamp=True)
while not announceVal: while not announceVal:
announceVal = self.performGet('announce', command[1][i], data=self._core.hsAdder, skipHighFailureAddress=True) announceVal = self.performGet('announce', command[1][i], data=self._core.hsAdder, skipHighFailureAddress=True)
time.sleep(1) time.sleep(1)
return return
@ -123,14 +123,14 @@ class OnionrCommunicate:
while peersCheck > peersChecked: while peersCheck > peersChecked:
i = random.randint(0, maxN) i = random.randint(0, maxN)
logger.info('Using ' + peerList[i] + ' to find new peers') logger.info('Using ' + peerList[i] + ' to find new peers', timestamp=True)
try: try:
newAdders = self.performGet('pex', peerList[i], skipHighFailureAddress=True) newAdders = self.performGet('pex', peerList[i], skipHighFailureAddress=True)
logger.debug('Attempting to merge address: ') logger.debug('Attempting to merge address: ')
logger.debug(newAdders) logger.debug(newAdders)
self._utils.mergeAdders(newAdders) self._utils.mergeAdders(newAdders)
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
logger.info(peerList[i] + ' connection failed') logger.info(peerList[i] + ' connection failed', timestamp=True)
continue continue
else: else:
try: try:
@ -141,7 +141,7 @@ class OnionrCommunicate:
# TODO: Require keys to come with POW token (very large amount of POW) # TODO: Require keys to come with POW token (very large amount of POW)
self._utils.mergeKeys(newKeys) self._utils.mergeKeys(newKeys)
except requests.exceptions.ConnectionError: except requests.exceptions.ConnectionError:
logger.info(peerList[i] + ' connection failed') logger.info(peerList[i] + ' connection failed', timestamp=True)
continue continue
else: else:
peersChecked += 1 peersChecked += 1
@ -226,7 +226,7 @@ class OnionrCommunicate:
self._core.setData(data) self._core.setData(data)
if data.startswith('-txt-'): if data.startswith('-txt-'):
self._core.setBlockType(hash, 'txt') self._core.setBlockType(hash, 'txt')
logger.info('Successfully obtained data for ' + hash) logger.info('Successfully obtained data for ' + hash, timestamp=True)
if len(data) < 120: if len(data) < 120:
logger.debug('Block text:\n' + data) logger.debug('Block text:\n' + data)
else: else:

View File

@ -24,12 +24,12 @@ class OnionrCryptoTests(unittest.TestCase):
crypto = onionrcrypto.OnionrCrypto(myCore) crypto = onionrcrypto.OnionrCrypto(myCore)
key = key = b"tttttttttttttttttttttttttttttttt" key = key = b"tttttttttttttttttttttttttttttttt"
logger.info("Encrypting: " + dataString) logger.info("Encrypting: " + dataString, timestamp=True)
encrypted = crypto.symmetricEncrypt(dataString, key, returnEncoded=True) encrypted = crypto.symmetricEncrypt(dataString, key, returnEncoded=True)
logger.info(encrypted) logger.info(encrypted, timestamp=True)
logger.info('Decrypting encrypted string:') logger.info('Decrypting encrypted string:', timestamp=True)
decrypted = crypto.symmetricDecrypt(encrypted, key, encodedMessage=True) decrypted = crypto.symmetricDecrypt(encrypted, key, encodedMessage=True)
logger.info(decrypted) logger.info(decrypted, timestamp=True)
self.assertTrue(True) self.assertTrue(True)
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()

View File

@ -141,11 +141,11 @@ def log(prefix, data, color = '', timestamp=True):
data : The actual data to output data : The actual data to output
color : The color to output before the data color : The color to output before the data
''' '''
curTime = ''
if timestamp: if timestamp:
curTime = time.strftime("%m-%d %H:%M:%S") curTime = time.strftime("%m-%d %H:%M:%S") + ' '
else:
curTime = '' output = colors.reset + str(color) + '[' + colors.bold + str(prefix) + colors.reset + str(color) + '] ' + curTime + str(data) + colors.reset
output = colors.reset + str(color) + '[' + colors.bold + str(prefix) + colors.reset + str(color) + '] ' + curTime + ' ' + str(data) + colors.reset
if not get_settings() & USE_ANSI: if not get_settings() & USE_ANSI:
output = colors.filter(output) output = colors.filter(output)
@ -201,26 +201,28 @@ def confirm(default = 'y', message = 'Are you sure %s? '):
return default == 'y' return default == 'y'
# debug: when there is info that could be useful for debugging purposes only # debug: when there is info that could be useful for debugging purposes only
def debug(data): def debug(data, timestamp=True):
if get_level() <= LEVEL_DEBUG: if get_level() <= LEVEL_DEBUG:
log('/', data) log('/', data, timestamp=timestamp)
# info: when there is something to notify the user of, such as the success of a process # info: when there is something to notify the user of, such as the success of a process
def info(data): def info(data, timestamp=False):
if get_level() <= LEVEL_INFO: if get_level() <= LEVEL_INFO:
log('+', data, colors.fg.green) log('+', data, colors.fg.green, timestamp=timestamp)
# warn: when there is a potential for something bad to happen # warn: when there is a potential for something bad to happen
def warn(data): def warn(data, timestamp=True):
if get_level() <= LEVEL_WARN: if get_level() <= LEVEL_WARN:
log('!', data, colors.fg.orange) log('!', data, colors.fg.orange, timestamp=timestamp)
# error: when only one function, module, or process of the program encountered a problem and must stop # error: when only one function, module, or process of the program encountered a problem and must stop
def error(data): def error(data, error=None, timestamp=True):
if get_level() <= LEVEL_ERROR: if get_level() <= LEVEL_ERROR:
log('-', data, colors.fg.red) log('-', data, colors.fg.red, timestamp=timestamp)
if not error is None:
debug('Error details: ' + str(error))
# fatal: when the something so bad has happened that the prorgam must stop # fatal: when the something so bad has happened that the prorgam must stop
def fatal(data): def fatal(data, timestamp=True):
if get_level() <= LEVEL_FATAL: if get_level() <= LEVEL_FATAL:
log('#', data, colors.bg.red + colors.fg.green + colors.bold) log('#', data, colors.bg.red + colors.fg.green + colors.bold, timestamp=timestamp)

View File

@ -97,7 +97,7 @@ HiddenServicePort 80 127.0.0.1:''' + str(self.hsPort) + '''
logger.fatal('Failed to start Tor. Try killing any other Tor processes owned by this user.') logger.fatal('Failed to start Tor. Try killing any other Tor processes owned by this user.')
return False return False
logger.info('Finished starting Tor') logger.info('Finished starting Tor', timestamp=True)
self.readyState = True self.readyState = True
myID = open('data/hs/hostname', 'r') myID = open('data/hs/hostname', 'r')

View File

@ -158,6 +158,8 @@ class Onionr:
'addpeer': self.addPeer, 'addpeer': self.addPeer,
'add-peer': self.addPeer, 'add-peer': self.addPeer,
'add-address': self.addAddress, 'add-address': self.addAddress,
'add-addr': self.addAddress,
'addaddr': self.addAddress,
'addaddress': self.addAddress, 'addaddress': self.addAddress,
'connect': self.addAddress 'connect': self.addAddress
@ -173,12 +175,12 @@ class Onionr:
'enable-plugin': 'Enables and starts a plugin', 'enable-plugin': 'Enables and starts a plugin',
'disable-plugin': 'Disables and stops a plugin', 'disable-plugin': 'Disables and stops a plugin',
'reload-plugin': 'Reloads a plugin', 'reload-plugin': 'Reloads a plugin',
'list-peers': 'Displays a list of peers',
'add-peer': 'Adds a peer (?)', 'add-peer': 'Adds a peer (?)',
'list-peers': 'Displays a list of peers',
'add-msg': 'Broadcasts a message to the Onionr network', 'add-msg': 'Broadcasts a message to the Onionr network',
'pm': 'Adds a private message to block', 'pm': 'Adds a private message to block',
'gui': 'Opens a graphical interface for Onionr', 'get-pms': 'Shows private messages sent to you',
'getpms': 'Shows private messages sent to you' 'gui': 'Opens a graphical interface for Onionr'
} }
command = '' command = ''
@ -300,7 +302,7 @@ class Onionr:
''' '''
Adds a peer (?) Adds a peer (?)
''' '''
try: try:
newPeer = sys.argv[2] newPeer = sys.argv[2]
except: except:
@ -312,7 +314,9 @@ class Onionr:
return return
def addAddress(self): def addAddress(self):
'''Adds a Onionr node address''' '''
Adds a Onionr node address
'''
try: try:
newAddress = sys.argv[2] newAddress = sys.argv[2]
except: except:
@ -320,9 +324,9 @@ class Onionr:
else: else:
logger.info("Adding address: " + logger.colors.underline + newAddress) logger.info("Adding address: " + logger.colors.underline + newAddress)
if self.onionrCore.addAddress(newAddress): if self.onionrCore.addAddress(newAddress):
logger.info("Successfully added address") logger.info("Successfully added address.")
else: else:
logger.warn("Unable to add address") logger.warn("Unable to add address.")
return return
@ -342,7 +346,7 @@ class Onionr:
self.onionrCore.setBlockType(addedHash, 'txt') self.onionrCore.setBlockType(addedHash, 'txt')
return return
def getPMs(self): def getPMs(self):
''' '''
display PMs sent to us display PMs sent to us

View File

@ -47,10 +47,10 @@ class POW:
if iFound: if iFound:
endTime = math.floor(time.time()) endTime = math.floor(time.time())
if self.reporting: if self.reporting:
logger.info('Found token ' + token) logger.info('Found token ' + token, timestamp=True)
logger.info('took ' + str(endTime - startTime)) logger.info('took ' + str(endTime - startTime), timestamp=True)
self.result = token self.result = token
def __init__(self, difficulty, bitcoinNode): def __init__(self, difficulty, bitcoinNode):
self.foundHash = False self.foundHash = False
self.difficulty = difficulty self.difficulty = difficulty
@ -72,7 +72,7 @@ class POW:
def shutdown(self): def shutdown(self):
self.hashing = False self.hashing = False
self.puzzle = '' self.puzzle = ''
def changeDifficulty(self, newDiff): def changeDifficulty(self, newDiff):
self.difficulty = newDiff self.difficulty = newDiff
@ -83,4 +83,4 @@ class POW:
except AttributeError: except AttributeError:
retVal = False retVal = False
self.result = False self.result = False
return retVal return retVal

View File

@ -39,19 +39,17 @@ class OnionrUtils:
self.timingToken = '' self.timingToken = ''
return return
def getTimeBypassToken(self): def getTimeBypassToken(self):
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()
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
'''
#forwardKey = self._core.getPeerInfo(pubkey, 'forwardKey')
#if self._core.getPeerInfo(pubkey, 'pubkeyExchanged') == 1:
# pass
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')
@ -61,21 +59,27 @@ class OnionrUtils:
logger.info('Sent PM, hash: ' + block) logger.info('Sent PM, hash: ' + block)
return return
def incrementAddressSuccess(self, address): def incrementAddressSuccess(self, address):
'''Increase the recorded sucesses for an address''' '''
Increase the recorded sucesses for an address
'''
increment = self._core.getAddressInfo(address, 'success') + 1 increment = self._core.getAddressInfo(address, 'success') + 1
self._core.setAddressInfo(address, 'success', increment) self._core.setAddressInfo(address, 'success', increment)
return return
def decrementAddressSuccess(self, address): def decrementAddressSuccess(self, address):
'''Decrease the recorded sucesses for an address''' '''
Decrease the recorded sucesses for an address
'''
increment = self._core.getAddressInfo(address, 'success') - 1 increment = self._core.getAddressInfo(address, 'success') - 1
self._core.setAddressInfo(address, 'success', increment) self._core.setAddressInfo(address, 'success', increment)
return return
def mergeKeys(self, newKeyList): def mergeKeys(self, newKeyList):
'''Merge ed25519 key list to our database''' '''
Merge ed25519 key list to our database
'''
retVal = False retVal = False
if newKeyList != False: if newKeyList != False:
for key in newKeyList.split(','): for key in newKeyList.split(','):
@ -84,15 +88,17 @@ class OnionrUtils:
retVal = True retVal = True
return retVal return retVal
def mergeAdders(self, newAdderList): def mergeAdders(self, newAdderList):
'''Merge peer adders list to our database''' '''
Merge peer adders list to our database
'''
retVal = False retVal = False
if newAdderList != False: if newAdderList != False:
for adder in newAdderList.split(','): for adder in newAdderList.split(','):
if not adder in self._core.listAdders(randomOrder=False) and adder.strip() != self.getMyAddress(): if not adder in self._core.listAdders(randomOrder=False) and adder.strip() != self.getMyAddress():
if self._core.addAddress(adder): if self._core.addAddress(adder):
logger.info('added ' + adder + ' to db') logger.info('Added ' + adder + ' to db.', timestamp=True)
input() input()
retVal = True retVal = True
else: else:
@ -116,7 +122,7 @@ class OnionrUtils:
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 requests.ConnectionError:
retData = False retData = False
return retData return retData
@ -285,15 +291,18 @@ class OnionrUtils:
for i in blocks: for i in blocks:
if len (i) == 0: if len (i) == 0:
continue continue
with open('data/blocks/' + i + '.dat', 'r') as potentialMessage: try:
message = potentialMessage.read() with open('data/blocks/' + i + '.dat', 'r') as potentialMessage:
if message.startswith('-pm-'): message = potentialMessage.read()
try: if message.startswith('-pm-'):
message = self._core._crypto.pubKeyDecrypt(message.replace('-pm-', ''), encodedData=True, anonymous=True) try:
except nacl.exceptions.CryptoError as e: message = self._core._crypto.pubKeyDecrypt(message.replace('-pm-', ''), encodedData=True, anonymous=True)
#logger.debug('Unable to decrypt ' + i) except nacl.exceptions.CryptoError as e:
#logger.debug(str(e)) #logger.debug('Unable to decrypt ' + i)
pass #logger.debug(str(e))
else: pass
logger.info('Recieved message: ' + message.decode()) else:
return logger.info('Recieved message: ' + message.decode())
except Exception as error:
logger.error('Failed to open block ' + str(i) + '.', error=error)
return