示例#1
0
def enrico(click_config, action, policy_encrypting_key, dry_run, http_port, message):
    """
    Start and manage an "Enrico" character control HTTP server
    """

    if not policy_encrypting_key:
        raise click.BadArgumentUsage('--policy-encrypting-key is required to start Enrico.')

    if not click_config.json_ipc and not click_config.quiet:
        click.secho(ENRICO_BANNER)

    policy_encrypting_key = UmbralPublicKey.from_bytes(bytes.fromhex(policy_encrypting_key))
    ENRICO = Enrico(policy_encrypting_key=policy_encrypting_key)

    if click_config.json_ipc:
        ENRICO.controller.emitter = IPCStdoutEmitter(quiet=click_config.quiet)

    if action == 'run':  # Forrest
        controller = ENRICO.make_web_controller()
        ENRICO.log.info('Starting HTTP Character Web Controller')
        return controller.start(http_port=http_port, dry_run=dry_run)

    elif action == 'encrypt':
        if not message:
            raise click.BadArgumentUsage('--message is a required flag to encrypt.')

        encryption_request = {'message': message}

        response = ENRICO.controller.encrypt_message(request=encryption_request)
        return response

    else:
        raise click.BadArgumentUsage
示例#2
0
def nucypher_cli(click_config,
                 verbose,
                 mock_networking,
                 json_ipc,
                 no_logs,
                 quiet,
                 debug,
                 no_registry):

    # Session Emitter for pre and post character control engagement.
    if json_ipc:
        emitter = IPCStdoutEmitter(quiet=quiet, capture_stdout=NucypherClickConfig.capture_stdout)
    else:
        emitter = StdoutEmitter(quiet=quiet, capture_stdout=NucypherClickConfig.capture_stdout)

    NucypherClickConfig.emitter = emitter
    click_config.emitter(message=NUCYPHER_BANNER)

    if debug and quiet:
        raise click.BadOptionUsage(option_name="quiet", message="--debug and --quiet cannot be used at the same time.")

    # Logging
    if not no_logs:
        GlobalConsoleLogger.start_if_not_started()

    if debug:
        click_config.log_to_sentry = False
        click_config.log_to_file = True
        globalLogPublisher.removeObserver(logToSentry)  # Sentry
        GlobalConsoleLogger.set_log_level(log_level_name='debug')

    elif quiet:
        globalLogPublisher.removeObserver(logToSentry)
        globalLogPublisher.removeObserver(SimpleObserver)
        globalLogPublisher.removeObserver(getJsonFileObserver())

    # CLI Session Configuration
    click_config.verbose = verbose
    click_config.mock_networking = mock_networking
    click_config.json_ipc = json_ipc
    click_config.no_logs = no_logs
    click_config.quiet = quiet
    click_config.no_registry = no_registry
    click_config.debug = debug

    # Only used for testing outputs;
    # Redirects outputs to in-memory python containers.
    if mock_networking:
        click_config.emitter(message="WARNING: Mock networking is enabled")
        click_config.middleware = MockRestMiddleware()
    else:
        click_config.middleware = RestMiddleware()

    # Global Warnings
    if click_config.verbose:
        click_config.emitter("Verbose mode is enabled", color='blue')
