Exemple #1
0
def select_worker_config_file(emitter, config_file, worker_address,
                              provider_uri, network, federated):

    config_root = abspath(
        dirname(config_file)) if config_file else DEFAULT_CONFIG_ROOT
    worker_config_exists = glob.glob(
        UrsulaConfiguration.default_filepath(config_root=config_root))

    if not worker_config_exists:
        emitter.message(
            "No Ursula configurations found.  run 'nucypher ursula init' then try again.",
            color='red')
        raise click.Abort()

    # TODO: Needs Cleanup
    more_than_one_worker_config_exists = glob.glob(
        f'{config_root}/ursula-0x*.json')
    ethereum_account_required = not worker_address and not federated

    if more_than_one_worker_config_exists:
        if config_file is None:
            if ethereum_account_required:
                worker_address = select_client_account(
                    emitter=emitter,
                    network=network,
                    provider_uri=provider_uri)
            else:
                pass  # TODO: Support Federated Mode by walking the filesystem
            config_file = os.path.join(
                DEFAULT_CONFIG_ROOT,
                UrsulaConfiguration.generate_filename(modifier=worker_address))
    return config_file
Exemple #2
0
def test_ursula_development_configuration(federated_only=True):
    config = UrsulaConfiguration(dev_mode=True, federated_only=federated_only)
    assert config.is_me is True
    assert config.dev_mode is True
    assert config.keyring == NO_KEYRING_ATTACHED

    # Produce an Ursula
    ursula_one = config()

    # Ensure we do in fact have an Ursula here
    assert isinstance(ursula_one, Ursula)
    assert len(ursula_one.checksum_address) == 42
    assert ursula_one.federated_only is federated_only

    # A Temporary Ursula
    port = ursula_one.rest_information()[0].port
    assert port == UrsulaConfiguration.DEFAULT_DEVELOPMENT_REST_PORT
    assert tempfile.gettempdir() in ursula_one.datastore.engine.url.database
    assert ursula_one.certificate_filepath is CERTIFICATE_NOT_SAVED
    assert UrsulaConfiguration.TEMP_CONFIGURATION_DIR_PREFIX in ursula_one.keyring_root
    assert isinstance(ursula_one.node_storage, ForgetfulNodeStorage)
    assert ursula_one.node_storage._name == ":memory:"

    # Alternate way to produce a character with a direct call
    ursula_two = config.produce()
    assert isinstance(ursula_two, Ursula)

    # All development Ursulas are unique
    ursulas = [ursula_one, ursula_two]
    for _ in range(3):
        ursula = config()
        assert ursula not in ursulas
        ursulas.append(ursula)
Exemple #3
0
def test_ursula_view_configuration(custom_filepath, click_runner,
                                   nominal_federated_configuration_fields):

    # Ensure the configuration file still exists
    custom_config_filepath = os.path.join(
        custom_filepath, UrsulaConfiguration.generate_filename())
    assert os.path.isfile(
        custom_config_filepath), 'Configuration file does not exist'

    view_args = ('ursula', 'view', '--config-file',
                 os.path.join(custom_filepath,
                              UrsulaConfiguration.generate_filename()))

    # View the configuration
    result = click_runner.invoke(
        nucypher_cli,
        view_args,
        input='{}\n'.format(INSECURE_DEVELOPMENT_PASSWORD),
        catch_exceptions=False)

    # CLI Output
    assert 'password' in result.output, 'WARNING: User was not prompted for password'
    assert MOCK_CUSTOM_INSTALLATION_PATH in result.output
    for field in nominal_federated_configuration_fields:
        assert field in result.output, "Missing field '{}' from configuration file."

    # Make sure nothing crazy is happening...
    assert os.path.isfile(
        custom_config_filepath), 'Configuration file does not exist'
