Exemple #1
0
def Main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    conffiles = ['work_order_tests.toml']
    confpaths = [".", TCFHOME + "/" + "config", "../../etc"]

    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='configuration file', nargs='+')
    parser.add_argument('--config-dir', help='configuration folder', nargs='+')
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        config_json_str = json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get('Logging', {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger('STDOUT'),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger('STDERR'),
                                          logging.WARN)

    ParseCommandLine(config, remainder)
    LocalMain(config)
Exemple #2
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    conf_file = ['listener_config.toml']
    conf_path = [get_config_dir('listener/')]

    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='configuration file', nargs='+')
    parser.add_argument('--config-dir', help='configuration folder', nargs='+')
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_file = options.config

    if options.config_dir:
        conf_path = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_file, conf_path)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get('Logging', {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger('STDOUT'),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger('STDERR'),
                                          logging.WARN)

    host_name, port = parse_command_line(config, remainder)
    start_listener(host_name, port, TCSListener(config))
def submit_lookup_sdk(worker_type, input_json=None):
    logger.info("SDK code path\n")
    if input_json is None:
        jrpc_req_id = 3
    else:
        jrpc_req_id = input_json["id"]
    config = pconfig.parse_configuration_files(constants.conffiles,
                                               constants.confpaths)
    logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])
    worker_dict = {
        'SGX': WorkerType.TEE_SGX,
        'MPC': WorkerType.MPC,
        'ZK': WorkerType.ZK
    }
    worker_registry = _create_worker_registry_instance(globals.blockchain_type,
                                                       config)
    if globals.blockchain_type == "ethereum":
        worker_lookup_response = worker_registry.worker_lookup(
            WorkerType.TEE_SGX, config["WorkerConfig"]["OrganizationId"],
            config["WorkerConfig"]["ApplicationTypeId"], jrpc_req_id)
    else:
        worker_lookup_response = worker_registry.worker_lookup(
            worker_type=worker_dict[worker_type], id=jrpc_req_id)
    logger.info("\n Worker lookup response: {}\n".format(
        json.dumps(worker_lookup_response, indent=4)))

    return worker_lookup_response
Exemple #4
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # Parse out the configuration file first
    conffiles = ['tcs_config.toml']
    confpaths = [".", TCFHOME + "/config"]

    parser = argparse.ArgumentParser()
    parser.add_argument('--config', help='configuration file', nargs='+')
    parser.add_argument('--config-dir', help='configuration folder', nargs='+')
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get('Logging', {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger('STDOUT'),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger('STDERR'),
                                          logging.WARN)

    parse_command_line(config, remainder)
    local_main(config)
Exemple #5
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    conffiles = ["tcs_config.toml"]
    confpaths = [".", TCFHOME + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    parse_command_line(config, remainder)
    logger.info("Starting Enclave manager")
    start_enclave_manager(config)
def submit_work_order_sdk(wo_params, input_json_obj=None):
    logger.info("SDK code path\n")
    if input_json_obj is None:
        req_id = 3
    else:
        req_id = input_json_obj["id"]
    config = pconfig.parse_configuration_files(constants.conffiles,
                                               constants.confpaths)
    logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])

    work_order = _create_work_order_instance(globals.blockchain_type, config)
    logger.info(" work order id %s \n", wo_params.get_work_order_id())
    logger.info(" worker id %s \n", wo_params.get_worker_id())
    logger.info(" Requester ID %s \n", wo_params.get_requester_id())
    logger.info(" To string %s \n", wo_params.to_string())

    logger.info(" worker id %s \n", wo_params.get_worker_id())
    logger.info("Work order submit request : %s, \n \n ",
                wo_params.to_jrpc_string(req_id))
    response = work_order.work_order_submit(wo_params.get_work_order_id(),
                                            wo_params.get_worker_id(),
                                            wo_params.get_requester_id(),
                                            wo_params.to_string(),
                                            id=req_id)

    logger.info('**********Received Response*********\n%s\n', response)
    return response
