Misc changes

- made stuff pretty
- fixed bugs
- refactored stuff
This commit is contained in:
Arinerron 2018-11-09 23:17:19 -08:00
parent 099550fa34
commit 548d4ed106
No known key found for this signature in database
GPG Key ID: 99383627861C62F0
7 changed files with 66 additions and 39 deletions

View File

@ -87,6 +87,7 @@ class OnionrCommunicatorDaemon:
# Set timers, function reference, seconds # Set timers, function reference, seconds
# requiresPeer True means the timer function won't fire if we have no connected peers # requiresPeer True means the timer function won't fire if we have no connected peers
OnionrCommunicatorTimers(self, self.runCheck, 1)
OnionrCommunicatorTimers(self, self.daemonCommands, 5) OnionrCommunicatorTimers(self, self.daemonCommands, 5)
OnionrCommunicatorTimers(self, self.detectAPICrash, 5) OnionrCommunicatorTimers(self, self.detectAPICrash, 5)
peerPoolTimer = OnionrCommunicatorTimers(self, self.getOnlinePeers, 60, maxThreads=1) peerPoolTimer = OnionrCommunicatorTimers(self, self.getOnlinePeers, 60, maxThreads=1)
@ -133,7 +134,7 @@ class OnionrCommunicatorDaemon:
def lookupAdders(self): def lookupAdders(self):
'''Lookup new peer addresses''' '''Lookup new peer addresses'''
logger.info('LOOKING UP NEW ADDRESSES') logger.info('Looking up new addresses...')
tryAmount = 1 tryAmount = 1
for i in range(tryAmount): for i in range(tryAmount):
# Download new peer address list from random online peers # Download new peer address list from random online peers
@ -144,7 +145,7 @@ class OnionrCommunicatorDaemon:
def lookupBlocks(self): def lookupBlocks(self):
'''Lookup new blocks & add them to download queue''' '''Lookup new blocks & add them to download queue'''
logger.info('LOOKING UP NEW BLOCKS') logger.info('Looking up new blocks...')
tryAmount = 2 tryAmount = 2
newBlocks = '' newBlocks = ''
existingBlocks = self._core.getBlockList() existingBlocks = self._core.getBlockList()
@ -175,7 +176,7 @@ class OnionrCommunicatorDaemon:
try: try:
newBlocks = self.peerAction(peer, 'getBlockHashes') # get list of new block hashes newBlocks = self.peerAction(peer, 'getBlockHashes') # get list of new block hashes
except Exception as error: except Exception as error:
logger.warn("could not get new blocks with " + peer, error=error) logger.warn('Could not get new blocks from %s.' % peer, error = error)
newBlocks = False newBlocks = False
if newBlocks != False: if newBlocks != False:
# if request was a success # if request was a success
@ -199,10 +200,10 @@ class OnionrCommunicatorDaemon:
break break
# Do not download blocks being downloaded or that are already saved (edge cases) # Do not download blocks being downloaded or that are already saved (edge cases)
if blockHash in self.currentDownloading: if blockHash in self.currentDownloading:
logger.debug('ALREADY DOWNLOADING ' + blockHash) logger.debug('Already downloading block %s...' % blockHash)
continue continue
if blockHash in self._core.getBlockList(): if blockHash in self._core.getBlockList():
logger.debug('%s is already saved' % (blockHash,)) logger.debug('Block %s is already saved.' % (blockHash,))
self.blockQueue.remove(blockHash) self.blockQueue.remove(blockHash)
continue continue
if self._core._blacklist.inBlacklist(blockHash): if self._core._blacklist.inBlacklist(blockHash):
@ -231,22 +232,22 @@ class OnionrCommunicatorDaemon:
#meta = metas[1] #meta = metas[1]
if self._core._utils.validateMetadata(metadata, metas[2]): # check if metadata is valid, and verify nonce if self._core._utils.validateMetadata(metadata, metas[2]): # check if metadata is valid, and verify nonce
if self._core._crypto.verifyPow(content): # check if POW is enough/correct if self._core._crypto.verifyPow(content): # check if POW is enough/correct
logger.info('Block passed proof, attempting save.') logger.info('Attempting to save block %s...' % blockHash)
try: try:
self._core.setData(content) self._core.setData(content)
except onionrexceptions.DiskAllocationReached: except onionrexceptions.DiskAllocationReached:
logger.error("Reached disk allocation allowance, cannot save this block.") logger.error('Reached disk allocation allowance, cannot save block %s.' % blockHash)
removeFromQueue = False removeFromQueue = False
else: else:
self._core.addToBlockDB(blockHash, dataSaved=True) self._core.addToBlockDB(blockHash, dataSaved=True)
self._core._utils.processBlockMetadata(blockHash) # caches block metadata values to block database self._core._utils.processBlockMetadata(blockHash) # caches block metadata values to block database
else: else:
logger.warn('POW failed for block ' + blockHash) logger.warn('POW failed for block %s.' % blockHash)
else: else:
if self._core._blacklist.inBlacklist(realHash): if self._core._blacklist.inBlacklist(realHash):
logger.warn('%s is blacklisted' % (realHash,)) logger.warn('Block %s is blacklisted.' % (realHash,))
else: else:
logger.warn('Metadata for ' + blockHash + ' is invalid.') logger.warn('Metadata for block %s is invalid.' % blockHash)
self._core._blacklist.addToDB(blockHash) self._core._blacklist.addToDB(blockHash)
else: else:
# if block didn't meet expected hash # if block didn't meet expected hash
@ -456,7 +457,7 @@ class OnionrCommunicatorDaemon:
self.announce(cmd[1]) self.announce(cmd[1])
else: else:
logger.warn("Not introducing, since I have no connected nodes.") logger.warn("Not introducing, since I have no connected nodes.")
elif cmd[0] == 'runCheck': elif cmd[0] == 'runCheck': # deprecated
logger.debug('Status check; looks good.') logger.debug('Status check; looks good.')
open(self._core.dataDir + '.runcheck', 'w+').close() open(self._core.dataDir + '.runcheck', 'w+').close()
elif cmd[0] == 'connectedPeers': elif cmd[0] == 'connectedPeers':
@ -525,6 +526,12 @@ class OnionrCommunicatorDaemon:
self.shutdown = True self.shutdown = True
self.decrementThreadCount('detectAPICrash') self.decrementThreadCount('detectAPICrash')
def runCheck(self):
if self.daemonTools.runCheck():
logger.debug('Status check; looks good.')
self.decrementThreadCount('runCheck')
class OnionrCommunicatorTimers: class OnionrCommunicatorTimers:
def __init__(self, daemonInstance, timerFunction, frequency, makeThread=True, threadAmount=1, maxThreads=5, requiresPeer=False): def __init__(self, daemonInstance, timerFunction, frequency, makeThread=True, threadAmount=1, maxThreads=5, requiresPeer=False):
self.timerFunction = timerFunction self.timerFunction = timerFunction

