Ejemplo n.º 1
0
def commandAddRepository():
    if len(sys.argv) >= 3:
        check()

        blockhash = sys.argv[2]

        if pluginapi.get_utils().validateHash(blockhash):
            if Block.exists(blockhash):
                try:
                    blockContent = json.loads(Block(blockhash, core = pluginapi.get_core()).getContent())

                    pluginslist = dict()

                    for pluginname, distributor in blockContent['plugins']:
                        if pluginapi.get_utils().validatePubKey(distributor):
                            pluginslist[pluginname] = distributor

                    logger.debug('Found %s records in repository.' % len(pluginslist))

                    if len(pluginslist) != 0:
                        addRepository(blockhash, pluginslist)
                        logger.info('Successfully added repository.')
                    else:
                        logger.error('Repository contains no records, not importing.', timestamp = False)
                except Exception as e:
                    logger.error('Failed to parse block.', error = e)
            else:
                logger.error('Block hash not found. Perhaps it has not been synced yet?', timestamp = False)
                logger.debug('Is valid hash, but does not belong to a known block.')
        else:
            logger.error('Unknown data "%s"; must be block hash.' % str(pkobh), timestamp = False)
    else:
        logger.info(sys.argv[0] + ' ' + sys.argv[1] + ' [block hash]')

    return True
Ejemplo n.º 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