Exemple #7
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../../")

    conf_files = ["kme_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--bind",
                        help="KME listener url for requests to KME",
                        type=str)
    parser.add_argument("--worker_id",
                        help="Id of worker in plain text",
                        type=str)
    parser.add_argument(
        "--wpe-mrenclave",
        help="MRENCLAVE of WPE that can register with this KME",
        type=str)

    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    if options.bind:
        config["KMEListener"]["bind"] = options.bind
    if options.worker_id:
        config["WorkerConfig"]["worker_id"] = options.worker_id
    if options.wpe_mrenclave:
        config["EnclaveModule"]["wpe_mrenclave"] = options.wpe_mrenclave

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    EnclaveManager.parse_command_line(config, remainder)
    logger.info("Initialize KeyManagement enclave_manager")
    enclave_manager = KeyManagementEnclaveManager(config)
    enclave_manager.init_kv_delegates()
    enclave_manager.setup_enclave()
    logger.info("About to start KeyManagement Enclave manager")
    enclave_manager.start_enclave_manager()
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../../")

    conf_files = ["wpe_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--kme_listener_url",
                        help="KME listener url for requests to KME",
                        type=str)
    parser.add_argument("--worker_id",
                        help="Id of worker in plain text",
                        type=str)

    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    if options.kme_listener_url:
        config["KMEListener"]["kme_listener_url"] = options.kme_listener_url
    if options.worker_id:
        config["WorkerConfig"]["worker_id"] = options.worker_id

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    try:
        EnclaveManager.parse_command_line(config, remainder)
        logger.info("Initialize WorkOrderProcessor enclave_manager")
        enclave_manager = WorkOrderProcessorEnclaveManager(config)
        logger.info("About to start WorkOrderProcessor Enclave manager")
        enclave_manager.start_enclave_manager()
    except Exception as e:
        logger.error("Exception occurred while running WPE, " +
                     "exiting WPE enclave manager")
        exit(1)
Exemple #9
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../")

    conf_files = ["graphene_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--worker_id",
                        help="Id of worker in plain text",
                        type=str)

    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    if options.worker_id:
        config["WorkerConfig"]["worker_id"] = options.worker_id

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    EnclaveManager.parse_command_line(config, remainder)
    try:
        enclave_manager = GrapheneEnclaveManager(config)
        enclave_manager.init_kv_delegates()
        enclave_manager.setup_enclave()
        logger.info("About to start Graphene Enclave manager")
        enclave_manager.start_enclave_manager()
    except Exception as ex:
        logger.error("Error starting Graphene Enclave Manager: " + str(e))
    # Disconnect ZMQ socket.
    if self.zmq_socket:
        self.zmq_socket.disconnect()
Exemple #10
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../../")

    conf_files = ["singleton_enclave_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--worker_id",
                        help="Id of worker in plain text",
                        type=str)
    parser.add_argument("--workloads",
                        help="Comma-separated list of workloads supported",
                        type=str)

    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    if options.workloads:
        config["WorkerConfig"]["workloads"] = options.workloads
    if options.worker_id:
        config["WorkerConfig"]["worker_id"] = options.worker_id

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    EnclaveManager.parse_command_line(config, remainder)
    logger.info("Initialize singleton enclave_manager")
    enclave_manager = SingletonEnclaveManager(config)
    logger.info("About to start Singleton Enclave manager")
    enclave_manager.start_enclave_manager()
def setup_config(args=None):
    """ Fixture to setup initial config for pytest session. """

    # parse out the configuration file first
    conffiles = ["tcs_config.toml"]
    confpaths = [".", TCFHOME + "/config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    parser.add_argument("--connect_uri", action="store",
                        default="http://localhost:1947",
                        help="server uri")
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conffiles = options.config

    if options.config_dir:
        confpaths = options.config_dir

    if options.connect_uri:
        server_uri = options.connect_uri

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        config_json_str = json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger((logging.getLogger("STDOUT"),
                                           logging.DEBUG))
    sys.stderr = plogger.stream_to_logger((logging.getLogger("STDERR"),
                                           logging.WARN))

    logger.info("configuration for the session: %s", config)
    uri_client = HttpJrpcClient(server_uri)

    # private_key of client
    private_key = enclave_helper.generate_signing_keys()

    # Initializing worker object to pass client default worker
    # data to testcases
    worker_obj = worker.SGXWorkerDetails()

    worker_obj, err_cd = worker_lookup_retrieve(config, worker_obj, uri_client)

    # return worker_obj, sig_obj, uri_client, private_key, err_cd
    return worker_obj, uri_client, private_key, err_cd