Exemple #4
0
 def create_config(self, emitter, config_file):
     if self.dev:
         return UrsulaConfiguration(
             emitter=emitter,
             dev_mode=True,
             domain=TEMPORARY_DOMAIN,
             poa=self.poa,
             light=self.light,
             registry_filepath=self.registry_filepath,
             policy_registry_filepath=self.policy_registry_filepath,
             eth_provider_uri=self.eth_provider_uri,
             signer_uri=self.signer_uri,
             gas_strategy=self.gas_strategy,
             max_gas_price=self.max_gas_price,
             checksum_address=self.operator_address,
             federated_only=self.federated_only,
             rest_host=self.rest_host,
             rest_port=self.rest_port,
             db_filepath=self.db_filepath,
             availability_check=self.availability_check,
             payment_method=self.payment_method,
             payment_provider=self.payment_provider,
             payment_network=self.payment_network)
     else:
         if not config_file:
             config_file = select_config_file(
                 emitter=emitter,
                 checksum_address=self.operator_address,
                 config_class=UrsulaConfiguration)
         try:
             return UrsulaConfiguration.from_configuration_file(
                 emitter=emitter,
                 filepath=config_file,
                 domain=self.domain,
                 registry_filepath=self.registry_filepath,
                 policy_registry_filepath=self.policy_registry_filepath,
                 eth_provider_uri=self.eth_provider_uri,
                 signer_uri=self.signer_uri,
                 gas_strategy=self.gas_strategy,
                 max_gas_price=self.max_gas_price,
                 rest_host=self.rest_host,
                 rest_port=self.rest_port,
                 db_filepath=self.db_filepath,
                 poa=self.poa,
                 light=self.light,
                 federated_only=self.federated_only,
                 availability_check=self.availability_check,
                 payment_method=self.payment_method,
                 payment_provider=self.payment_provider,
                 payment_network=self.payment_network)
         except FileNotFoundError:
             return handle_missing_configuration_file(
                 character_config_class=UrsulaConfiguration,
                 config_file=config_file)
         except Keystore.AuthenticationFailed as e:
             emitter.echo(str(e), color='red', bold=True)
             # TODO: Exit codes (not only for this, but for other exceptions)
             return click.get_current_context().exit(1)
Exemple #5
0
def ursula_federated_test_config():

    ursula_config = UrsulaConfiguration(temp=True,
                                        auto_initialize=True,
                                        is_me=True,
                                        start_learning_now=False,
                                        abort_on_learning_error=True,
                                        federated_only=True)
    yield ursula_config
    ursula_config.cleanup()
Exemple #6
0
def ursula_federated_test_config():
    ursula_config = UrsulaConfiguration(dev_mode=True,
                                        rest_port=MOCK_URSULA_STARTING_PORT,
                                        start_learning_now=False,
                                        abort_on_learning_error=True,
                                        federated_only=True,
                                        network_middleware=MockRestMiddleware(),
                                        save_metadata=False,
                                        reload_metadata=False,)
    yield ursula_config
    ursula_config.cleanup()
Exemple #7
0
def ursula_decentralized_test_config(three_agents):
    token_agent, miner_agent, policy_agent = three_agents

    ursula_config = UrsulaConfiguration(temp=True,
                                        auto_initialize=True,
                                        is_me=True,
                                        start_learning_now=False,
                                        abort_on_learning_error=True,
                                        miner_agent=miner_agent,
                                        federated_only=False)
    yield ursula_config
    ursula_config.cleanup()
Exemple #8
0
def ursula_decentralized_test_config(test_registry):
    ursula_config = UrsulaConfiguration(dev_mode=True,
                                        provider_uri=TEST_PROVIDER_URI,
                                        rest_port=MOCK_URSULA_STARTING_PORT,
                                        start_learning_now=False,
                                        abort_on_learning_error=True,
                                        federated_only=False,
                                        network_middleware=MockRestMiddleware(),
                                        save_metadata=False,
                                        reload_metadata=False,
                                        registry=test_registry)
    yield ursula_config
    ursula_config.cleanup()
