def _get_or_create_alice_config(click_config, dev, network, eth_node, provider_uri, config_file, discovery_port, pay_with, registry_filepath): if dev: alice_config = AliceConfiguration( dev_mode=True, network_middleware=click_config.middleware, domains={network}, provider_process=eth_node, provider_uri=provider_uri, federated_only=True) else: try: alice_config = AliceConfiguration.from_configuration_file( dev_mode=False, filepath=config_file, domains={network} if network else None, network_middleware=click_config.middleware, rest_port=discovery_port, checksum_address=pay_with, provider_process=eth_node, provider_uri=provider_uri, registry_filepath=registry_filepath) except FileNotFoundError: return actions.handle_missing_configuration_file( character_config_class=AliceConfiguration, config_file=config_file) return alice_config
def view(click_config, config_file): """ View existing Alice's configuration. """ emitter = _setup_emitter(click_config) configuration_file_location = config_file or AliceConfiguration.default_filepath() response = AliceConfiguration._read_configuration_file(filepath=configuration_file_location) return emitter.ipc(response=response, request_id=0, duration=0) # FIXME: what are request_id and duration here?
def view(general_config, config_file): """ View existing Alice's configuration. """ emitter = _setup_emitter(general_config) configuration_file_location = config_file or AliceConfiguration.default_filepath() response = AliceConfiguration._read_configuration_file(filepath=configuration_file_location) emitter.echo(f"Alice Configuration {configuration_file_location} \n {'='*55}") return emitter.echo(json.dumps(response, indent=4))
def alice_federated_test_config(federated_ursulas): config = AliceConfiguration(temp=True, auto_initialize=True, is_me=True, network_middleware=MockRestMiddleware(), known_nodes=federated_ursulas, federated_only=True, abort_on_learning_error=True) yield config config.cleanup()
def alice_federated_test_config(federated_ursulas): config = AliceConfiguration(dev_mode=True, network_middleware=MockRestMiddleware(), known_nodes=federated_ursulas, federated_only=True, abort_on_learning_error=True, save_metadata=False, reload_metadata=False) yield config config.cleanup()
def create_config(self, emitter, config_file): if self.dev: # Can be None as well, meaning it is unset - no error in this case if self.federated_only is False: raise click.BadOptionUsage( option_name="--federated-only", message=click.style( "--federated-only cannot be explicitly set to False when --dev is set", fg="red")) return AliceConfiguration(emitter=emitter, dev_mode=True, network_middleware=self.middleware, domain=TEMPORARY_DOMAIN, eth_provider_uri=self.eth_provider_uri, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, federated_only=True, lonely=self.lonely, 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.pay_with, config_class=AliceConfiguration) try: return AliceConfiguration.from_configuration_file( emitter=emitter, dev_mode=False, network_middleware=self.middleware, domain=self.domain, eth_provider_uri=self.eth_provider_uri, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, filepath=config_file, rest_port=self.discovery_port, checksum_address=self.pay_with, registry_filepath=self.registry_filepath, lonely=self.lonely, 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=AliceConfiguration, config_file=config_file)
def alice_blockchain_test_config(blockchain_ursulas, testerchain): config = AliceConfiguration(dev_mode=True, provider_uri=TEST_PROVIDER_URI, checksum_address=testerchain.alice_account, network_middleware=MockRestMiddleware(), known_nodes=blockchain_ursulas, abort_on_learning_error=True, download_registry=False, save_metadata=False, reload_metadata=False) yield config config.cleanup()
def highperf_mocked_alice(fleet_of_highperf_mocked_ursulas): config = AliceConfiguration(dev_mode=True, domains={TEMPORARY_DOMAIN}, network_middleware=MockRestMiddlewareForLargeFleetTests(), federated_only=True, abort_on_learning_error=True, save_metadata=False, reload_metadata=False) with mock_cert_storage, mock_verify_node, mock_record_fleet_state, mock_message_verification, mock_keep_learning: alice = config.produce(known_nodes=list(fleet_of_highperf_mocked_ursulas)[:1]) return alice
def alice_federated_test_config(federated_ursulas): config = AliceConfiguration(temp=True, auto_initialize=True, auto_generate_keys=True, passphrase=TEST_URSULA_INSECURE_DEVELOPMENT_PASSWORD, is_me=True, network_middleware=MockRestMiddleware(), known_nodes=federated_ursulas, federated_only=True, abort_on_learning_error=True, save_metadata=False, load_metadata=False) yield config config.cleanup()
def alice_blockchain_test_config(blockchain_ursulas, three_agents): token_agent, miner_agent, policy_agent = three_agents etherbase, alice_address, bob_address, *everyone_else = token_agent.blockchain.interface.w3.eth.accounts config = AliceConfiguration(temp=True, is_me=True, auto_initialize=True, network_middleware=MockRestMiddleware(), policy_agent=policy_agent, known_nodes=blockchain_ursulas, abort_on_learning_error=True, checksum_address=alice_address) yield config config.cleanup()
def highperf_mocked_alice(fleet_of_highperf_mocked_ursulas): config = AliceConfiguration(dev_mode=True, domain=TEMPORARY_DOMAIN, network_middleware=MockRestMiddlewareForLargeFleetTests(), federated_only=True, abort_on_learning_error=True, save_metadata=False, reload_metadata=False) with mock_cert_storage, mock_verify_node, mock_record_fleet_state, mock_message_verification, mock_keep_learning: alice = config.produce(known_nodes=list(fleet_of_highperf_mocked_ursulas)[:1]) yield alice # TODO: Where does this really, truly belong? alice._learning_task.stop()
def alice_blockchain_test_config(blockchain_ursulas, three_agents): token_agent, miner_agent, policy_agent = three_agents config = AliceConfiguration( dev_mode=True, is_me=True, provider_uri="tester://pyevm", checksum_public_address=token_agent.blockchain.alice_account, network_middleware=MockRestMiddleware(), known_nodes=blockchain_ursulas, abort_on_learning_error=True, import_seed_registry=False, save_metadata=False, reload_metadata=False) yield config config.cleanup()
def test_alice_control_starts_with_mocked_keyring(click_runner, mocker, monkeypatch, custom_filepath): monkeypatch.delenv(NUCYPHER_ENVVAR_KEYRING_PASSWORD, raising=False) class MockKeyring: is_unlocked = False keyring_root = custom_filepath / 'keyring' checksum_address = None def derive_crypto_power(self, power_class, *args, **kwargs): return power_class() @classmethod def unlock(cls, password, *args, **kwargs): assert password == INSECURE_DEVELOPMENT_PASSWORD cls.is_unlocked = True mocker.patch.object(AliceConfiguration, "attach_keyring", return_value=None) good_enough_config = AliceConfiguration(dev_mode=True, federated_only=True, keyring=MockKeyring()) mocker.patch.object(AliceConfiguration, "from_configuration_file", return_value=good_enough_config) init_args = ('alice', 'run', '-x', '--lonely', '--network', TEMPORARY_DOMAIN) result = click_runner.invoke(nucypher_cli, init_args, input=FAKE_PASSWORD_CONFIRMED) assert result.exit_code == 0, result.exception
def generate_config(self, emitter, config_root): opts = self.config_options if opts.dev: raise click.BadArgumentUsage( "Cannot create a persistent development character") if not opts.provider_uri and not opts.federated_only: raise click.BadOptionUsage( option_name='--provider', message= "--provider is required to create a new decentralized alice.") pay_with = opts.pay_with if not pay_with and not opts.federated_only: pay_with = select_client_account(emitter=emitter, provider_uri=opts.provider_uri, show_eth_balance=True) return AliceConfiguration.generate( password=get_nucypher_password(confirm=True), config_root=config_root, checksum_address=pay_with, domains=opts.domains, federated_only=opts.federated_only, provider_uri=opts.provider_uri, signer_uri=opts.signer_uri, provider_process=opts.eth_node, registry_filepath=opts.registry_filepath, poa=self.poa, light=self.light, m=self.m, n=self.n, duration_periods=self.duration_periods)
def test_alice_control_starts_with_mocked_keyring(click_runner, mocker, monkeypatch): monkeypatch.delenv("NUCYPHER_KEYRING_PASSWORD", raising=False) class MockKeyring: is_unlocked = False @classmethod def unlock(cls, password, *args, **kwargs): assert password == INSECURE_DEVELOPMENT_PASSWORD cls.is_unlocked = True mocker.patch.object(AliceConfiguration, "attach_keyring", return_value=None) good_enough_config = AliceConfiguration(dev_mode=True, federated_only=True, keyring=MockKeyring) mocker.patch.object(AliceConfiguration, "from_configuration_file", return_value=good_enough_config) init_args = ('alice', 'run', '-x') user_input = '{password}\n{password}\n'.format( password=INSECURE_DEVELOPMENT_PASSWORD) result = click_runner.invoke(nucypher_cli, init_args, input=user_input) assert result.exit_code == 0, result.exception
def test_initialize_alice_with_custom_configuration_root(custom_filepath, click_runner): # Use a custom local filepath for configuration init_args = ('alice', 'init', '--network', TEMPORARY_DOMAIN, '--federated-only', '--config-root', custom_filepath) user_input = '{password}\n{password}'.format(password=INSECURE_DEVELOPMENT_PASSWORD, ip=MOCK_IP_ADDRESS) 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 alice 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, AliceConfiguration.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'
def test_alice_control_starts_with_mocked_keystore(click_runner, mocker, monkeypatch, custom_filepath): monkeypatch.delenv(NUCYPHER_ENVVAR_KEYSTORE_PASSWORD, raising=False) class MockKeystore: is_unlocked = False keystore_dir = custom_filepath / 'keystore' keystore_path = custom_filepath / 'keystore' / 'path.json' def derive_crypto_power(self, power_class, *args, **kwargs): return power_class() @classmethod def unlock(cls, password, *args, **kwargs): assert password == INSECURE_DEVELOPMENT_PASSWORD cls.is_unlocked = True good_enough_config = AliceConfiguration(dev_mode=True, federated_only=True, keystore=MockKeystore()) mocker.patch.object(AliceConfigOptions, "create_config", return_value=good_enough_config) init_args = ('alice', 'run', '-x', '--lonely', '--network', TEMPORARY_DOMAIN) result = click_runner.invoke(nucypher_cli, init_args, input=FAKE_PASSWORD_CONFIRMED) assert result.exit_code == 0, result.output
def generate_config(self, emitter: StdoutEmitter, config_root: Path, key_material: str) -> AliceConfiguration: opts = self.config_options if opts.dev: raise click.BadArgumentUsage("Cannot create a persistent development character") if not opts.provider_uri and not opts.federated_only: raise click.BadOptionUsage( option_name='--provider', message="--provider is required to create a new decentralized alice.") pay_with = opts.pay_with if not pay_with and not opts.federated_only: pay_with = select_client_account(emitter=emitter, provider_uri=opts.provider_uri, signer_uri=opts.signer_uri, show_eth_balance=True, network=opts.domain) return AliceConfiguration.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=pay_with, domain=opts.domain, federated_only=opts.federated_only, provider_uri=opts.provider_uri, signer_uri=opts.signer_uri, registry_filepath=opts.registry_filepath, poa=self.poa, light=self.light, threshold=self.threshold, shares=self.shares, payment_periods=self.payment_periods)
def test_initialize_alice_with_custom_configuration_root(custom_filepath, click_runner, monkeypatch): monkeypatch.delenv(NUCYPHER_ENVVAR_KEYRING_PASSWORD, raising=False) # Use a custom local filepath for configuration init_args = ('alice', 'init', '--network', TEMPORARY_DOMAIN, '--federated-only', '--config-root', custom_filepath) result = click_runner.invoke(nucypher_cli, init_args, input=FAKE_PASSWORD_CONFIRMED, catch_exceptions=False) assert result.exit_code == 0 # CLI Output assert str(MOCK_CUSTOM_INSTALLATION_PATH) in result.output, "Configuration not in system temporary directory" assert "nucypher alice 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, AliceConfiguration.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'
def act_as_alice(self, name, password): dirname = "accounts/" + name + "/" congifloc = dirname + "alice.config" alice_config = AliceConfiguration( config_root=os.path.join(dirname), is_me=True, known_nodes={self.ursula}, start_learning_now=False, federated_only=True, learn_on_same_thread=True, ) cfg = alice_config.from_configuration_file(congifloc) cfg.keyring.unlock(password) alice = cfg.produce() # alice.start_learning_loop(now=True) return alice
def test_alice_destroy(click_runner, custom_filepath): """Should be the last test since it deletes the configuration file""" custom_config_filepath = custom_filepath / AliceConfiguration.generate_filename() destroy_args = ('alice', 'destroy', '--config-file', custom_config_filepath, '--force') result = click_runner.invoke(nucypher_cli, destroy_args, catch_exceptions=False) assert result.exit_code == 0 assert SUCCESSFUL_DESTRUCTION in result.output assert not custom_config_filepath.exists(), "Alice config file was deleted"
def createGenericAlicia(passphrase): print('createGenericAlicia') TEMP_ALICE_DIR = os.path.join('/', 'tmp', 'zkDonationFlaskApp') shutil.rmtree(TEMP_ALICE_DIR, ignore_errors=True) ursula = Ursula.from_seed_and_stake_info(seed_uri=SEEDNODE_URI, federated_only=True, minimum_stake=0) alice_config = AliceConfiguration( config_root=os.path.join(TEMP_ALICE_DIR), domains={TEMPORARY_DOMAIN}, known_nodes={ursula}, start_learning_now=False, federated_only=True, learn_on_same_thread=True, ) alice_config.initialize(password=passphrase) alice_config.keyring.unlock(password=passphrase) alicia = alice_config.produce() alice_config.to_configuration_file() alicia.start_learning_loop(now=True) return alicia
def test_alice_view_preexisting_configuration(click_runner, custom_filepath): custom_config_filepath = os.path.join(custom_filepath, AliceConfiguration.generate_filename()) view_args = ('alice', 'config', '--config-file', custom_config_filepath) result = click_runner.invoke(nucypher_cli, view_args, input=FAKE_PASSWORD_CONFIRMED) assert result.exit_code == 0 assert "checksum_address" in result.output assert "domain" in result.output assert TEMPORARY_DOMAIN in result.output assert str(custom_filepath) in result.output
def configure_alice(self, path): return AliceConfiguration( config_root=os.path.join(path), known_nodes=[self.ursula, self.ursula2, self.ursula3], start_learning_now=False, federated_only=True, learn_on_same_thread=True, network_middleware=RestMiddleware(), )
def make_alice(known_nodes: Optional[Set[Ursula]] = None): """Initializes a new 'persistent alice configuration' for grant metrics collection.""" alice_config = AliceConfiguration(provider_uri=ETHEREUM_PROVIDER_URI, checksum_address=ALICE_ADDRESS, signer_uri=f'keystore://{SIGNER_URI}', config_root=os.path.join(TEMP_ALICE_DIR), domain=DOMAIN, known_nodes=known_nodes, start_learning_now=False, federated_only=False, learn_on_same_thread=True, gas_strategy=GAS_STRATEGY) alice_config.initialize(password=INSECURE_PASSWORD) alice_config.keyring.unlock(password=INSECURE_PASSWORD) alice = alice_config.produce(client_password=SIGNER_PASSWORD) alice.start_learning_loop(now=True) return alice
def test_alice_control_starts_with_preexisting_configuration( click_runner, custom_filepath): custom_config_filepath = custom_filepath / AliceConfiguration.generate_filename( ) run_args = ('alice', 'run', '--dry-run', '--lonely', '--config-file', str(custom_config_filepath.absolute())) result = click_runner.invoke(nucypher_cli, run_args, input=FAKE_PASSWORD_CONFIRMED) assert result.exit_code == 0, result.exception
def test_alice_destroy(click_runner, custom_filepath): custom_config_filepath = os.path.join(custom_filepath, AliceConfiguration.generate_filename()) destroy_args = ('alice', 'destroy', '--config-file', custom_config_filepath, '--force') result = click_runner.invoke(nucypher_cli, destroy_args, catch_exceptions=False) assert result.exit_code == 0 assert SUCCESSFUL_DESTRUCTION in result.output assert not os.path.exists(custom_config_filepath), "Alice config file was deleted"
def alice_blockchain_test_config(blockchain_ursulas, three_agents): token_agent, miner_agent, policy_agent = three_agents etherbase, alice_address, bob_address, *everyone_else = token_agent.blockchain.interface.w3.eth.accounts config = AliceConfiguration( temp=True, is_me=True, auto_initialize=True, auto_generate_keys=True, checksum_address=alice_address, passphrase=TEST_URSULA_INSECURE_DEVELOPMENT_PASSWORD, network_middleware=MockRestMiddleware(), known_nodes=blockchain_ursulas, abort_on_learning_error=True, import_seed_registry=False, save_metadata=False, load_metadata=False) yield config config.cleanup()
def test_alice_control_starts_with_preexisting_configuration(click_runner, custom_filepath): custom_config_filepath = os.path.join(custom_filepath, AliceConfiguration.generate_filename()) run_args = ('alice', 'run', '--dry-run', '--config-file', custom_config_filepath) user_input = '{password}\n{password}\n'.format(password=INSECURE_DEVELOPMENT_PASSWORD) result = click_runner.invoke(nucypher_cli, run_args, input=user_input) assert result.exit_code == 0
def config(general_config, config_file, full_config_options): """ View and optionally update existing Alice's configuration. """ emitter = _setup_emitter(general_config) configuration_file_location = config_file or AliceConfiguration.default_filepath() emitter.echo(f"Alice Configuration {configuration_file_location} \n {'='*55}") return get_or_update_configuration(emitter=emitter, config_class=AliceConfiguration, filepath=configuration_file_location, config_options=full_config_options)