def _parse_config_file(config_file):
    # Parse config file and return a config dictionary.
    if config_file:
        conf_files = [config_file]
    else:
        conf_files = [TCFHOME + "/sdk/avalon_sdk/tcf_connector.toml"]
    confpaths = ["."]
    try:
        config = pconfig.parse_configuration_files(conf_files, confpaths)
        json.dumps(config)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        config = None

    return config
def submit_getresult_sdk(workorderId, input_json):
    logger.info("SDK code path\n")
    jrpc_req_id = input_json["id"]
    config = pconfig.parse_configuration_files(constants.conffiles,
                                               constants.confpaths)

    logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])

    work_order = _create_work_order_instance(globals.blockchain_type, config)
    logger.info("----- Validating WorkOrderGetResult Response ------")

    get_result_res = work_order.work_order_get_result(workorderId, jrpc_req_id)
    logger.info("******Received Response*****\n%s\n", get_result_res)

    return get_result_res
def submit_register_sdk(dummy, input_json):
    logger.info("SDK code path\n")
    jrpc_req_id = input_json["id"]
    config = pconfig.parse_configuration_files(constants.conffiles,
                                               constants.confpaths)
    logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])
    worker_registry = _create_worker_registry_instance(globals.blockchain_type,
                                                       config)
    worker_register_result = worker_registry.worker_register(
        input_json["params"]["workerId"], input_json["params"]["workerType"],
        input_json["params"]["organizationId"],
        input_json["params"]["applicationTypeId"],
        input_json["params"]["details"])
    logger.info("\n Worker register response: {}\n".format(
        json.dumps(worker_register_result, indent=4)))
    return worker_register_result
def submit_retrieve_receipt_sdk(workorderId, input_json):
    logger.info("SDK code path\n")
    jrpc_req_id = input_json["id"]
    config = pconfig.parse_configuration_files(constants.conffiles,
                                               constants.confpaths)
    logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])
    # Create receipt
    wo_receipt = _create_work_order_receipt_instance(globals.blockchain_type,
                                                     config)

    wo_receipt_resp = wo_receipt.work_order_receipt_retrieve(
        workorderId, jrpc_req_id)

    logger.info("Work order retrieve receipt response : {} \n \n ".format(
        wo_receipt_resp))
    return wo_receipt_resp
def submit_retrieve_sdk(worker_id, input_json=None):
    logger.info("SDK code path\n")
    worker_obj = worker_details.SGXWorkerDetails()
    if input_json is None:
        jrpc_req_id = 11
    else:
        jrpc_req_id = input_json["id"]
    config = pconfig.parse_configuration_files(constants.conffiles,
                                               constants.confpaths)
    logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])
    worker_registry = _create_worker_registry_instance(globals.blockchain_type,
                                                       config)
    if constants.proxy_mode and globals.blockchain_type == 'ethereum':
        for w_id in worker_id:
            worker = worker_registry\
                .worker_retrieve(w_id, jrpc_req_id)
            if worker["result"]["status"] == \
                WorkerStatus.ACTIVE.value:
                worker_retrieve_result = worker
                worker_id = w_id
                break
        logger.info("\n Worker ID\n%s\n", worker_id)
        logger.info("\n Worker retrieve response: {}\n".format(
            json.dumps(worker_retrieve_result, indent=4)))
    else:
        worker_retrieve_result = worker_registry.worker_retrieve(
            worker_id, jrpc_req_id)
        logger.info("\n Worker retrieve response: {}\n".format(
            json.dumps(worker_retrieve_result, indent=4)))

        if "error" in worker_retrieve_result:
            logger.error("Unable to retrieve worker details\n")
            return worker_retrieve_result
    if constants.proxy_mode and globals.blockchain_type == 'fabric':
        worker_obj.load_worker(json.loads(worker_retrieve_result[4]))
    else:
        worker_obj.load_worker(worker_retrieve_result['result']['details'])
    worker_obj.worker_id = worker_id
    logger.info("\n Worker ID\n%s\n", worker_obj.worker_id)
    if input_json is None:
        return worker_obj
    else:
        return worker_retrieve_result
