def _get_bob_config(click_config, dev, provider_uri, network, registry_filepath, checksum_address, config_file, discovery_port): 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, registry_filepath=registry_filepath, network_middleware=click_config.middleware) except FileNotFoundError: return actions.handle_missing_configuration_file( character_config_class=BobConfiguration, config_file=config_file) return bob_config
def create_config(self, emitter: StdoutEmitter, config_file: str) -> BobConfiguration: if self.dev: return BobConfiguration(emitter=emitter, dev_mode=True, domain=TEMPORARY_DOMAIN, provider_uri=self.provider_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, signer_uri=self.signer_uri, federated_only=True, checksum_address=self.checksum_address, network_middleware=self.middleware, lonely=self.lonely) else: try: return BobConfiguration.from_configuration_file( emitter=emitter, filepath=config_file, domain=self.domain, checksum_address=self.checksum_address, rest_port=self.discovery_port, provider_uri=self.provider_uri, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, max_gas_price=self.max_gas_price, registry_filepath=self.registry_filepath, network_middleware=self.middleware, lonely=self.lonely) except FileNotFoundError: handle_missing_configuration_file( character_config_class=BobConfiguration, config_file=config_file)
def create_config(self, emitter, config_file): if self.dev: return BobConfiguration(emitter=emitter, dev_mode=True, domains={TEMPORARY_DOMAIN}, provider_uri=self.provider_uri, gas_strategy=self.gas_strategy, signer_uri=self.signer_uri, federated_only=True, checksum_address=self.checksum_address, network_middleware=self.middleware) else: try: return BobConfiguration.from_configuration_file( emitter=emitter, filepath=config_file, domains=self.domains, checksum_address=self.checksum_address, rest_port=self.discovery_port, provider_uri=self.provider_uri, signer_uri=self.signer_uri, gas_strategy=self.gas_strategy, registry_filepath=self.registry_filepath, network_middleware=self.middleware) except FileNotFoundError: return actions.handle_missing_configuration_file( character_config_class=BobConfiguration, config_file=config_file)
def _get_bob(self, passphrase) -> object: ''' :param passphrase: Passpharse for new Bob instance :return: None ''' try: bob_config_file = os.path.join(self.TEMP_BOB_DIR, "config_root", "bob.config") bob_config = BobConfiguration.from_configuration_file( filepath=bob_config_file, network_middleware=RestMiddleware(), start_learning_now=False, save_metadata=False, ) bob_config.keyring.unlock(password=passphrase) bob = bob_config.produce() except: shutil.rmtree(self.TEMP_BOB_DIR, ignore_errors=True) os.mkdir(self.TEMP_BOB_DIR) bob_config = BobConfiguration( config_root=os.path.join(self.TEMP_BOB_DIR, "config_root"), is_me=True, known_nodes={self.ursula}, start_learning_now=True, federated_only=True, learn_on_same_thread=True, ) bob_config.initialize(password=passphrase) bob_config.keyring.unlock(password=passphrase) bob = bob_config.produce() bob_config_file = bob_config.to_configuration_file() return bob
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}")
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}")
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}")
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}")
def decrypt_article(article_instance): username = article_instance.author.username DATASOURCE_FILENAME = f"\ {article_instance.author.username}-\ {article_instance.title}-\ datasource-pubkey.msgpack" DATA_SOURCE_DIR = os.path.join( settings.BASE_DIR, 'nucypher_utils', 'nucypher_data', ) with open( os.path.join( DATA_SOURCE_DIR, DATASOURCE_FILENAME ), "rb" ) as file: data = msgpack.load(file) data_source_public_key = data[b'data_source_public_key'] cipher_text = data[b'kits'] POLICY_FILENAME = "policy-metadata.json" POLICY_FILE = os.path.join( settings.BASE_DIR, 'nucypher_utils', 'nucypher_data', POLICY_FILENAME, ) with open(POLICY_FILE, 'r') as f: policy_pubkey_data = json.load(f) policy_pubkey_string = policy_pubkey_data['policy_pubkey'] policy_pubkey_bytes = unhexlify(policy_pubkey_string) policy_pubkey = keys.UmbralPublicKey.from_bytes(policy_pubkey_bytes) enrico_as_understood_by_bob = Enrico.from_public_keys( {SigningPower: data_source_public_key}, policy_encrypting_key=policy_pubkey, ) ALICE_CONFIG_DIR = os.path.join( settings.BASE_DIR, 'nucypher_utils', 'nucypher_data', 'nucypher_char_configs', 'stridon-demo-alice') ALICE_CONFIG_FILE = os.path.join( ALICE_CONFIG_DIR, "alice.config" ) passphrase = "TEST_ALICE_PASSWORD" new_alice_config = AliceConfiguration.from_configuration_file( filepath=ALICE_CONFIG_FILE, network_middleware=RestMiddleware(), start_learning_now=False, save_metadata=False, ) new_alice_config.keyring.unlock(password=passphrase) alice = new_alice_config() alice.start_learning_loop(now=True) alice_pubkey = keys.UmbralPublicKey.from_bytes(bytes(alice.stamp)) BOB_CONFIG_DIR = os.path.join( settings.BASE_DIR, 'nucypher_utils', 'nucypher_data', 'nucypher_char_configs', username) BOB_CONFIG_FILE = os.path.join( BOB_CONFIG_DIR, "bob.config" ) new_premium_user = BobConfiguration.from_configuration_file( filepath=BOB_CONFIG_FILE, network_middleware=RestMiddleware(), start_learning_now=False, save_metadata=False, ) new_premium_user.keyring.unlock(password=passphrase) premium_user = new_premium_user() policy_end_datetime = maya.now() + datetime.timedelta(days=5) label = b'stridon-premium-service' cipher_kit = kits.UmbralMessageKit.from_bytes(cipher_text) print("ALICE") print(alice.public_keys(SigningPower)) print(alice.public_keys(DecryptingPower)) print("PREMIUM_USER") print(premium_user.public_keys(SigningPower)) print(premium_user.public_keys(DecryptingPower)) try: delivered_cleartexts = premium_user.retrieve( message_kit=cipher_kit, data_source=enrico_as_understood_by_bob, alice_verifying_key=alice_pubkey, label=label ) failed = False plain_text_article_content = delivered_cleartexts[0] except KeyError: plain_text_article_content = '' failed = True return (plain_text_article_content, failed)