Esempio n. 1
0
def init(
        click_config,

        # Admin Options
        provider_uri,
        network,
        registry_filepath,
        checksum_address,

        # Other
        federated_only,
        config_root):
    """
    Create a brand new persistent Bob.
    """
    emitter = _setup_emitter(click_config)

    if not config_root:  # Flag
        config_root = click_config.config_file  # Envvar
    if not checksum_address and not federated_only:
        checksum_address = select_client_account(emitter=emitter,
                                                 provider_uri=provider_uri)

    new_bob_config = BobConfiguration.generate(
        password=get_nucypher_password(confirm=True),
        config_root=config_root or DEFAULT_CONFIG_ROOT,
        checksum_address=checksum_address,
        domains={network} if network else None,
        federated_only=federated_only,
        registry_filepath=registry_filepath,
        provider_uri=provider_uri)
    return painting.paint_new_installation_help(
        emitter, new_configuration=new_bob_config)
Esempio n. 2
0
    def generate_config(self, emitter, config_root, federated_only):

        checksum_address = self.checksum_address
        if not checksum_address and not federated_only:
            checksum_address = select_client_account(
                emitter=emitter,
                provider_uri=self.provider_uri,
                show_balances=False)

        return BobConfiguration.generate(
            password=get_nucypher_password(confirm=True),
            config_root=config_root,
            checksum_address=checksum_address,
            domains=self.domains,
            federated_only=federated_only,
            registry_filepath=self.registry_filepath,
            provider_uri=self.provider_uri)
Esempio n. 3
0
    def generate_config(self, emitter: StdoutEmitter, config_root: str) -> BobConfiguration:

        checksum_address = self.checksum_address
        if not checksum_address and not self.federated_only:
            checksum_address = select_client_account(emitter=emitter,
                                                     signer_uri=self.signer_uri,
                                                     provider_uri=self.provider_uri)  # TODO: See #1888

        return BobConfiguration.generate(
            password=get_nucypher_password(confirm=True),
            config_root=config_root,
            checksum_address=checksum_address,
            domains=self.domains,
            federated_only=self.federated_only,
            registry_filepath=self.registry_filepath,
            provider_uri=self.provider_uri,
            signer_uri=self.signer_uri,
            gas_strategy=self.gas_strategy,
        )
Esempio n. 4
0
    def generate_config(self, emitter: StdoutEmitter, config_root: Path,
                        key_material: str) -> BobConfiguration:

        checksum_address = self.checksum_address
        if not checksum_address and not self.federated_only:
            checksum_address = select_client_account(
                emitter=emitter,
                signer_uri=self.signer_uri,
                provider_uri=self.provider_uri)  # TODO: See #1888

        return BobConfiguration.generate(
            password=get_nucypher_password(emitter=emitter, confirm=True),
            key_material=bytes.fromhex(key_material) if key_material else None,
            config_root=config_root,
            checksum_address=checksum_address,
            domain=self.domain,
            federated_only=self.federated_only,
            registry_filepath=self.registry_filepath,
            provider_uri=self.provider_uri,
            signer_uri=self.signer_uri,
            gas_strategy=self.gas_strategy,
            max_gas_price=self.max_gas_price,
            lonely=self.lonely)