def read_toml_file(input_file, config_name = None, confpaths = [".", TCFHOME + "/" + "config"]):
    """
    Function to read toml file and returns the toml content as a list
    Parameters:
        - input_file is any toml file which need to be read
        - config_name is particular configuration to pull
        - data_dir is the directory structure in which the toml file exists
    """
    conffiles = [input_file]
    config = pconfig.parse_configuration_files(conffiles, confpaths)
    if config_name is None:
        return config
    else :
        result = config.get(config_name)
        if result is None:
            logger.error("%s is missing in toml file %s", config_name, input_file )
            return None
        else :
            return result
Exemple #18
0
def directSubmitWorkOrder():
    input = json.loads(request.data)
    work_order_id = input['workOrder_id']
    worker_id = input['worker_id']
    session_key = utility.generate_key()
    session_iv = utility.generate_iv()

    # This is config file implementaion

    conffiles = ['tcs_config.toml']
    confpaths = ['.', TCFHOME + '/' + 'config']
    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    # host = "tcp://localhost:"

    urlString = config.get('Listener')['zmq_url'] \
        + config.get('Listener')['zmq_port']
    logging.info(urlString)

    # This function fetch a worker from enclave

    worker_obj = fetchWorkerObj(worker_id)

    # This function creates a workOrder Request

    createWorkOrder(input, session_key, session_iv)

    # This function evaluate the workOrder request

    replymessage = evaluateWorkorder(work_order_id, urlString)

    # This functions submits result to the blockchain in case of any violations

    replyResult = storeResultBlockchain(replymessage, worker_obj,
                                        session_key, session_iv, input)
    return replyResult
Exemple #19
0
def setup_config(args=None):
    """ Fixture to setup initial config for pytest session. """

    # parse out the configuration file first
    conffiles = ["tcs_config.toml"]
    confpaths = [".", TCFHOME + "/config"]

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        config_json_str = json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(
        (logging.getLogger("STDOUT"), logging.DEBUG))
    sys.stderr = plogger.stream_to_logger(
        (logging.getLogger("STDERR"), logging.WARN))

    logger.info("configuration for the session: %s", config)
def submit_update_sdk(update_params, input_json=None):
    logger.info("SDK code path\n")
    logger.info("Worker update params %s \n", update_params)
    worker_obj = worker_details.SGXWorkerDetails()
    # update_params = json.loads(update_params)
    if input_json is None:
        jrpc_req_id = 11
    else:
        jrpc_req_id = input_json["id"]
    config = pconfig.parse_configuration_files(constants.conffiles,
                                               constants.confpaths)
    logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])
    worker_registry = _create_worker_registry_instance(globals.blockchain_type,
                                                       config)
    if not constants.proxy_mode:
        worker_update_result = worker_registry.worker_update(
            eval(str(update_params))["worker_id"],
            eval(str(update_params))["details"], jrpc_req_id)
        logger.info("\n Worker update response: {}\n".format(
            json.dumps(worker_update_result, indent=4)))

    return worker_update_result
def submit_create_receipt_sdk(wo_create_receipt, input_json):
    logger.info("SDK code path\n")
    jrpc_req_id = input_json["id"]
    config = pconfig.parse_configuration_files(constants.conffiles,
                                               constants.confpaths)
    logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])
    # Create receipt
    wo_receipt = _create_work_order_receipt_instance(globals.blockchain_type,
                                                     config)
    # Submit work order create receipt jrpc request
    wo_receipt_resp = wo_receipt.work_order_receipt_create(
        wo_create_receipt["workOrderId"], wo_create_receipt["workerServiceId"],
        wo_create_receipt["workerId"], wo_create_receipt["requesterId"],
        wo_create_receipt["receiptCreateStatus"],
        wo_create_receipt["workOrderRequestHash"],
        wo_create_receipt["requesterGeneratedNonce"],
        wo_create_receipt["requesterSignature"],
        wo_create_receipt["signatureRules"],
        wo_create_receipt["receiptVerificationKey"], jrpc_req_id)
    logger.info("Work order create receipt response : {} \n \n ".format(
        wo_receipt_resp))
    return wo_receipt_resp
