示例#1
0
def update():
    global listedBlocks, listbox, runningCheckDelayCount, runningCheckDelay, root, daemonStatus

    for i in Block.getBlocks(type='txt'):
        if i.getContent().strip() == '' or i.getHash() in listedBlocks:
            continue
        listbox.insert(99999, str(i.getContent()))
        listedBlocks.append(i.getHash())
        listbox.see(99999)

    runningCheckDelayCount += 1

    if runningCheckDelayCount == runningCheckDelay:
        resp = pluginapi.daemon.local_command('ping')
        if resp == 'pong':
            daemonStatus.config(text="Onionr Daemon Status: Running")
        else:
            daemonStatus.config(text="Onionr Daemon Status: Not Running")
        runningCheckDelayCount = 0
    root.after(10000, update)
示例#2
0
def commandInstallPlugin():
    if len(sys.argv) >= 3:
        check()

        pluginname = sys.argv[2]
        pkobh = None  # public key or block hash

        version = None
        if ':' in pluginname:
            details = pluginname
            pluginname = sanitize(details[0])
            version = details[1]

        sanitize(pluginname)

        if len(sys.argv) >= 4:
            # public key or block hash specified
            pkobh = sys.argv[3]
        else:
            # none specified, check if in config file
            pkobh = getKey(pluginname)

        if pkobh is None:
            # still nothing found, try searching repositories
            logger.info('Searching for public key in repositories...')
            try:
                repos = getRepositories()
                distributors = list()
                for repo, records in repos.items():
                    if pluginname in records:
                        logger.debug(
                            'Found %s in repository %s for plugin %s.' %
                            (records[pluginname], repo, pluginname))
                        distributors.append(records[pluginname])

                if len(distributors) != 0:
                    distributor = None

                    if len(distributors) == 1:
                        logger.info('Found distributor: %s' % distributors[0])
                        distributor = distributors[0]
                    else:
                        distributors_message = ''

                        index = 1
                        for dist in distributors:
                            distributors_message += '    ' + logger.colors.bold + str(
                                index) + ') ' + logger.colors.reset + str(
                                    dist) + '\n'
                            index += 1

                        logger.info(
                            (logger.colors.bold + 'Found distributors (%s):' +
                             logger.colors.reset + '\n' + distributors_message)
                            % len(distributors))

                        valid = False
                        while not valid:
                            choice = logger.readline(
                                'Select the number of the key to use, from 1 to %s, or press Ctrl+C to cancel:'
                                % (index - 1))

                            try:
                                if int(choice) < index and int(choice) >= 1:
                                    distributor = distributors[int(choice)]
                                    valid = True
                            except KeyboardInterrupt:
                                logger.info('Installation cancelled.')
                                return True
                            except:
                                pass

                    if not distributor is None:
                        pkobh = distributor
            except Exception as e:
                logger.warn('Failed to lookup plugin in repositories.',
                            timestamp=False)
                logger.error('asdf', error=e, timestamp=False)

        if pkobh is None:
            logger.error(
                'No key for this plugin found in keystore or repositories, please specify.'
            )
            help()
            return True

        valid_hash = pluginapi.get_utils().validateHash(pkobh)
        real_block = False
        valid_key = pluginapi.get_utils().validatePubKey(pkobh)
        real_key = False

        if valid_hash:
            real_block = Block.exists(pkobh)
        elif valid_key:
            real_key = pluginapi.get_utils().hasKey(pkobh)

        blockhash = None

        if valid_hash and not real_block:
            logger.error(
                'Block hash not found. Perhaps it has not been synced yet?')
            logger.debug(
                'Is valid hash, but does not belong to a known block.')

            return True
        elif valid_hash and real_block:
            blockhash = str(pkobh)
            logger.debug('Using block %s...' % blockhash)

            installBlock(blockhash)
        elif valid_key and not real_key:
            logger.error(
                'Public key not found. Try adding the node by address manually, if possible.'
            )
            logger.debug('Is valid key, but the key is not a known one.')
        elif valid_key and real_key:
            publickey = str(pkobh)
            logger.debug('Using public key %s...' % publickey)

            saveKey(pluginname, pkobh)

            signedBlocks = Block.getBlocks(type='plugin',
                                           signed=True,
                                           signer=publickey)

            mostRecentTimestamp = None
            mostRecentVersionBlock = None

            for block in signedBlocks:
                try:
                    blockContent = json.loads(block.getContent())

                    if not (('author' in blockContent) and
                            ('info' in blockContent) and
                            ('date' in blockContent) and
                            ('name' in blockContent)):
                        raise ValueError(
                            'Missing required parameter `date` in block %s.' %
                            block.getHash())

                    blockDatetime = datetime.datetime.strptime(
                        blockContent['date'], '%Y-%m-%d %H:%M:%S')

                    if blockContent['name'] == pluginname:
                        if ('version' in blockContent['info']) and (
                                blockContent['info']['version']
                                == version) and (not version is None):
                            mostRecentTimestamp = blockDatetime
                            mostRecentVersionBlock = block.getHash()
                            break
                        elif mostRecentTimestamp is None:
                            mostRecentTimestamp = blockDatetime
                            mostRecentVersionBlock = block.getHash()
                        elif blockDatetime > mostRecentTimestamp:
                            mostRecentTimestamp = blockDatetime
                            mostRecentVersionBlock = block.getHash()
                except Exception as e:
                    pass

            logger.warn(
                'Only continue the installation is you are absolutely certain that you trust the plugin distributor. Public key of plugin distributor: %s'
                % publickey,
                timestamp=False)
            installBlock(mostRecentVersionBlock)
        else:
            logger.error(
                'Unknown data "%s"; must be public key or block hash.' %
                str(pkobh))
            return
    else:
        logger.info(sys.argv[0] + ' ' + sys.argv[1] +
                    ' <plugin> [public key/block hash]')

    return True