Esempio n. 5
0
def bob(click_config,
        action,
        quiet,
        teacher_uri,
        min_stake,
        http_port,
        discovery_port,
        federated_only,
        network,
        config_root,
        config_file,
        pay_with,
        provider_uri,
        registry_filepath,
        dev,
        force,
        dry_run,
        label,
        policy_encrypting_key,
        alice_verifying_key,
        message_kit):
    """
    Start and manage a "Bob" character.
    """

    #
    # Validate
    #

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

    #
    # Eager Actions
    #

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

        if dev:
            raise click.BadArgumentUsage("Cannot create a persistent development character")

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

        new_bob_config = BobConfiguration.generate(password=get_password(confirm=True),
                                                   config_root=config_root or DEFAULT_CONFIG_ROOT,
                                                   checksum_address=pay_with,
                                                   domains={network} if network else None,
                                                   federated_only=federated_only,
                                                   download_registry=click_config.no_registry,
                                                   registry_filepath=registry_filepath,
                                                   provider_uri=provider_uri)

        return painting.paint_new_installation_help(new_configuration=new_bob_config)

    # TODO
    # 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)

    #
    # Make Bob
    #

    if dev:
        bob_config = BobConfiguration(dev_mode=True,
                                      domains={network},
                                      provider_uri=provider_uri,
                                      federated_only=True,
                                      checksum_address=pay_with,
                                      network_middleware=click_config.middleware)
    else:

        try:
            bob_config = BobConfiguration.from_configuration_file(
                filepath=config_file,
                domains={network} if network else None,
                checksum_address=pay_with,
                rest_port=discovery_port,
                provider_uri=provider_uri,
                network_middleware=click_config.middleware)
        except FileNotFoundError:
            return actions.handle_missing_configuration_file(character_config_class=BobConfiguration,
                                                             config_file=config_file)

    BOB = actions.make_cli_character(character_config=bob_config,
                                     click_config=click_config,
                                     dev=dev,
                                     teacher_uri=teacher_uri,
                                     min_stake=min_stake)

    #
    # Admin Action
    #

    if action == "run":

        # Echo Public Keys
        click_config.emit(message=f"Bob Verifying Key {bytes(BOB.stamp).hex()}", color='green', bold=True)

        # RPC
        if click_config.json_ipc:
            rpc_controller = BOB.make_rpc_controller()
            _transport = rpc_controller.make_control_transport()
            rpc_controller.start()
            return

        click_config.emit(message=f"Bob Verifying Key {bytes(BOB.stamp).hex()}", color='green', bold=True)
        bob_encrypting_key = bytes(BOB.public_keys(DecryptingPower)).hex()
        click_config.emit(message=f"Bob Encrypting Key {bob_encrypting_key}", color="blue", bold=True)

        # Start Controller
        controller = BOB.make_control_transport()
        BOB.log.info('Starting HTTP Character Web Controller')
        return controller.start(http_port=http_port, dry_run=dry_run)

    elif action == "destroy":
        """Delete Bob's character configuration files from the disk"""

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

        # Request
        return actions.destroy_configuration(character_config=bob_config)

    #
    # Bob API Actions
    #

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

    elif action == "retrieve":

        # Validate
        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')

        # Request
        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}")
Esempio n. 6
0
def bob(click_config, action, teacher_uri, min_stake, controller_port,
        discovery_port, federated_only, network, config_root, config_file,
        checksum_address, provider_uri, registry_filepath, dev, force, poa,
        dry_run, label, policy_encrypting_key, alice_verifying_key,
        message_kit, sync):
    """
    "Bob" management commands.

    \b
    Actions
    -------------------------------------------------
    \b
    init         Create a brand new persistent Bob
    view         View existing Bob's configuration.
    run          Start Bob's controller.
    destroy      Delete existing Bob's configuration.
    public-keys  Obtain Bob's public verification and encryption keys.
    retrieve     Obtain plaintext from encrypted data, if access was granted.

    """

    #
    # Validate
    #

    # Banner
    emitter = click_config.emitter
    emitter.clear()
    emitter.banner(BOB_BANNER)

    #
    # Eager Actions
    #

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

        if dev:
            raise click.BadArgumentUsage(
                "Cannot create a persistent development character")

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

        if not checksum_address and not federated_only:
            registry = None
            if registry_filepath:
                registry = EthereumContractRegistry(
                    registry_filepath=registry_filepath)
            blockchain = BlockchainInterface(provider_uri=provider_uri,
                                             registry=registry,
                                             poa=poa)
            blockchain.connect(sync_now=sync, emitter=emitter)
            checksum_address = select_client_account(emitter=emitter,
                                                     blockchain=blockchain)

        download_registry = not federated_only and not click_config.no_registry
        new_bob_config = BobConfiguration.generate(
            password=get_nucypher_password(confirm=True),
            config_root=config_root or DEFAULT_CONFIG_ROOT,
            checksum_address=checksum_address,
            domains={network} if network else None,
            federated_only=federated_only,
            download_registry=download_registry,
            registry_filepath=registry_filepath,
            provider_uri=provider_uri)

        return painting.paint_new_installation_help(
            emitter, new_configuration=new_bob_config)

    #
    # Make Bob
    #

    if dev:
        bob_config = BobConfiguration(
            dev_mode=True,
            domains={network},
            provider_uri=provider_uri,
            federated_only=True,
            checksum_address=checksum_address,
            network_middleware=click_config.middleware)
    else:

        try:
            bob_config = BobConfiguration.from_configuration_file(
                filepath=config_file,
                domains={network} if network else None,
                checksum_address=checksum_address,
                rest_port=discovery_port,
                provider_uri=provider_uri,
                network_middleware=click_config.middleware)
        except FileNotFoundError:
            return actions.handle_missing_configuration_file(
                character_config_class=BobConfiguration,
                config_file=config_file)

    BOB = actions.make_cli_character(character_config=bob_config,
                                     click_config=click_config,
                                     dev=dev,
                                     teacher_uri=teacher_uri,
                                     min_stake=min_stake)

    #
    # Admin Action
    #

    if action == "run":

        # RPC
        if click_config.json_ipc:
            rpc_controller = BOB.make_rpc_controller()
            _transport = rpc_controller.make_control_transport()
            rpc_controller.start()
            return

        # Echo Public Keys
        emitter.message(f"Bob Verifying Key {bytes(BOB.stamp).hex()}",
                        color='green',
                        bold=True)
        bob_encrypting_key = bytes(BOB.public_keys(DecryptingPower)).hex()
        emitter.message(f"Bob Encrypting Key {bob_encrypting_key}",
                        color="blue",
                        bold=True)

        # Start Controller
        controller = BOB.make_web_controller(crash_on_error=click_config.debug)
        BOB.log.info('Starting HTTP Character Web Controller')
        return controller.start(http_port=controller_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.ipc(
            response, request_id=0, duration=0
        )  # FIXME: #1216 - what are request_id and duration here?

    elif action == "destroy":
        """Delete Bob's character configuration files from the disk"""

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

        # Request
        return actions.destroy_configuration(emitter,
                                             character_config=bob_config)

    #
    # Bob API Actions
    #

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

    elif action == "retrieve":

        # Validate
        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')

        # Request
        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}")