示例#3
0
文件: main.py 项目: mallek/nucypher
def nucypher_cli(click_config,
                 verbose,
                 mock_networking,
                 json_ipc,
                 no_logs,
                 quiet,
                 debug,
                 no_registry):

    # Session Emitter for pre and post character control engagement.
    if json_ipc:
        emitter = IPCStdoutEmitter(quiet=quiet, capture_stdout=NucypherClickConfig.capture_stdout)
    else:
        emitter = StdoutEmitter(quiet=quiet, capture_stdout=NucypherClickConfig.capture_stdout)

    NucypherClickConfig.emitter = emitter
    click_config.emitter(message=NUCYPHER_BANNER)

    # Logging
    if not no_logs:
        GlobalConsoleLogger.start_if_not_started()

    # CLI Session Configuration
    click_config.verbose = verbose
    click_config.mock_networking = mock_networking
    click_config.json_ipc = json_ipc
    click_config.no_logs = no_logs
    click_config.quiet = quiet
    click_config.no_registry = no_registry
    click_config.debug = debug

    # only used for testing outputs;
    # Redirects outputs to in-memory python containers.
    if mock_networking:
        click_config.emitter(message="WARNING: Mock networking is enabled")
        click_config.middleware = MockRestMiddleware()
    else:
        click_config.middleware = RestMiddleware()

    # Global Warnings
    if click_config.verbose:
        click_config.emitter("Verbose mode is enabled", color='blue')
示例#4
0
def bob(click_config, action, quiet, teacher_uri, min_stake, http_port,
        discovery_port, federated_only, network, config_root, config_file,
        provider_uri, registry_filepath, dev, force, dry_run, label,
        policy_encrypting_key, alice_verifying_key, message_kit):
    """
    Start and manage a "Bob" character.
    """

    if not click_config.json_ipc and not click_config.quiet:
        click.secho(BOB_BANNER)

    if action == 'init':
        """Create a brand-new persistent Bob"""

        if dev:
            actions.handle_control_output(
                message="WARNING: Using temporary storage area",
                quiet=quiet,
                color='yellow',
                json=click_config.json)

        if not config_root:  # Flag
            config_root = click_config.config_file  # Envvar

        new_bob_config = BobConfiguration.generate(
            password=click_config._get_password(confirm=True),
            config_root=config_root or click_config,
            rest_host="localhost",
            domains={network} if network else None,
            federated_only=federated_only,
            no_registry=click_config.no_registry,
            registry_filepath=registry_filepath,
            provider_uri=provider_uri)

        return painting.paint_new_installation_help(
            new_configuration=new_bob_config, config_file=config_file)

    elif action == "destroy":
        """Delete all configuration files from the disk"""

        if dev:
            message = "'nucypher ursula destroy' cannot be used in --dev mode"
            raise click.BadOptionUsage(option_name='--dev', message=message)

        destroyed_path = actions.destroy_system_configuration(
            config_class=BobConfiguration,
            config_file=config_file,
            network=network,
            config_root=config_root,
            force=force)

        return click_config.emitter(message=f"Destroyed {destroyed_path}")

    #
    # Get Bob Configuration
    #

    if dev:
        bob_config = BobConfiguration(
            dev_mode=True,
            domains={network},
            provider_uri=provider_uri,
            federated_only=True,
            network_middleware=click_config.middleware)
    else:
        bob_config = BobConfiguration.from_configuration_file(
            filepath=config_file,
            domains={network or GLOBAL_DOMAIN},
            rest_port=discovery_port,
            provider_uri=provider_uri,
            network_middleware=click_config.middleware)

    # Teacher Ursula
    teacher_uris = [teacher_uri] if teacher_uri else list()
    teacher_nodes = actions.load_seednodes(
        teacher_uris=teacher_uris,
        min_stake=min_stake,
        federated_only=federated_only,
        network_middleware=click_config.middleware)

    if not dev:
        click_config.unlock_keyring(character_configuration=bob_config)

    # Produce
    BOB = bob_config(known_nodes=teacher_nodes,
                     network_middleware=click_config.middleware)

    # Switch to character control emitter
    if click_config.json_ipc:
        BOB.controller.emitter = IPCStdoutEmitter(quiet=click_config.quiet)

    if action == "run":
        click_config.emitter(
            message=f"Bob Verifying Key {bytes(BOB.stamp).hex()}",
            color='green',
            bold=True)
        bob_encrypting_key = bytes(BOB.public_keys(DecryptingPower)).hex()
        click_config.emitter(
            message=f"Bob Encrypting Key {bob_encrypting_key}",
            color="blue",
            bold=True)
        controller = BOB.make_web_controller()
        BOB.log.info('Starting HTTP Character Web Controller')
        return controller.start(http_port=http_port, dry_run=dry_run)

    elif action == "view":
        """Paint an existing configuration to the console"""
        response = BobConfiguration._read_configuration_file(
            filepath=config_file or bob_config.config_file_location)
        return BOB.controller.emitter(response=response)

    elif action == "public-keys":
        response = BOB.controller.public_keys()
        return response

    elif action == "retrieve":

        if not all(
            (label, policy_encrypting_key, alice_verifying_key, message_kit)):
            input_specification, output_specification = BOB.control.get_specifications(
                interface_name='retrieve')
            required_fields = ', '.join(input_specification)
            raise click.BadArgumentUsage(
                f'{required_fields} are required flags to retrieve')

        bob_request_data = {
            'label': label,
            'policy_encrypting_key': policy_encrypting_key,
            'alice_verifying_key': alice_verifying_key,
            'message_kit': message_kit,
        }

        response = BOB.controller.retrieve(request=bob_request_data)
        return response

    else:
        raise click.BadArgumentUsage(f"No such argument {action}")