Exemple #22
0
def main(args=None):
    import config.config as pconfig
    import utility.logger as plogger

    # parse out the configuration file first
    tcf_home = os.environ.get("TCF_HOME", "../../../../")

    conf_files = ["kme_config.toml"]
    conf_paths = [".", tcf_home + "/" + "config"]

    parser = argparse.ArgumentParser()
    parser.add_argument("--config", help="configuration file", nargs="+")
    parser.add_argument("--config-dir", help="configuration folder", nargs="+")
    (options, remainder) = parser.parse_known_args(args)

    if options.config:
        conf_files = options.config

    if options.config_dir:
        conf_paths = options.config_dir

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    plogger.setup_loggers(config.get("Logging", {}))
    sys.stdout = plogger.stream_to_logger(logging.getLogger("STDOUT"),
                                          logging.DEBUG)
    sys.stderr = plogger.stream_to_logger(logging.getLogger("STDERR"),
                                          logging.WARN)

    EnclaveManager.parse_command_line(config, remainder)
    logger.info("Initialize KeyManagement enclave_manager")
    enclave_manager = KeyManagementEnclaveManager(config)
    logger.info("About to start KeyManagement Enclave manager")
    enclave_manager.start_enclave_manager()
def submit_setstatus_sdk(set_status_params, input_json):
    logger.info("SDK code path\n")
    logger.info("Worker status params %s \n", set_status_params)
    if input_json is None:
        jrpc_req_id = 3
    else:
        jrpc_req_id = input_json["id"]
    status_dict = {
        1: WorkerStatus.ACTIVE,
        2: WorkerStatus.OFF_LINE,
        3: WorkerStatus.DECOMMISSIONED,
        4: WorkerStatus.COMPROMISED
    }
    config = pconfig.parse_configuration_files(constants.conffiles,
                                               constants.confpaths)
    logger.info(" URI client %s \n", config["tcf"]["json_rpc_uri"])
    worker_registry = _create_worker_registry_instance(globals.blockchain_type,
                                                       config)
    worker_setstatus_result = worker_registry.worker_set_status(
        eval(str(set_status_params))["worker_id"],
        status_dict[eval(str(set_status_params))["status"]])
    logger.info("\n Worker setstatus response: {}\n".format(
        json.dumps(worker_setstatus_result, indent=4)))
    return worker_setstatus_result
Exemple #24
0
context = zmq.Context()
req_id = 1

logging.info('Running server...')
TCFHOME = os.environ.get('TCF_HOME', '../../')
logging.info(TCFHOME)

app = Flask(__name__)
CORS(app)
logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s',
                    level=logging.INFO)
conf_files = [TCFHOME + '/client_sdk/avalon_client_sdk/tcf_connector.toml']
confpaths = ['.']

try:
    config = pconfig.parse_configuration_files(conf_files, confpaths)
    json.dumps(config)
except pconfig.ConfigurationException as e:
    logger.error(str(e))
    sys.exit(-1)


# Register worker on blockchain

@app.route('/tcf/api/blockchain/worker', methods=['POST'])
def registerWorker():
    input = json.loads(request.data)
    eth_conn = QuorumWorkerRegistryImpl(config)
    worker_id = (input['workerId'])[:8].encode('utf-8')
    logging.info('Worker Id in bytes')
    logging.info(worker_id)
Exemple #25
0
def parse_command_line(args):
    """Setup and parse command line arguments and help information."""

    global worker_obj
    global worker_id
    global verbose
    global config
    global off_chain
    global requester_signature

    parser = argparse.ArgumentParser()
    use_service = parser.add_mutually_exclusive_group()
    parser.add_argument("-c", "--config",
     help="the config file containing the" + \
     " Ethereum contract information", type=str)
    use_service.add_argument("-r",
                             "--registry-list",
                             help="the Ethereum address of the registry list",
                             type=str)
    use_service.add_argument("-s",
                             "--service-uri",
                             help="skip URI lookup and send to specified URI",
                             type=str)
    use_service.add_argument(
        "-o",
        "--off-chain",
        help="skip URI lookup and use the registry in the config file",
        action="store_true")
    parser.add_argument(
        "-w",
        "--worker-id",
        help="skip worker lookup and retrieve specified worker",
        type=str)
    parser.add_argument("-v",
                        "--verbose",
                        help="increase output verbosity",
                        action="store_true")
    parser.add_argument(
        "-rs",
        "--requester_signature",
        help="Enable requester signature for work order requests",
        action="store_true")

    options = parser.parse_args(args)

    if options.config:
        conf_files = [options.config]
    else:
        conf_files = [ TCFHOME + \
         "/examples/common/python/connectors/tcf_connector.toml"
         ]
    conf_paths = ["."]

    try:
        config = pconfig.parse_configuration_files(conf_files, conf_paths)
        json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    global direct_jrpc
    direct_jrpc = DirectJsonRpcApiConnector(conf_files[0])

    # Whether or not to connect to the registry list on the blockchain
    off_chain = False

    if options.registry_list:
        config["ethereum"]["direct_registry_contract_address"] = \
         options.registry_list

    if options.service_uri:
        service_uri = options.service_uri
        off_chain = True

    if options.off_chain:
        service_uri = config["tcf"].get("json_rpc_uri")
        off_chain = True

    requester_signature = options.requester_signature

    verbose = options.verbose
    worker_id = options.worker_id

    # Initializing Worker Object
    worker_obj = worker.SGXWorkerDetails()