Exemple #9
0
def test_ursula_destroy_configuration(custom_filepath, click_runner):

    preexisting_live_configuration = os.path.isdir(DEFAULT_CONFIG_ROOT)
    preexisting_live_configuration_file = os.path.isfile(
        os.path.join(DEFAULT_CONFIG_ROOT,
                     UrsulaConfiguration.generate_filename()))

    # Ensure the configuration file still exists
    custom_config_filepath = os.path.join(
        custom_filepath, UrsulaConfiguration.generate_filename())
    assert os.path.isfile(
        custom_config_filepath), 'Configuration file does not exist'

    # Run the destroy command
    destruction_args = ('ursula', 'destroy', '--config-file',
                        custom_config_filepath)
    result = click_runner.invoke(
        nucypher_cli,
        destruction_args,
        input='Y\n'.format(INSECURE_DEVELOPMENT_PASSWORD),
        catch_exceptions=False,
        env={NUCYPHER_ENVVAR_KEYRING_PASSWORD: INSECURE_DEVELOPMENT_PASSWORD})

    # CLI Output
    assert not os.path.isfile(
        custom_config_filepath), 'Configuration file still exists'
    assert '? [y/N]:' in result.output, 'WARNING: User was not asked to destroy files'
    assert str(
        custom_filepath
    ) in result.output, 'WARNING: Configuration path not in output. Deleting the wrong path?'
    assert SUCCESSFUL_DESTRUCTION in result.output, '"Destroyed" not in output'
    assert str(custom_filepath) in result.output
    assert result.exit_code == 0, 'Destruction did not succeed'

    # Ensure the files are deleted from the filesystem
    assert not os.path.isfile(
        custom_config_filepath), 'Files still exist'  # ... shes's gone...
    assert os.path.isdir(
        custom_filepath
    ), 'Nucypher files no longer exist'  # ... but not NuCypher ...

    # If this test started off with a live configuration, ensure it still exists
    if preexisting_live_configuration:
        configuration_still_exists = os.path.isdir(DEFAULT_CONFIG_ROOT)
        assert configuration_still_exists

    if preexisting_live_configuration_file:
        file_still_exists = os.path.isfile(
            os.path.join(DEFAULT_CONFIG_ROOT,
                         UrsulaConfiguration.generate_filename()))
        assert file_still_exists, 'WARNING: Test command deleted live non-test files'
Exemple #10
0
def ursula_decentralized_test_config(three_agents):
    ursula_config = UrsulaConfiguration(dev_mode=True,
                                        is_me=True,
                                        provider_uri="tester://pyevm",
                                        rest_port=MOCK_URSULA_STARTING_PORT,
                                        start_learning_now=False,
                                        abort_on_learning_error=True,
                                        federated_only=False,
                                        network_middleware=MockRestMiddleware(),
                                        import_seed_registry=False,
                                        save_metadata=False,
                                        reload_metadata=False)
    yield ursula_config
    ursula_config.cleanup()
Exemple #11
0
def ursula_federated_test_config():

    ursula_config = UrsulaConfiguration(temp=True,
                                        auto_initialize=True,
                                        auto_generate_keys=True,
                                        passphrase=TEST_URSULA_INSECURE_DEVELOPMENT_PASSWORD,
                                        is_me=True,
                                        start_learning_now=False,
                                        abort_on_learning_error=True,
                                        federated_only=True,
                                        network_middleware=MockRestMiddleware(),
                                        save_metadata=False,
                                        load_metadata=False)
    yield ursula_config
    ursula_config.cleanup()
def test_federated_ursula_development_configuration():

    # Configure & Produce Ursula
    ursula_config = UrsulaConfiguration(dev_mode=True, federated_only=True)
    ursula = ursula_config.produce()

    # Network Port
    port = ursula.rest_information()[0].port
    assert port == UrsulaConfiguration.DEFAULT_DEVELOPMENT_REST_PORT

    # Database
    assert tempfile.gettempdir() in ursula.datastore.engine.url.database

    # TLS Certificate
    assert ursula.certificate_filepath is CERTIFICATE_NOT_SAVED
Exemple #13
0
def test_password_prompt(click_runner, custom_filepath):

    # Ensure the configuration file still exists
    custom_config_filepath = os.path.join(
        custom_filepath, UrsulaConfiguration.generate_filename())
    assert os.path.isfile(
        custom_config_filepath), 'Configuration file does not exist'

    view_args = ('ursula', 'view', '--config-file', custom_config_filepath,
                 '--federated-only')

    user_input = '{}\n'.format(INSECURE_DEVELOPMENT_PASSWORD)
    result = click_runner.invoke(nucypher_cli,
                                 view_args,
                                 input=user_input,
                                 catch_exceptions=False,
                                 env=dict())
    assert 'password' in result.output, 'WARNING: User was not prompted for password'
    assert result.exit_code == 0

    envvars = {'NUCYPHER_KEYRING_PASSWORD': INSECURE_DEVELOPMENT_PASSWORD}
    result = click_runner.invoke(nucypher_cli,
                                 view_args,
                                 input=user_input,
                                 catch_exceptions=False,
                                 env=envvars)
    assert not 'password' in result.output, 'User was prompted for password'
    assert result.exit_code == 0