示例#3
0
def show_stats(o_inst):
    try:
        # define stats messages here
        totalBlocks = len(o_inst.onionrCore.getBlockList())
        signedBlocks = len(Block.getBlocks(signed=True))
        messages = {
            # info about local client
            'Onionr Daemon Status':
            ((logger.colors.fg.green +
              'Online') if o_inst.onionrUtils.isCommunicatorRunning(
                  timeout=9) else logger.colors.fg.red + 'Offline'),

            # file and folder size stats
            'div1':
            True,  # this creates a solid line across the screen, a div
            'Total Block Size':
            onionrutils.humanSize(onionrutils.size(o_inst.dataDir +
                                                   'blocks/')),
            'Total Plugin Size':
            onionrutils.humanSize(onionrutils.size(o_inst.dataDir +
                                                   'plugins/')),
            'Log File Size':
            onionrutils.humanSize(
                onionrutils.size(o_inst.dataDir + 'output.log')),

            # count stats
            'div2':
            True,
            'Known Peers':
            str(max(len(o_inst.onionrCore.listPeers()) - 1, 0)),
            'Enabled Plugins':
            str(len(o_inst.onionrCore.config.get('plugins.enabled', list()))) +
            ' / ' + str(len(os.listdir(o_inst.dataDir + 'plugins/'))),
            'Stored Blocks':
            str(totalBlocks),
            'Percent Blocks Signed':
            str(round(100 * signedBlocks / max(totalBlocks, 1), 2)) + '%'
        }

        # color configuration
        colors = {
            'title': logger.colors.bold,
            'key': logger.colors.fg.lightgreen,
            'val': logger.colors.fg.green,
            'border': logger.colors.fg.lightblue,
            'reset': logger.colors.reset
        }

        # pre-processing
        maxlength = 0
        width = o_inst.getConsoleWidth()
        for key, val in messages.items():
            if not (type(val) is bool and val is True):
                maxlength = max(len(key), maxlength)
        prewidth = maxlength + len(' | ')
        groupsize = width - prewidth - len('[+] ')

        # generate stats table
        logger.info(colors['title'] +
                    'Onionr v%s Statistics' % onionr.ONIONR_VERSION +
                    colors['reset'])
        logger.info(colors['border'] + '-' * (maxlength + 1) + '+' +
                    colors['reset'])
        for key, val in messages.items():
            if not (type(val) is bool and val is True):
                val = [
                    str(val)[i:i + groupsize]
                    for i in range(0, len(str(val)), groupsize)
                ]

                logger.info(colors['key'] + str(key).rjust(maxlength) +
                            colors['reset'] + colors['border'] + ' | ' +
                            colors['reset'] + colors['val'] + str(val.pop(0)) +
                            colors['reset'])

                for value in val:
                    logger.info(' ' * maxlength + colors['border'] + ' | ' +
                                colors['reset'] + colors['val'] + str(value) +
                                colors['reset'])
            else:
                logger.info(colors['border'] + '-' * (maxlength + 1) + '+' +
                            colors['reset'])
        logger.info(colors['border'] + '-' * (maxlength + 1) + '+' +
                    colors['reset'])
    except Exception as e:
        logger.error('Failed to generate statistics table.',
                     error=e,
                     timestamp=False)