Beispiel #1
0
def temp_config_root(temp_dir_path):
    """
    User is responsible for closing the file given at the path.
    """
    default_node_config = NodeConfiguration(dev_mode=True,
                                            config_root=temp_dir_path,
                                            import_seed_registry=False)
    yield default_node_config.config_root
    default_node_config.cleanup()
Beispiel #2
0
def temp_config_root(temp_dir_path):
    """
    User is responsible for closing the file given at the path.
    """
    default_node_config = NodeConfiguration(temp=True,
                                            auto_initialize=False,
                                            config_root=temp_dir_path)
    yield default_node_config.config_root
    default_node_config.cleanup()
Beispiel #3
0
def configure(config, action, config_file, config_root, temp, filesystem):
    """Manage the nucypher .ini configuration file"""

    def __destroy(configuration):
        if temp:
            raise NodeConfiguration.ConfigurationError("Cannot destroy a temporary node configuration")
        click.confirm("Permanently destroy all nucypher files, configurations, known nodes, certificates and keys?", abort=True)
        shutil.rmtree(configuration.config_root, ignore_errors=True)
        click.echo("Deleted configuration files at {}".format(node_configuration.config_root))

    def __initialize(configuration):
        if temp:
            click.echo("Using temporary storage area")
        click.confirm("Initialize new nucypher configuration?", abort=True)
        configuration.write_defaults()
        click.echo("Created configuration files at {}".format(node_configuration.config_root))

    if config_root:
        node_configuration = NodeConfiguration(temp=False,
                                               config_root=config_root,
                                               auto_initialize=False)
    elif temp:
        node_configuration = NodeConfiguration(temp=temp, auto_initialize=False)
    elif config_file:
        click.echo("Using configuration file at: {}".format(config_file))
        node_configuration = NodeConfiguration.from_configuration_file(filepath=config_file)
    else:
        node_configuration = NodeConfiguration(auto_initialize=False)  # Fully Default


    #
    # Action switch
    #
    if action == "init":
        __initialize(node_configuration)
    elif action == "destroy":
        __destroy(node_configuration)
    elif action == "reset":
        __destroy(node_configuration)
        __initialize(node_configuration)
    elif action == "validate":
        is_valid = True  # Until there is a reason to believe otherwise
        try:
            if filesystem:   # Check runtime directory
                is_valid = NodeConfiguration.check_config_tree_exists(config_root=node_configuration.config_root)
            if config_file:
                is_valid = validate_configuration_file(filepath=node_configuration.config_file_location)
        except NodeConfiguration.InvalidConfiguration:
            is_valid = False
        finally:
            result = 'Valid' if is_valid else 'Invalid'
            click.echo('{} is {}'.format(node_configuration.config_root, result))
Beispiel #4
0
def validate_configuration_file(
        config=None,
        filepath: str = DEFAULT_CONFIG_FILE_LOCATION,
        raise_on_failure: bool = False) -> Union[bool, Tuple[bool, tuple]]:

    if config is None:
        config = configparser.ConfigParser()
        config.read(filepath)

    if not config.sections():

        raise NodeConfiguration.InvalidConfiguration(
            "Empty configuration file")

    required_sections = ("nucypher", "blockchain")

    missing_sections = list()

    try:
        operating_mode = config["nucypher"]["mode"]
    except KeyError:
        raise NodeConfiguration.ConfigurationError(
            "No operating mode configured")
    else:
        modes = ('federated', 'testing', 'decentralized', 'centralized')
        if operating_mode not in modes:
            missing_sections.append("mode")
            if raise_on_failure is True:
                raise NodeConfiguration.ConfigurationError(
                    "Invalid nucypher operating mode '{}'. Specify {}".format(
                        operating_mode, modes))

    for section in required_sections:
        if section not in config.sections():
            missing_sections.append(section)
            if raise_on_failure is True:
                raise NodeConfiguration.ConfigurationError(
                    "Invalid config file: missing section '{}'".format(
                        section))

    if len(missing_sections) > 0:
        result = False, tuple(missing_sections)
    else:
        result = True, tuple()

    return result
Beispiel #5
0
def _parse_keyfile(keypath: str):
    """Parses a keyfile and returns key metadata as a dict."""

    with open(keypath, 'r') as keyfile:
        try:
            key_metadata = json.loads(keyfile)
        except json.JSONDecodeError:
            raise NodeConfiguration.ConfigurationError("Invalid data in keyfile {}".format(keypath))
        else:
            return key_metadata
Beispiel #6
0
def validate_passphrase(passphrase) -> bool:
    """Validate a passphrase and return True or raise an error with a failure reason"""

    rules = ((len(passphrase) >= 16,
              'Passphrase is too short, must be >= 16 chars.'), )

    for rule, failure_message in rules:
        if not rule:
            raise NodeConfiguration.ConfigurationError(failure_message)
    return True
Beispiel #7
0
    def destroy_configuration(self) -> None:
        if self.dev:
            raise NodeConfiguration.ConfigurationError(
                "Cannot destroy a temporary node configuration")
        click.confirm('''
*Permanently and irreversibly delete all* nucypher files including:
  - Private and Public Keys
  - Known Nodes
  - TLS certificates
  - Node Configurations
Located at {}?'''.format(self.node_configuration.config_root),
                      abort=True)
        shutil.rmtree(self.node_configuration.config_root, ignore_errors=True)
        click.secho("Deleted configuration files at {}".format(
            self.node_configuration.config_root),
                    fg='blue')
Beispiel #8
0
 def connect_to_blockchain(self):
     if self.federated_only:
         raise NodeConfiguration.ConfigurationError(
             "Cannot connect to blockchain in federated mode")
     if self.deployer:
         self.registry_filepath = NodeConfiguration.REGISTRY_SOURCE
     if self.compile:
         click.confirm("Compile solidity source?", abort=True)
     self.blockchain = Blockchain.connect(provider_uri=self.provider_uri,
                                          deployer=self.deployer,
                                          compile=self.compile)
     if self.poa:
         w3 = self.blockchain.interface.w3
         w3.middleware_stack.inject(geth_poa_middleware, layer=0)
     self.accounts = self.blockchain.interface.w3.eth.accounts
     self.log.debug("CLI established connection to provider {}".format(
         self.blockchain.interface.provider_uri))
Beispiel #9
0
 def generate_runtime_filepaths(self, config_root: str) -> dict:
     base_filepaths = NodeConfiguration.generate_runtime_filepaths(config_root=config_root)
     filepaths = dict(db_filepath=os.path.join(config_root, self.db_name),
                      )
     base_filepaths.update(filepaths)
     return base_filepaths
Beispiel #10
0
 def __destroy(configuration):
     if temp:
         raise NodeConfiguration.ConfigurationError("Cannot destroy a temporary node configuration")
     click.confirm("Permanently destroy all nucypher files, configurations, known nodes, certificates and keys?", abort=True)
     shutil.rmtree(configuration.config_root, ignore_errors=True)
     click.echo("Deleted configuration files at {}".format(node_configuration.config_root))