示例#5
0
def alice(click_config, action, teacher_uri, min_stake, http_port,
          discovery_port, federated_only, network, config_root, config_file,
          provider_uri, no_registry, registry_filepath, dev, force, dry_run,
          bob_encrypting_key, bob_verifying_key, policy_encrypting_key, label,
          m, n):
    """
    Start and manage an "Alice" character.
    """

    if not click_config.json_ipc and not click_config.quiet:
        click.secho(ALICE_BANNER)

    if action == 'init':
        """Create a brand-new persistent Alice"""

        if not network:
            raise click.BadArgumentUsage(
                '--network is required to initialize a new configuration.')

        if dev:
            click_config.emitter(
                message="WARNING: Using temporary storage area",
                color='yellow')

        if not config_root:  # Flag
            config_root = click_config.config_file  # Envvar

        new_alice_config = AliceConfiguration.generate(
            password=click_config._get_password(confirm=True),
            config_root=config_root,
            rest_host="localhost",
            domains={network} if network else None,
            federated_only=federated_only,
            no_registry=no_registry,
            registry_filepath=registry_filepath,
            provider_uri=provider_uri)

        return painting.paint_new_installation_help(
            new_configuration=new_alice_config,
            config_root=config_root,
            config_file=config_file)

    elif action == "destroy":
        """Delete all configuration files from the disk"""
        if dev:
            message = "'nucypher ursula destroy' cannot be used in --dev mode"
            raise click.BadOptionUsage(option_name='--dev', message=message)

        destroyed_path = actions.destroy_system_configuration(
            config_class=AliceConfiguration,
            config_file=config_file,
            network=network,
            config_root=config_root,
            force=force)

        return nucypher_click_config.emitter(
            message=f"Destroyed {destroyed_path}", color='red')

    #
    # Get Alice Configuration
    #

    if dev:
        alice_config = AliceConfiguration(
            dev_mode=True,
            network_middleware=click_config.middleware,
            domains={network},
            provider_uri=provider_uri,
            federated_only=True)

    else:
        alice_config = AliceConfiguration.from_configuration_file(
            filepath=config_file,
            domains={network or GLOBAL_DOMAIN},
            network_middleware=click_config.middleware,
            rest_port=discovery_port,
            provider_uri=provider_uri)

    if not dev:
        click_config.unlock_keyring(character_configuration=alice_config)

    # Teacher Ursula
    teacher_uris = [teacher_uri] if teacher_uri else list()
    teacher_nodes = actions.load_seednodes(
        teacher_uris=teacher_uris,
        min_stake=min_stake,
        federated_only=federated_only,
        network_middleware=click_config.middleware)
    # Produce
    ALICE = alice_config(known_nodes=teacher_nodes,
                         network_middleware=click_config.middleware)

    # Switch to character control emitter
    if click_config.json_ipc:
        ALICE.controller.emitter = IPCStdoutEmitter(quiet=click_config.quiet)

    if action == "run":
        """Start Alice Web Controller"""
        ALICE.controller.emitter(
            message=f"Alice Verifying Key {bytes(ALICE.stamp).hex()}",
            color="green",
            bold=True)
        controller = ALICE.make_web_controller(
            crash_on_error=click_config.debug)
        ALICE.log.info('Starting HTTP Character Web Controller')
        return controller.start(http_port=http_port, dry_run=dry_run)

    elif action == "view":
        """Paint an existing configuration to the console"""
        configuration_file_location = config_file or alice_config.config_file_location
        response = AliceConfiguration._read_configuration_file(
            filepath=configuration_file_location)
        return ALICE.controller.emitter(
            response=response)  # TODO: Uses character control instead

    elif action == "public-keys":
        response = ALICE.controller.public_keys()
        return response

    elif action == "create-policy":
        if not all((bob_verifying_key, bob_encrypting_key, label)):
            raise click.BadArgumentUsage(
                message=
                "--bob-verifying-key, --bob-encrypting-key, and --label are "
                "required options to create a new policy.")

        create_policy_request = {
            'bob_encrypting_key': bob_encrypting_key,
            'bob_verifying_key': bob_verifying_key,
            'label': label,
            'm': m,
            'n': n,
        }

        return ALICE.controller.create_policy(request=create_policy_request)

    elif action == "derive-policy-pubkey":
        return ALICE.controller.derive_policy_encrypting_key(label=label)

    elif action == "grant":
        grant_request = {
            'bob_encrypting_key': bob_encrypting_key,
            'bob_verifying_key': bob_verifying_key,
            'label': label,
            'm': m,
            'n': n,
            'expiration':
            (maya.now() + datetime.timedelta(days=3)).iso8601(),  # TODO
        }

        return ALICE.controller.grant(request=grant_request)

    elif action == "revoke":
        return ALICE.controller.revoke(
            policy_encrypting_key=policy_encrypting_key)

    else:
        raise click.BadArgumentUsage(f"No such argument {action}")