Exemple #14
0
def make_decentralized_ursulas(ursula_config: UrsulaConfiguration,
                               stakers_addresses: Iterable[str],
                               workers_addresses: Iterable[str],
                               commit_to_next_period: bool = False,
                               **ursula_overrides) -> List[Ursula]:

    if not MOCK_KNOWN_URSULAS_CACHE:
        starting_port = MOCK_URSULA_STARTING_PORT
    else:
        starting_port = max(MOCK_KNOWN_URSULAS_CACHE.keys()) + 1

    stakers_and_workers = zip(stakers_addresses, workers_addresses)
    ursulas = list()

    for port, (staker_address, worker_address) in enumerate(stakers_and_workers, start=starting_port):
        ursula = ursula_config.produce(checksum_address=staker_address,
                                       worker_address=worker_address,
                                       db_filepath=tempfile.mkdtemp(),
                                       rest_port=port + 100,
                                       **ursula_overrides)
        if commit_to_next_period:
            # TODO: Is _crypto_power trying to be public?  Or is there a way to expose *something* public about TransactingPower?
            # Do we need to revisit the concept of "public material"?  Or does this rightly belong as a method?
            tx_power = ursula._crypto_power.power_ups(TransactingPower)
            tx_power.activate()
            ursula.commit_to_next_period()

        ursulas.append(ursula)
        # Store this Ursula in our global cache.
        port = ursula.rest_interface.port
        MOCK_KNOWN_URSULAS_CACHE[port] = ursula

    return ursulas
Exemple #15
0
def make_federated_ursulas(ursula_config: UrsulaConfiguration,
                           quantity: int = NUMBER_OF_URSULAS_IN_DEVELOPMENT_NETWORK,
                           know_each_other: bool = True,
                           **ursula_overrides) -> Set[Ursula]:

    if not MOCK_KNOWN_URSULAS_CACHE:
        starting_port = MOCK_URSULA_STARTING_PORT
    else:
        starting_port = max(MOCK_KNOWN_URSULAS_CACHE.keys()) + 1

    federated_ursulas = set()
    for port in range(starting_port, starting_port+quantity):

        ursula = ursula_config.produce(rest_port=port + 100,
                                       db_filepath=MOCK_URSULA_DB_FILEPATH,
                                       **ursula_overrides)

        federated_ursulas.add(ursula)

        # Store this Ursula in our global testing cache.

        port = ursula.rest_interface.port
        MOCK_KNOWN_URSULAS_CACHE[port] = ursula

    if know_each_other:
        for ursula_to_teach in federated_ursulas:
            # Add other Ursulas as known nodes.
            for ursula_to_learn_about in federated_ursulas:
                ursula_to_teach.remember_node(ursula_to_learn_about)

    return federated_ursulas
Exemple #16
0
def make_decentralized_ursulas(ursula_config: UrsulaConfiguration,
                               stakers_addresses: Iterable[str],
                               workers_addresses: Iterable[str],
                               commit_to_next_period: bool = False,
                               **ursula_overrides) -> List[Ursula]:

    if not MOCK_KNOWN_URSULAS_CACHE:
        starting_port = MOCK_URSULA_STARTING_PORT
    else:
        starting_port = max(MOCK_KNOWN_URSULAS_CACHE.keys()) + 1

    stakers_and_workers = zip(stakers_addresses, workers_addresses)
    ursulas = list()

    for port, (staker_address, worker_address) in enumerate(stakers_and_workers, start=starting_port):
        ursula = ursula_config.produce(checksum_address=staker_address,
                                       worker_address=worker_address,
                                       db_filepath=MOCK_URSULA_DB_FILEPATH,
                                       rest_port=port + 100,
                                       **ursula_overrides)
        if commit_to_next_period:
            ursula.transacting_power.activate()
            ursula.commit_to_next_period()

        ursulas.append(ursula)
        # Store this Ursula in our global cache.
        port = ursula.rest_interface.port
        MOCK_KNOWN_URSULAS_CACHE[port] = ursula

    return ursulas