View File

@ -179,7 +179,7 @@ class Core:
return True return True
else: else:
logger.debug('Invalid ID') logger.debug('Invalid ID: %s' % address)
return False return False
def removeAddress(self, address): def removeAddress(self, address):

View File

@ -156,6 +156,16 @@ class Onionr:
'status': self.showStats, 'status': self.showStats,
'statistics': self.showStats, 'statistics': self.showStats,
'stats': self.showStats, 'stats': self.showStats,
'details' : self.showDetails,
'detail' : self.showDetails,
'show-details' : self.showDetails,
'show-detail' : self.showDetails,
'showdetails' : self.showDetails,
'showdetail' : self.showDetails,
'get-details' : self.showDetails,
'get-detail' : self.showDetails,
'getdetails' : self.showDetails,
'getdetail' : self.showDetails,
'enable-plugin': self.enablePlugin, 'enable-plugin': self.enablePlugin,
'enplugin': self.enablePlugin, 'enplugin': self.enablePlugin,
@ -188,7 +198,6 @@ class Onionr:
'add-file': self.addFile, 'add-file': self.addFile,
'addfile': self.addFile, 'addfile': self.addFile,
'get-file': self.getFile, 'get-file': self.getFile,
'getfile': self.getFile, 'getfile': self.getFile,
@ -204,16 +213,6 @@ class Onionr:
'ui' : self.openUI, 'ui' : self.openUI,
'gui' : self.openUI, 'gui' : self.openUI,
'getpassword': self.printWebPassword,
'get-password': self.printWebPassword,
'getpwd': self.printWebPassword,
'get-pwd': self.printWebPassword,
'getpass': self.printWebPassword,
'get-pass': self.printWebPassword,
'getpasswd': self.printWebPassword,
'get-passwd': self.printWebPassword,
'chat': self.startChat, 'chat': self.startChat,
'friend': self.friendCmd 'friend': self.friendCmd
@ -261,6 +260,18 @@ class Onionr:
THIS SECTION HANDLES THE COMMANDS THIS SECTION HANDLES THE COMMANDS
''' '''
def showDetails(self):
details = {
'Node Address' : self.get_hostname(),
'Web Password' : self.getWebPassword(),
'Public Key' : self.onionrCore._crypto.pubKey,
'Human-readable Public Key' : self.onionrCore._utils.getHumanReadableID()
}
for detail in details:
logger.info('%s%s: \n%s%s\n' % (logger.colors.fg.lightgreen, detail, logger.colors.fg.green, details[detail]), sensitive = True)
def startChat(self): def startChat(self):
try: try:
data = json.dumps({'peer': sys.argv[2], 'reason': 'chat'}) data = json.dumps({'peer': sys.argv[2], 'reason': 'chat'})
@ -427,9 +438,7 @@ class Onionr:
Displays a list of keys (used to be called peers) (?) Displays a list of keys (used to be called peers) (?)
''' '''
logger.info('Public keys in database:\n') logger.info('%sPublic keys in database: \n%s%s' % (logger.colors.fg.lightgreen, logger.colors.fg.green, '\n'.join(self.onionrCore.listPeers())))
for i in self.onionrCore.listPeers():
logger.info(i)
def addPeer(self): def addPeer(self):
''' '''
@ -618,8 +627,14 @@ class Onionr:
''' '''
Starts the Onionr communication daemon Starts the Onionr communication daemon
''' '''
communicatorDaemon = './communicator2.py' communicatorDaemon = './communicator2.py'
# remove runcheck if it exists
if os.path.isfile('data/.runcheck'):
logger.debug('Runcheck file found on daemon start, deleting in advance.')
os.remove('data/.runcheck')
apiThread = Thread(target=api.API, args=(self.debug,API_VERSION)) apiThread = Thread(target=api.API, args=(self.debug,API_VERSION))
apiThread.start() apiThread.start()
try: try:
@ -689,9 +704,6 @@ class Onionr:
messages = { messages = {
# info about local client # info about local client
'Onionr Daemon Status' : ((logger.colors.fg.green + 'Online') if self.onionrUtils.isCommunicatorRunning(timeout = 9) else logger.colors.fg.red + 'Offline'), 'Onionr Daemon Status' : ((logger.colors.fg.green + 'Online') if self.onionrUtils.isCommunicatorRunning(timeout = 9) else logger.colors.fg.red + 'Offline'),
'Public Key' : self.onionrCore._crypto.pubKey,
'Human readable public key' : self.onionrCore._utils.getHumanReadableID(),
'Node Address' : self.get_hostname(),
# file and folder size stats # file and folder size stats
'div1' : True, # this creates a solid line across the screen, a div 'div1' : True, # this creates a solid line across the screen, a div

View File

@ -17,8 +17,10 @@
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>. along with this program. If not, see <https://www.gnu.org/licenses/>.
''' '''
import onionrexceptions, onionrpeers, onionrproofs, base64, logger, onionrusers, sqlite3 import onionrexceptions, onionrpeers, onionrproofs, logger, onionrusers
import base64, sqlite3, os
from dependencies import secrets from dependencies import secrets
class DaemonTools: class DaemonTools:
def __init__(self, daemon): def __init__(self, daemon):
self.daemon = daemon self.daemon = daemon
@ -131,3 +133,10 @@ class DaemonTools:
self.daemon.removeOnlinePeer(toCool) self.daemon.removeOnlinePeer(toCool)
self.daemon.cooldownPeer[toCool] = self.daemon._core._utils.getEpoch() self.daemon.cooldownPeer[toCool] = self.daemon._core._utils.getEpoch()
self.daemon.decrementThreadCount('cooldownPeer') self.daemon.decrementThreadCount('cooldownPeer')
def runCheck(self):
if os.path.isfile('data/.runcheck'):
os.remove('data/.runcheck')
return True
return False

View File

@ -519,18 +519,16 @@ class OnionrUtils:
try: try:
runcheck_file = self._core.dataDir + '.runcheck' runcheck_file = self._core.dataDir + '.runcheck'
if os.path.isfile(runcheck_file): if not os.path.isfile(runcheck_file):
os.remove(runcheck_file) open(runcheck_file, 'w+').close()
logger.debug('%s file appears to have existed before the run check.' % runcheck_file, timestamp = False)
self._core.daemonQueueAdd('runCheck') # self._core.daemonQueueAdd('runCheck') # deprecated
starttime = time.time() starttime = time.time()
while True: while True:
time.sleep(interval) time.sleep(interval)
if os.path.isfile(runcheck_file):
os.remove(runcheck_file)
if not os.path.isfile(runcheck_file):
return True return True
elif time.time() - starttime >= timeout: elif time.time() - starttime >= timeout:
return False return False
@ -541,6 +539,7 @@ class OnionrUtils:
''' '''
Generates a secure random hex encoded token Generates a secure random hex encoded token
''' '''
return binascii.hexlify(os.urandom(size)) return binascii.hexlify(os.urandom(size))
def importNewBlocks(self, scanDir=''): def importNewBlocks(self, scanDir=''):

View File

@ -641,7 +641,7 @@ if(tt !== null && tt !== undefined) {
if(getWebPassword() === null) { if(getWebPassword() === null) {
var password = ""; var password = "";
while(password.length != 64) { while(password.length != 64) {
password = prompt("Please enter the web password (run `./RUN-LINUX.sh --get-password`)"); password = prompt("Please enter the web password (run `./RUN-LINUX.sh --details`)");
} }
setWebPassword(password); setWebPassword(password);