示例#6
0
def make_cli_character(character_config,
                       click_config,
                       dev: bool = False,
                       teacher_uri: str = None,
                       min_stake: int = 0,
                       enode: str = None,
                       sync: bool = True,
                       recompile_contracts: bool = False,
                       **config_args):

    #
    # Pre-Init
    #

    # Handle Blockchain
    if not character_config.federated_only:
        click_config.connect_to_blockchain(
            character_configuration=character_config,
            full_sync=sync,
            recompile_contracts=recompile_contracts)

    # Handle Keyring
    if not dev:
        click_config.unlock_keyring(
            character_configuration=character_config,
            password=click_config.get_password(confirm=False))

    # Handle Teachers
    teacher_nodes = None
    if teacher_uri:
        teacher_nodes = load_seednodes(
            teacher_uris=[teacher_uri] if teacher_uri else None,
            min_stake=min_stake,
            federated_only=character_config.federated_only,
            network_domains=character_config.domains,
            network_middleware=click_config.middleware)

    #
    # Character Init
    #

    # Produce Character
    CHARACTER = character_config(known_nodes=teacher_nodes,
                                 network_middleware=click_config.middleware,
                                 **config_args)

    #
    # Post-Init
    #

    # Switch to character control emitter
    if click_config.json_ipc:
        CHARACTER.controller.emitter = IPCStdoutEmitter(
            quiet=click_config.quiet)

    # Federated
    if character_config.federated_only:
        click_config.emit(message="WARNING: Running in Federated mode",
                          color='yellow')

    # Decentralized
    else:
        # Manual ethereum peer
        if enode:
            character_config.blockchain.interface.client.add_peer(enode)
            click.secho(f"Added ethereum peer {enode}")

    return CHARACTER