Exemple #17
0
    def __make_ursula():
        if not checksum_address and not config.dev:
            raise click.BadArgumentUsage(
                "No Configuration file found, and no --checksum address <addr> was provided."
            )
        if not checksum_address and not config.dev:
            raise click.BadOptionUsage(
                message="No account specified. pass --checksum-address, --dev, "
                "or use a configuration file with --config-file <path>")

        return UrsulaConfiguration(temp=config.dev,
                                   auto_initialize=config.dev,
                                   is_me=True,
                                   rest_host=rest_host,
                                   rest_port=rest_port,
                                   db_name=db_name,
                                   federated_only=config.federated_only,
                                   registry_filepath=config.registry_filepath,
                                   provider_uri=config.provider_uri,
                                   checksum_address=checksum_address,
                                   poa=config.poa,
                                   save_metadata=False,
                                   load_metadata=True,
                                   start_learning_now=True,
                                   learn_on_same_thread=False,
                                   abort_on_learning_error=config.dev)
Exemple #18
0
def make_decentralized_ursulas(ursula_config: UrsulaConfiguration,
                               blockchain: BlockchainInterface,
                               stakers_addresses: Iterable[str],
                               workers_addresses: Iterable[str],
                               confirm_activity: bool = False,
                               **ursula_overrides) -> List[Ursula]:

    if not MOCK_KNOWN_URSULAS_CACHE:
        starting_port = MOCK_URSULA_STARTING_PORT
    else:
        starting_port = max(MOCK_KNOWN_URSULAS_CACHE.keys()) + 1

    stakers_and_workers = zip(stakers_addresses, workers_addresses)
    ursulas = list()

    stake_tracker = StakeTracker(checksum_addresses=list(stakers_addresses))
    for port, (staker_address, worker_address) in enumerate(stakers_and_workers, start=starting_port):

        ursula = ursula_config.produce(checksum_address=staker_address,
                                       worker_address=worker_address,
                                       blockchain=blockchain,
                                       db_filepath=MOCK_URSULA_DB_FILEPATH,
                                       rest_port=port + 100,
                                       stake_tracker=stake_tracker,
                                       **ursula_overrides)
        if confirm_activity:
            ursula.confirm_activity()

        ursulas.append(ursula)
        # Store this Ursula in our global cache.
        port = ursula.rest_interface.port
        MOCK_KNOWN_URSULAS_CACHE[port] = ursula

    return ursulas
Exemple #19
0
def test_ursula_run(click_runner,
                    manual_worker,
                    manual_staker,
                    custom_filepath,
                    testerchain):

    custom_config_filepath = os.path.join(custom_filepath, UrsulaConfiguration.generate_filename())

    # Simulate "Reconnection" within the CLI process to the testerchain
    def connect(self, *args, **kwargs):
        self._attach_provider(testerchain.provider)
        self.w3 = self.Web3(provider=self._provider)
        self.client = Web3Client.from_w3(w3=self.w3)
    BlockchainInterface.connect = connect

    # Now start running your Ursula!
    init_args = ('ursula', 'run',
                 '--dry-run',
                 '--config-file', custom_config_filepath)

    user_input = f'{INSECURE_DEVELOPMENT_PASSWORD}\n' * 2
    result = click_runner.invoke(nucypher_cli,
                                 init_args,
                                 input=user_input,
                                 catch_exceptions=False)
    assert result.exit_code == 0
Exemple #20
0
def test_render_lonely_ursula_status_page(tmpdir):
    ursula_config = UrsulaConfiguration(dev_mode=True, federated_only=True)
    ursula = ursula_config()

    rendering = status_template.render(this_node=ursula, known_nodes=ursula.known_nodes)
    assert '<!DOCTYPE html>' in rendering
    assert ursula.nickname in rendering