Exemple #26
0
def ParseCommandLine(args):
    global worker_obj
    global worker_id
    global message
    global config
    global off_chain
    global requester_signature
    global input_data_hash

    parser = argparse.ArgumentParser()
    use_service = parser.add_mutually_exclusive_group()
    parser.add_argument(
        "-c",
        "--config",
        help="the config file containing the Ethereum contract information",
        type=str)
    use_service.add_argument("-r",
                             "--registry-list",
                             help="the Ethereum address of the registry list",
                             type=str)

    use_service.add_argument("-s",
                             "--service-uri",
                             help="skip URI lookup and send to specified URI",
                             type=str)

    use_service.add_argument(
        "-o",
        "--off-chain",
        help="skip URI lookup and use the registry in the config file",
        action="store_true")

    parser.add_argument(
        "-w",
        "--worker-id",
        help="skip worker lookup and retrieve specified worker",
        type=str)
    parser.add_argument(
        "-m",
        "--message",
        help='text message to be included in the JSON request payload',
        type=str)
    parser.add_argument(
        "-rs",
        "--requester-signature",
        help="Enable requester signature for work order requests",
        action="store_true")
    parser.add_argument("-dh",
                        "--data-hash",
                        help="Enable input data hash for work order requests",
                        action="store_true")

    options = parser.parse_args(args)
    if options.config:
        conf_files = [options.config]
    else:
        conf_files = [TCFHOME + "/sdk/avalon_sdk/tcf_connector.toml"]
    confpaths = ["."]
    try:
        config = pconfig.parse_configuration_files(conf_files, confpaths)
        config_json_str = json.dumps(config)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    global direct_jrpc
    direct_jrpc = AvalonDirectClient(conf_files[0])

    # Whether or not to connect to the registry list on the blockchain
    off_chain = False

    if options.registry_list:
        config["ethereum"]["direct_registry_contract_address"] = \
            options.registry_list

    if options.service_uri:
        config["tcf"]["json_rpc_uri"] = options.service_uri
        off_chain = True

    if options.off_chain:
        off_chain = True

    requester_signature = options.requester_signature
    input_data_hash = options.data_hash
    worker_id = options.worker_id
    message = options.message
    if options.message is None or options.message == "":
        message = "Test Message"

    # Initializing Worker Object
    worker_obj = worker.SGXWorkerDetails()