Esempio n. 7
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}")
Esempio n. 8
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_encrypting_key):
    """
    Start and manage a "Bob" character.
    """

    if not quiet:
        click.secho(BOB_BANNER)

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

        if dev and not quiet:
            click.secho("WARNING: Using temporary storage area", fg='yellow')

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

        bob_config = BobConfiguration.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=True,  # Yes we have no registry,
            registry_filepath=registry_filepath,
            provider_uri=provider_uri,
        )

        if not quiet:
            click.secho("Generated keyring {}".format(bob_config.keyring_dir),
                        fg='green')
            click.secho("Saved configuration file {}".format(
                bob_config.config_file_location),
                        fg='green')

            # Give the use a suggestion as to what to do next...
            how_to_run_message = "\nTo run an Bob node from the default configuration filepath run: \n\n'{}'\n"
            suggested_command = 'nucypher bob run'
            if config_root is not None:
                config_file_location = os.path.join(
                    config_root, config_file
                    or BobConfiguration.CONFIG_FILENAME)
                suggested_command += ' --config-file {}'.format(
                    config_file_location)
            click.secho(how_to_run_message.format(suggested_command),
                        fg='green')
            return  # FIN

        else:
            click.secho("OK")

    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)

        destroy_system_configuration(config_class=BobConfiguration,
                                     config_file=config_file,
                                     network=network,
                                     config_root=config_root,
                                     force=force)
        if not quiet:
            click.secho("Destroyed {}".format(config_root))
        return

    #
    # Get Bob Configuration
    #

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

    # Teacher
    teacher_nodes = list()
    if teacher_uri:
        teacher_node = Ursula.from_teacher_uri(
            teacher_uri=teacher_uri,
            min_stake=min_stake,
            federated_only=bob_config.federated_only)
        teacher_nodes.append(teacher_node)

    # Produce
    BOB = bob_config(known_nodes=teacher_nodes)

    if action == "run":

        if not dev:
            # Keyring
            try:
                click.secho("Decrypting keyring...", fg='blue')
                bob_config.keyring.unlock(password=click_config.get_password())
            except CryptoError:
                raise bob_config.keyring.AuthenticationFailed
            finally:
                click_config.bob_config = bob_config

        # Bob Control
        bob_control = BOB.make_wsgi_app()
        click.secho("Starting Bob Character Control...")

        click.secho(f"Bob Verifying Key {bytes(BOB.stamp).hex()}",
                    fg="green",
                    bold=True)
        click.secho(
            f"Bob Encrypting Key {bytes(BOB.public_keys(DecryptingPower)).hex()}",
            fg="blue",
            bold=True)

        # Run
        if dry_run:
            return

        hx_deployer = HendrixDeploy(action="start",
                                    options={
                                        "wsgi": bob_control,
                                        "http_port": http_port
                                    })
        hx_deployer.run()  # <--- Blocking Call to Reactor

    elif action == "view":
        """Paint an existing configuration to the console"""
        paint_configuration(
            config_filepath=config_file or bob_config.config_file_location)
        return

    elif action == "retrieve":
        bob_request_data = {
            'label': b64encode(label).decode(),
            'policy_encrypting_pubkey': policy_encrypting_key,
            'alice_signing_pubkey': alice_encrypting_key,
            # 'message_kit': b64encode(bob_message_kit.to_bytes()).decode(),  # TODO
        }

        response = requests.post('/retrieve',
                                 data=json.dumps(bob_request_data))
        click.secho(response)
        return

    else:
        raise click.BadArgumentUsage(f"No such argument {action}")