Exemple #21
0
    def generate_config(self, emitter, config_root, force):

        assert not self.dev

        staker_address = self.staker_address
        worker_address = self.worker_address
        if (not staker_address or not worker_address) and not self.federated_only:
            if not staker_address:
                staker_address = click.prompt("Enter staker address", type=EIP55_CHECKSUM_ADDRESS)

            if not worker_address:
                prompt = "Select worker account"
                worker_address = select_client_account(emitter=emitter,
                                                       prompt=prompt,
                                                       provider_uri=self.provider_uri,
                                                       show_balances=False)

        rest_host = self.rest_host
        if not rest_host:
            rest_host = actions.determine_external_ip_address(emitter, force=force)

        return UrsulaConfiguration.generate(password=get_nucypher_password(confirm=True),
                                            config_root=config_root,
                                            rest_host=rest_host,
                                            rest_port=self.rest_port,
                                            db_filepath=self.db_filepath,
                                            domains=self.domains,
                                            federated_only=self.federated_only,
                                            checksum_address=staker_address,
                                            worker_address=worker_address,
                                            registry_filepath=self.registry_filepath,
                                            provider_process=self.eth_node,
                                            provider_uri=self.provider_uri,
                                            poa=self.poa,
                                            light=self.light)
Exemple #22
0
def test_configuration_file_contents(custom_filepath,
                                     nominal_federated_configuration_fields):
    custom_config_filepath = os.path.join(
        custom_filepath, UrsulaConfiguration.generate_filename())
    assert os.path.isfile(
        custom_config_filepath), 'Configuration file does not exist'

    # Check the contents of the configuration file
    with open(custom_config_filepath, 'r') as config_file:
        raw_contents = config_file.read()

        try:
            data = json.loads(raw_contents)
        except JSONDecodeError:
            raise pytest.fail(msg="Invalid JSON configuration file {}".format(
                custom_config_filepath))

        for field in nominal_federated_configuration_fields:
            assert field in data, "Missing field '{}' from configuration file."
            if any(keyword in field for keyword in ('path', 'dir')):
                path = data[field]
                user_data_dir = APP_DIR.user_data_dir
                # assert os.path.exists(path), '{} does not exist'.format(path)
                assert user_data_dir not in path, '{} includes default appdir path {}'.format(
                    field, user_data_dir)

    assert os.path.isfile(
        custom_config_filepath), 'Configuration file does not exist'
def test_ursula_init(click_runner, custom_filepath, agency_local_registry,
                     manual_staker, manual_worker, testerchain):

    deploy_port = select_test_port()

    init_args = ('ursula', 'init', '--network', TEMPORARY_DOMAIN,
                 '--worker-address', manual_worker, '--config-root',
                 str(custom_filepath.absolute()), '--provider',
                 TEST_PROVIDER_URI, '--registry-filepath',
                 str(agency_local_registry.filepath.absolute()), '--rest-host',
                 MOCK_IP_ADDRESS, '--rest-port', deploy_port)

    result = click_runner.invoke(nucypher_cli,
                                 init_args,
                                 input=FAKE_PASSWORD_CONFIRMED,
                                 catch_exceptions=False)
    assert result.exit_code == 0

    # Files and Directories
    assert custom_filepath.is_dir(), 'Configuration file does not exist'
    assert (custom_filepath / 'keystore').is_dir(), 'KEYSTORE does not exist'
    assert (custom_filepath /
            'known_nodes').is_dir(), 'known_nodes directory does not exist'

    custom_config_filepath = custom_filepath / UrsulaConfiguration.generate_filename(
    )
    assert custom_config_filepath.is_file(
    ), 'Configuration file does not exist'

    with open(custom_config_filepath, 'r') as config_file:
        raw_config_data = config_file.read()
        config_data = json.loads(raw_config_data)
        assert config_data['provider_uri'] == TEST_PROVIDER_URI
        assert config_data['worker_address'] == manual_worker
        assert TEMPORARY_DOMAIN == config_data['domain']
def test_ursula_view_configuration(custom_filepath: Path, click_runner,
                                   nominal_federated_configuration_fields):

    # Ensure the configuration file still exists
    custom_config_filepath = custom_filepath / UrsulaConfiguration.generate_filename(
    )
    assert custom_config_filepath.is_file(
    ), 'Configuration file does not exist'

    view_args = ('ursula', 'config', '--config-file',
                 str(custom_config_filepath.absolute()))

    # View the configuration
    result = click_runner.invoke(
        nucypher_cli,
        view_args,
        input='{}\n'.format(INSECURE_DEVELOPMENT_PASSWORD),
        catch_exceptions=False)

    # CLI Output
    assert str(MOCK_CUSTOM_INSTALLATION_PATH) in result.output
    for field in nominal_federated_configuration_fields:
        assert field in result.output, "Missing field '{}' from configuration file."

    # Make sure nothing crazy is happening...
    assert custom_config_filepath.is_file(
    ), 'Configuration file does not exist'