Exemple #27
0
def ParseCommandLine(args):

    global worker_obj
    global worker_id
    global verbose
    global config
    global off_chain

    parser = argparse.ArgumentParser()
    use_service = parser.add_mutually_exclusive_group()
    parser.add_argument(
        "-c",
        "--config",
        help="the config file containing the Ethereum contract information",
        type=str)
    use_service.add_argument("-r",
                             "--registry-list",
                             help="the Ethereum address of the registry list",
                             type=str)
    use_service.add_argument("-s",
                             "--service-uri",
                             help="skip URI lookup and send to specified URI",
                             type=str)
    use_service.add_argument(
        "-o",
        "--off-chain",
        help="skip URI lookup and use the registry in the config file",
        action="store_true")
    parser.add_argument(
        "-w",
        "--worker-id",
        help="skip worker lookup and retrieve specified worker",
        type=str)
    parser.add_argument("-v",
                        "--verbose",
                        help="increase output verbosity",
                        action="store_true")

    options = parser.parse_args(args)

    if options.config:
        conffiles = [options.config]
    else:
        conffiles = [ TCFHOME + \
         "/examples/common/python/connectors/tcf_connector.toml" ]
    confpaths = ["."]

    try:
        config = pconfig.parse_configuration_files(conffiles, confpaths)
        config_json_str = json.dumps(config, indent=4)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    global direct_wrapper
    direct_wrapper = DirectAdaptorFactoryWrapper(conffiles[0])

    # Whether or not to connect to the registry list on the blockchain
    off_chain = False

    if options.registry_list:
        config["ethereum"]["direct_registry_contract_address"] = \
         options.registry_list

    if options.service_uri:
        service_uri = options.service_uri
        off_chain = True
        uri_client = GenericServiceClient(service_uri)

    if options.off_chain:
        service_uri = config["tcf"].get("json_rpc_uri")
        off_chain = True
        uri_client = GenericServiceClient(service_uri)

    service_uri = options.service_uri
    verbose = options.verbose
    worker_id = options.worker_id

    # Initializing Worker Object
    worker_obj = worker.SGXWorkerDetails()
def ParseCommandLine(args):

        global worker_obj
        global worker_id
        global message
        global config
        global off_chain

        parser = argparse.ArgumentParser()
        use_service = parser.add_mutually_exclusive_group()
        parser.add_argument("-c", "--config",
                            help="the config file containing the Ethereum " + "
                            "contract information",
                            type=str)
        use_service.add_argument("-r", "--registry-list",
                                 help="the Ethereum address of the " +
                                 "registry list",
                                 type=str)
        use_service.add_argument("-s", "--service-uri",
                                 help="skip URI lookup and send to " +
                                 "specified URI",
                                 type=str)
        use_service.add_argument("-o", "--off-chain",
                                 help="skip URI lookup and use the registry " +
                                 "in the config file",
                                 action="store_true")
        parser.add_argument("-w", "--worker-id",
                            help="skip worker lookup and retrieve " +
                            "specified worker",
                            type=str)
        parser.add_argument("-m", "--message",
                            help="text message to be included in the " +
                            "JSON request payload",
                            type=str)

        options = parser.parse_args(args)

        if options.config:
            conffiles = [options.config]
        else:
            conffiles = [TCFHOME + "/examples/common/python/connectors/" +
                         "tcf_connector.toml"]
        confpaths = ["."]
        try:
                config = pconfig.parse_configuration_files(
                    conffiles, confpaths)
                json.dumps(config)
        except pconfig.ConfigurationException as e:
                logger.error(str(e))
                sys.exit(-1)

        global direct_wrapper
        direct_wrapper = DirectAdaptorFactoryWrapper(conffiles[0])

        # Whether or not to connect to the registry list on the blockchain
        off_chain = False

        if options.registry_list:
                config["ethereum"]["direct_registry_contract_address"] = \
                    options.registry_list

        if options.service_uri:
                config["tcf"]["json_rpc_uri"] = options.service_uri
                off_chain = True

        if options.off_chain:
                off_chain = True

        worker_id = options.worker_id
        message = options.message
        if options.message is None or options.message == "":
                message = "Hello world"

        # Initializing Worker Object
        worker_obj = worker.WorkerDetails()