Exemple #25
0
def test_ursula_init(click_runner, custom_filepath, agency_local_registry,
                     preallocation_escrow_agent, manual_worker, testerchain):

    init_args = ('ursula', 'init', '--network', TEMPORARY_DOMAIN,
                 '--worker-address', manual_worker, '--config-root',
                 custom_filepath, '--provider', TEST_PROVIDER_URI,
                 '--registry-filepath', agency_local_registry.filepath,
                 '--rest-host', MOCK_IP_ADDRESS, '--rest-port',
                 MOCK_URSULA_STARTING_PORT)

    result = click_runner.invoke(nucypher_cli,
                                 init_args,
                                 input=FAKE_PASSWORD_CONFIRMED,
                                 catch_exceptions=False)
    assert result.exit_code == 0

    # Files and Directories
    assert os.path.isdir(custom_filepath), 'Configuration file does not exist'
    assert os.path.isdir(os.path.join(custom_filepath,
                                      'keyring')), 'Keyring does not exist'
    assert os.path.isdir(
        os.path.join(custom_filepath,
                     'known_nodes')), 'known_nodes directory does not exist'

    custom_config_filepath = os.path.join(
        custom_filepath, UrsulaConfiguration.generate_filename())
    assert os.path.isfile(
        custom_config_filepath), 'Configuration file does not exist'

    with open(custom_config_filepath, 'r') as config_file:
        raw_config_data = config_file.read()
        config_data = json.loads(raw_config_data)
        assert config_data['provider_uri'] == TEST_PROVIDER_URI
        assert config_data['worker_address'] == manual_worker
        assert TEMPORARY_DOMAIN in config_data['domains']
Exemple #26
0
def test_run_federated_ursula_from_config_file(custom_filepath, click_runner):

    # Ensure the configuration file still exists
    custom_config_filepath = os.path.join(
        custom_filepath, UrsulaConfiguration.generate_filename())
    assert os.path.isfile(
        custom_config_filepath), 'Configuration file does not exist'

    # Run Ursula
    run_args = ('ursula', 'run', '--dry-run', '--interactive', '--config-file',
                custom_config_filepath)

    result = click_runner.invoke(
        nucypher_cli,
        run_args,
        input='{}\nY\n'.format(INSECURE_DEVELOPMENT_PASSWORD),
        catch_exceptions=False)

    # CLI Output
    assert result.exit_code == 0
    assert 'Federated' in result.output, 'WARNING: Federated ursula is not running in federated mode'
    assert 'Connecting' in result.output
    assert 'Running' in result.output
    assert 'Attached' in result.output
    assert "'help' or '?'" in result.output
def test_initialize_custom_configuration_root(custom_filepath, click_runner):

    # Use a custom local filepath for configuration
    init_args = ('ursula', 'init',
                 '--network', TEMPORARY_DOMAIN,
                 '--federated-only',
                 '--config-root', custom_filepath,
                 '--rest-host', MOCK_IP_ADDRESS,
                 '--rest-port', MOCK_URSULA_STARTING_PORT)

    user_input = '{password}\n{password}'.format(password=INSECURE_DEVELOPMENT_PASSWORD)
    result = click_runner.invoke(nucypher_cli, init_args, input=user_input, catch_exceptions=False)
    assert result.exit_code == 0

    # CLI Output
    assert MOCK_CUSTOM_INSTALLATION_PATH in result.output, "Configuration not in system temporary directory"
    assert "nucypher ursula run" in result.output, 'Help message is missing suggested command'
    assert 'IPv4' not in result.output

    # Files and Directories
    assert os.path.isdir(custom_filepath), 'Configuration file does not exist'
    assert os.path.isdir(os.path.join(custom_filepath, 'keyring')), 'Keyring does not exist'
    assert os.path.isdir(os.path.join(custom_filepath, 'known_nodes')), 'known_nodes directory does not exist'

    custom_config_filepath = os.path.join(custom_filepath, UrsulaConfiguration.generate_filename())
    assert os.path.isfile(custom_config_filepath), 'Configuration file does not exist'

    # Auth
    assert 'Enter NuCypher keyring password' in result.output, 'WARNING: User was not prompted for password'
    assert 'Repeat for confirmation:' in result.output, 'User was not prompted to confirm password'
Exemple #28
0
def _get_ursula_config(emitter, geth, provider_uri, network, registry_filepath,
                       dev, config_file, staker_address, worker_address,
                       federated_only, rest_host, rest_port, db_filepath, poa):

    ETH_NODE = NO_BLOCKCHAIN_CONNECTION
    if geth:
        ETH_NODE = actions.get_provider_process()
        provider_uri = ETH_NODE.provider_uri(scheme='file')

    if dev:
        ursula_config = UrsulaConfiguration(
            dev_mode=True,
            domains={TEMPORARY_DOMAIN},
            poa=poa,
            registry_filepath=registry_filepath,
            provider_process=ETH_NODE,
            provider_uri=provider_uri,
            checksum_address=staker_address,
            worker_address=worker_address,
            federated_only=federated_only,
            rest_host=rest_host,
            rest_port=rest_port,
            db_filepath=db_filepath)
    else:
        try:
            ursula_config = UrsulaConfiguration.from_configuration_file(
                filepath=config_file,
                domains={network} if network else None,
                registry_filepath=registry_filepath,
                provider_process=ETH_NODE,
                provider_uri=provider_uri,
                rest_host=rest_host,
                rest_port=rest_port,
                db_filepath=db_filepath,
                poa=poa,
                federated_only=federated_only)
        except FileNotFoundError:
            return actions.handle_missing_configuration_file(
                character_config_class=UrsulaConfiguration,
                config_file=config_file)
        except NucypherKeyring.AuthenticationFailed as e:
            emitter.echo(str(e), color='red', bold=True)
            # TODO: Exit codes (not only for this, but for other exceptions)
            return click.get_current_context().exit(1)

    return ursula_config, provider_uri
Exemple #29
0
 def create_config(self, emitter, config_file):
     if self.dev:
         return UrsulaConfiguration(
             emitter=emitter,
             dev_mode=True,
             domains={TEMPORARY_DOMAIN},
             poa=self.poa,
             light=self.light,
             registry_filepath=self.registry_filepath,
             provider_process=self.eth_node,
             provider_uri=self.provider_uri,
             signer_uri=self.signer_uri,
             gas_strategy=self.gas_strategy,
             checksum_address=self.worker_address,
             federated_only=self.federated_only,
             rest_host=self.rest_host,
             rest_port=self.rest_port,
             db_filepath=self.db_filepath,
             availability_check=self.availability_check)
     else:
         try:
             return UrsulaConfiguration.from_configuration_file(
                 emitter=emitter,
                 filepath=config_file,
                 domains=self.domains,
                 registry_filepath=self.registry_filepath,
                 provider_process=self.eth_node,
                 provider_uri=self.provider_uri,
                 signer_uri=self.signer_uri,
                 gas_strategy=self.gas_strategy,
                 rest_host=self.rest_host,
                 rest_port=self.rest_port,
                 db_filepath=self.db_filepath,
                 poa=self.poa,
                 light=self.light,
                 federated_only=self.federated_only,
                 availability_check=self.availability_check)
         except FileNotFoundError:
             return handle_missing_configuration_file(
                 character_config_class=UrsulaConfiguration,
                 config_file=config_file)
         except NucypherKeyring.AuthenticationFailed as e:
             emitter.echo(str(e), color='red', bold=True)
             # TODO: Exit codes (not only for this, but for other exceptions)
             return click.get_current_context().exit(1)
Exemple #30
0
def ursula_decentralized_test_config(three_agents):
    token_agent, miner_agent, policy_agent = three_agents

    ursula_config = UrsulaConfiguration(
        temp=True,
        auto_initialize=True,
        auto_generate_keys=True,
        passphrase=TEST_URSULA_INSECURE_DEVELOPMENT_PASSWORD,
        is_me=True,
        start_learning_now=False,
        abort_on_learning_error=True,
        federated_only=False,
        network_middleware=MockRestMiddleware(),
        import_seed_registry=False,
        save_metadata=False,
        load_metadata=False)
    yield ursula_config
    ursula_config.cleanup()