def ParseCommandLine(args):

    global worker_obj
    global worker_id
    global workload_id
    global in_data
    global config
    global mode
    global uri
    global address
    global show_receipt
    global show_decrypted_output
    global requester_signature

    parser = argparse.ArgumentParser()
    mutually_excl_group = parser.add_mutually_exclusive_group()
    parser.add_argument(
        "-c",
        "--config",
        help="The config file containing the Ethereum contract information",
        type=str)
    mutually_excl_group.add_argument(
        "-u",
        "--uri",
        help="Direct API listener endpoint, default is http://localhost:1947",
        default="http://localhost:1947",
        type=str)
    mutually_excl_group.add_argument(
        "-a",
        "--address",
        help="an address (hex string) of the smart contract " +
        "(e.g. Worker registry listing)",
        type=str)
    parser.add_argument("-m",
                        "--mode",
                        help="should be one of listing or registry (default)",
                        default="registry",
                        choices={"registry", "listing"},
                        type=str)
    parser.add_argument(
        "-w",
        "--worker_id",
        help="worker id (hex string) to use to submit a work order",
        type=str)
    parser.add_argument("-l",
                        "--workload_id",
                        help='workload id (hex string) for a given worker',
                        type=str)
    parser.add_argument("-i",
                        "--in_data",
                        help='Input data',
                        nargs="+",
                        type=str)
    parser.add_argument(
        "-r",
        "--receipt",
        help="If present, retrieve and display work order receipt",
        action='store_true')
    parser.add_argument("-o",
                        "--decrypted_output",
                        help="If present, display decrypted output as JSON",
                        action='store_true')
    parser.add_argument(
        "-rs",
        "--requester_signature",
        help="Enable requester signature for work order requests",
        action="store_true")
    options = parser.parse_args(args)

    if options.config:
        conf_files = [options.config]
    else:
        conf_files = [
            TCFHOME + "/examples/common/python/connectors/tcf_connector.toml"
        ]
    confpaths = ["."]
    try:
        config = pconfig.parse_configuration_files(conf_files, confpaths)
        json.dumps(config)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    mode = options.mode

    uri = options.uri
    if uri:
        config["tcf"]["json_rpc_uri"] = uri

    address = options.address
    if address:
        if mode == "listing":
            config["ethereum"]["direct_registry_contract_address"] = \
                address
        elif mode == "registry":
            logger.error(
                "\n Only Worker registry listing address is supported." +
                "Worker registry address is unsupported \n")
            sys.exit(-1)

    worker_id = options.worker_id

    workload_id = options.workload_id
    if not workload_id:
        logger.error("\nWorkload id is mandatory\n")
        sys.exit(-1)

    in_data = options.in_data
    show_receipt = options.receipt
    show_decrypted_output = options.decrypted_output
    requester_signature = options.requester_signature
Exemple #30
0
def ParseCommandLine(args):

    global worker_obj
    global worker_id
    global workload_id
    global in_data
    global config
    global mode
    global uri
    global address

    parser = argparse.ArgumentParser()
    mutually_excl_group = parser.add_mutually_exclusive_group()
    parser.add_argument(
        "-c",
        "--config",
        help="The config file containing the Ethereum contract information",
        type=str)
    mutually_excl_group.add_argument("-u",
                                     "--uri",
                                     help="Direct API listener endpoint",
                                     type=str)
    mutually_excl_group.add_argument(
        "-a",
        "--address",
        help=
        "an address (hex string) of the smart contract (e.g. Worker registry listing)",
        type=str)
    parser.add_argument("-m",
                        "--mode",
                        help="should be one of listing or registry",
                        type=str)
    parser.add_argument(
        "-w",
        "--worker_id",
        help="worker id (hex string) to use to submit a work order",
        type=str)
    parser.add_argument("-l",
                        "--workload_id",
                        help='workload id (hex string) for a given worker',
                        type=str)
    parser.add_argument("-i", "--in_data", help='Input data', type=str)

    options = parser.parse_args(args)

    if options.config:
        conf_files = [options.config]
    else:
        conf_files = [TCFHOME + \
         "/examples/common/python/connectors/tcf_connector.toml"]
    confpaths = ["."]
    try:
        config = pconfig.parse_configuration_files(conf_files, confpaths)
        config_json_str = json.dumps(config)
    except pconfig.ConfigurationException as e:
        logger.error(str(e))
        sys.exit(-1)

    mode = options.mode

    uri = options.uri
    if uri:
        config["tcf"]["json_rpc_uri"] = uri

    address = options.address
    if address:
        if mode == "listing":
            config["ethereum"]["direct_registry_contract_address"] = \
             address
        elif mode == "registry":
            logger.error(
                "\n Only Worker registry listing address is supported." +
                "Worker registry address is unsupported \n")
            sys.exit(-1)
        else:
            logger.error("Mode should be either registry or listing")

    else:
        if not mode:
            logger.error("Address needs to be passed with mode option")

    worker_id = options.worker_id

    workload_id = options.workload_id
    if not workload_id:
        logger.info("\nWorkload id is mandatory\n")
        sys.exit(-1)

    in_data = options.in_data