class WorkOrderJRPCImpl(WorkOrderInterface):
    def __init__(self, config):
        self.__uri_client = GenericServiceClient(config["tcf"]["json_rpc_uri"])

    def work_order_submit(self, params, in_data, out_data=None, id=None):
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderSubmit",
            "id": id
        }
        json_rpc_request["params"] = params
        json_rpc_request["params"]["inData"] = in_data

        if out_data is not None:
            json_rpc_request["params"]["outData"] = out_data

        logging.debug("Work order request %s", json.dumps(json_rpc_request))
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_get_result_nonblocking(self, work_order_id, id=None):
        """
        Get the work order result in non-blocking way.
        It return json rpc response of dictionary type
        """
        if not is_valid_hex_str(work_order_id):
            logging.error("Invalid work order Id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid work order Id")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderGetResult",
            "id": id,
            "params": {
                "workOrderId": work_order_id
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_get_result(self, work_order_id, id=None):
        """
        Get the work order result in blocking way until it get the result/error
        It return json rpc response of dictionary type
        """
        response = self.work_order_get_result_nonblocking(work_order_id, id)
        if "error" in response:
            if response["error"]["code"] != WorkOrderStatus.PENDING:
                return response
            else:
                while "error" in response and \
                    response["error"]["code"] == WorkOrderStatus.PENDING:
                    response = self.work_order_get_result_nonblocking(
                        work_order_id, id)
                    # TODO: currently pooling after every 2 sec interval forever.
                    # We should implement feature to timeout after responseTimeoutMsecs in the request
                    time.sleep(2)
                return response
class WorkOrderReceiptJRPCImpl(WorkOrderReceiptInterface):
    """
    WorkOrderReceiptJRPCImpl is an implementation of WorkOrderReceiptInterface
    """
    def __init__(self, config):
        self.__uri_client = GenericServiceClient(config["tcf"]["json_rpc_uri"])


    def work_order_receipt_create(self, work_order_id, worker_id,  
        worker_service_id,
        requester_id,
        receipt_create_status,
        work_order_request_hash, id=None):
        """
        Creating a Work Order Receipt json rpc request and submit tcs listener
        """
        if work_order_id is None or not is_hex(work_order_id):
            logging.error("Work order id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        if worker_id is None or not is_hex(worker_id):
            logging.error("Worker id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        if not isinstance(worker_type, ReceiptCreateStatus):
            logging.error("Invalid receipt create status")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Invalid receipt create status")

        if worker_service_id is None or not is_hex(worker_service_id):
            logging.error("Worker service id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker service id is empty or Invalid")

        if requester_id is None or not is_hex(requester_id):
            logging.error("requester id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "requester id is empty or Invalid")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptCreate",
            "id": id,
            "params": {
                "workOrderId": work_order_id,
                "workerId": worker_id,
                "workerServiceId": worker_service_id,
                "requesterId": requester_id,
                "receiptCreateStatus": receipt_create_status,
                "workOrderRequestHash": work_order_request_hash
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_receipt_update(self, work_order_id,
        updater_id,
        update_type,
        update_data,
        update_signature,
        signature_rules, id=None):
        """
        Update a Work Order Receipt json rpc request and submit tcs listener
        """
        if work_order_id is None or not is_hex(work_order_id):
            logging.error("Work order id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        if updater_id is None or not is_hex(updater_id):
            logging.error("Updater id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        if not isinstance(update_type, ReceiptCreateStatus):
            logging.error("Invalid Update type")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Invalid update type")

        if update_data is None or not is_hex(update_data):
            logging.error("Update data is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Update data is empty or Invalid")

        if update_signature is None or not is_hex(update_signature):
            logging.error("update signature is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "update signature is empty or Invalid")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptUpdate",
            "id": id,
            "params": {
                "workOrderId": work_order_id,
                "updaterId": updater_id,
                "updateType": update_type,
                "updateData": update_data,
                "updateSignature": update_signature,
                "signatureRules": signature_rules
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    
    def work_order_receipt_retrieve(self, work_order_id, id=None):
        """
        Retrieve a Work Order Receipt json rpc request and submit tcs listener
        """
        if work_order_id is None or not is_hex(work_order_id):
            logging.error("Work order id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptRetrieve",
            "id": id,
            "params": {
                "workOrderId": work_order_id
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response


    def work_order_receipt_update_retrieve(self, work_order_id,
        updater_id,
        update_index, id=None):
        """
        Retrieving a Work Order Receipt Update
        """
        if work_order_id is None or not is_hex(work_order_id):
            logging.error("Work order id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        if updater_id is None or not is_hex(updater_id):
            logging.error("Updater id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptUpdateRetrieve",
            "id": id,
            "params": {
                "workOrderId": work_order_id,
                "updaterId": updater_id,
                "updateIndex": update_index
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_receipt_lookup(self, worker_service_id,
        worker_id,
        requester_id,
        receipt_status, id=None):
        """
        Work Order Receipt Lookup
        """
        if worker_id is None or not is_hex(worker_id):
            logging.error("Worker id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        if worker_service_id is None or not is_hex(worker_service_id):
            logging.error("Worker service id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker service id is empty or Invalid")

        if requester_id is None or not is_hex(requester_id):
            logging.error("requester id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "requester id is empty or Invalid")

        if not isinstance(receipt_status, ReceiptCreateStatus):
            logging.error("Invalid receipt status")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Invalid receipt status")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptLookUp",
            "id": id,
            "params": {
                "workerServiceId": worker_service_id,
                "workerId": worker_id,
                "requesterId": requester_id,
                "updateIndex": receipt_status
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_receipt_lookup_next(self, worker_service_id,
        worker_id,
        requester_id,
        receipt_status,
        last_lookup_tag, id=None):
        """
        Work Order Receipt Lookup Next
        """
        if worker_id is None or not is_hex(worker_id):
            logging.error("Worker id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        if worker_service_id is None or not is_hex(worker_service_id):
            logging.error("Worker service id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker service id is empty or Invalid")

        if requester_id is None or not is_hex(requester_id):
            logging.error("requester id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "requester id is empty or Invalid")

        if not isinstance(receipt_status, ReceiptCreateStatus):
            logging.error("Invalid receipt status")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Invalid receipt status")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptLookUpNext",
            "id": id,
            "params": {
                "workerServiceId": worker_service_id,
                "workerId": worker_id,
                "requesterId": requester_id,
                "updateIndex": receipt_status,
                "lastLookUpTag": last_lookup_tag
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response
class WorkOrderJRPCImpl(WorkOrderInterface):
    def __init__(self, config):
        self.__uri_client = GenericServiceClient(config["tcf"]["json_rpc_uri"])
        """
        key value pair with field name and boolean indicator that tells 
        whether field is mandatory or not. True is mandatory and False is optional
        """
        self.__param_key_map = {
            "responseTimeoutMSecs": True,
            "payloadFormat": False,
            "resultUri": False,
            "notifyUri": False,
            "workOrderId": True,
            "workerId": True,
            "workloadId": True,
            "requesterId": True,
            "workerEncryptionKey": False,
            "dataEncryptionAlgorithm": False,
            "encryptedSessionKey": True,
            "sessionKeyIv": False,
            "requesterNonce": True,
            "encryptedRequestHash": True,
            "requesterSignature": False,
            "verifyingKey": True
        }
        self.__data_key_map = {
            "index": True,
            "dataHash": False,
            "data": True,
            "encryptedDataEncryptionKey": True,
            "iv": True
        }

    def __validate_parameters(self, params, in_data, out_data):
        """Validate parameter dictionary for existence of fields and mandatory fields """
        key_list = []
        for key in params.keys():
            if not key in self.__param_key_map.keys():
                logging.error("Invalid parameter %s", key)
                return "Invalid parameter {}".format(key)
            else:
                key_list.append(key)
        for k, v in self.__param_key_map.items():
            if v == True and not k in key_list:
                logging.error("Missing parameter %s", k)
                return "Missing parameter {}".format(k)
        """Validate in_data and out_data dictionary for existence of fields
        and mandatory fields """

        for data in in_data:
            in_data_keys = []
            for key in data.keys():
                if not key in self.__data_key_map.keys():
                    logging.error("Invalid in data parameter %s", key)
                    return "Invalid in data parameter {}".format(key)
                else:
                    in_data_keys.append(key)
            for k, v in self.__data_key_map.items():
                if v == True and not k in in_data_keys:
                    logging.error("Missing in data parameter %s", k)
                    return "Missing in data parameter {}".format(k)

        for data in out_data:
            out_data_keys = []
            for key in data.keys():
                if not key in self.__data_key_map.keys():
                    logging.error("Invalid out data parameter %s", key)
                    return "Invalid out data parameter {}".format(key)
                else:
                    out_data_keys.append(key)
            for k, v in self.__data_key_map.items():
                if v == True and not k in out_data_keys:
                    logging.error("Missing out data parameter %s", k)
                    return "Missing out data parameter {}".format(k)

        return None

    def work_order_submit(self, params, in_data, out_data, id=None):
        is_valid = self.__validate_parameters(params, in_data, out_data)
        if is_valid is not None:
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        is_valid)
        if not is_hex(params["workOrderId"]):
            logging.error("Invalid work order id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid work order id")
        if not is_hex(params["workloadId"]):
            logging.error("Invalid work load id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid work load id")
        if not is_hex(params["requesterId"]):
            logging.error("Invalid requester id id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid requester id id")
        if not is_hex(params["workerEncryptionKey"]):
            logging.error("Invalid worker encryption key")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid worker encryption key")
        for data in in_data:
            if not is_hex(data["dataHash"]):
                logging.error("Invalid data hash of in data")
                return create_jrpc_response(id,
                                            JsonRpcErrorCode.INVALID_PARAMETER,
                                            "Invalid data hash of in data")
            if not is_hex(data["encryptedDataEncryptionKey"]):
                logging.error("Invalid Encryption key of in data")
                return create_jrpc_response(
                    id, JsonRpcErrorCode.INVALID_PARAMETER,
                    "Invalid Encryption key of in data")
            if not is_hex(data["iv"]):
                logging.error("Invalid initialization vector of in data")
                return create_jrpc_response(
                    id, JsonRpcErrorCode.INVALID_PARAMETER,
                    "Invalid initialization vector of in data")
            try:
                base64.b64decode(data["data"])
            except Exception as e:
                logging.error("Invalid base64 format of in data")
                return create_jrpc_response(
                    id, JsonRpcErrorCode.INVALID_PARAMETER,
                    "Invalid base64 format of in data")

        for data in out_data:
            if not is_hex(data["dataHash"]):
                logging.error("Invalid data hash of out data")
                return create_jrpc_response(id,
                                            JsonRpcErrorCode.INVALID_PARAMETER,
                                            "Invalid data hash of out data")
            if not is_hex(data["encryptedDataEncryptionKey"]):
                logging.error("Invalid Encryption key of out data")
                return create_jrpc_response(
                    id, JsonRpcErrorCode.INVALID_PARAMETER,
                    "Invalid Encryption key of out data")
            if not is_hex(data["iv"]):
                logging.error("Invalid initialization vector of out data")
                return create_jrpc_response(
                    id, JsonRpcErrorCode.INVALID_PARAMETER,
                    "Invalid initialization vector of out data")
            try:
                base64.b64decode(data["data"])
            except Exception as e:
                logging.error("Invalid base64 format of out data")
                return create_jrpc_response(
                    id, JsonRpcErrorCode.INVALID_PARAMETER,
                    "Invalid base64 format of out data")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderSubmit",
            "id": id,
            "params": {
                "responseTimeoutMSecs": params["responseTimeoutMSecs"],
                "payloadFormat": params["payloadFormat"],
                "resultUri": params["resultUri"],
                "notifyUri": params["notifyUri"],
                "workOrderId": params["workOrderId"],
                "workerId": params["workerId"],
                "workloadId": params["workloadId"],
                "requesterId": params["requesterId"],
                "workerEncryptionKey": params["workerEncryptionKey"],
                "dataEncryptionAlgorithm": params["dataEncryptionAlgorithm"],
                "encryptedSessionKey": params["encryptedSessionKey"],
                "sessionKeyIv": params["sessionKeyIv"],
                "requesterNonce": params["requesterNonce"],
                "encryptedRequestHash": params["encryptedRequestHash"],
                "requesterSignature": params["requesterSignature"],
                "inData": in_data,
                "outData": out_data
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_get_result(self, work_order_id, id=None):
        if not is_hex(work_order_id):
            logging.error("Invalid workOrder Id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid workOrder Id")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderGetResult",
            "id": id,
            "params": {
                "workOrderId": work_order_id
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response
class WorkerRegistryJRPCImpl(WorkerRegistryInterface):
    def __init__(self, config):
        self.__uri_client = GenericServiceClient(config["tcf"]["json_rpc_uri"])

    def worker_register(self, worker_id, worker_type, org_id, application_type_ids,
        details, id=None):
        """ Adds worker details to registry """
        if worker_id is None or not is_hex(worker_id):
            logging.error("Worker id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")
        if not isinstance(worker_type, WorkerType):
            logging.error("Invalid worker type")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Invalid worker type")
        if org_id is not None and not is_hex(org_id):
            logging.error("Invalid organization id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Invalid organization id")
        if application_type_ids is not None:
            for appId in application_type_ids:
                if not is_hex(appId):
                    logging.error("Invalid application type id")
                    return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                        "Invalid application type id")
                    break
        if details is not None:
            is_valid = validate_details(details)
            if is_valid is not None:
                logging.error(is_valid)
                return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                    is_valid)
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerRegister",
            "id": id,
            "params": {
                "workerId": worker_id,
                "workerType": worker_type.value,
                "organizationId": org_id,
                "applicationTypeId": application_type_ids,
                "details": details
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response
    
    def worker_update(self, worker_id, details, id=None):
        """ Update worker with new information """
        if worker_id is None or not is_hex(worker_id):
            logging.error("Worker id is empty or invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerUpdate",
            "id": id,
            "params": {
                "workerId": worker_id,
                "details": details
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response


    def worker_set_status(self, worker_id, status, id=None):
        """ Set the worker status to active, offline, decommissioned 
        or compromised state 
        """
        if worker_id is None or not is_hex(worker_id):
            logging.error("Worker id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerSetStatus",
            "id": id,
            "params": {
                "workerId": worker_id,
                "status": status.value
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response
    

    def worker_retrieve(self, worker_id, id=None):
        """ Retrieve the worker identified by worker id """
        if worker_id is None or not is_hex(worker_id):
            logging.error("Worker id is empty or Invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker id is empty or Invalid")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerRetrieve",
            "id": id,
            "params": {
                "workerId": worker_id
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    
    def worker_lookup(self, worker_type, organization_id, application_type_id,
        id=None):
        """ Worker lookup based on worker type, organization id and application id"""
        if not isinstance(worker_type, WorkerType):
            logging.error("Worker type is invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker type is invalid")
        if organization_id is None or not is_hex(organization_id):
            logging.error("Invalid Organization id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Invalid Organization id")
        if application_type_id is not None:
            for appId in application_type_id:
                if not is_hex(appId):
                    logging.error("Invalid application type id")
                    return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                        "Invalid application type id")
                    break
        

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerLookUp",
            "id": id,
            "params": {
                "workerType": worker_type.value,
                "organizationId": organization_id,
                "applicationTypeId": application_type_id
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    
    def worker_lookup_next(self, worker_type, organization_id, 
        application_type_id, lookup_tag, id=None):
        """ Similar to workerLookUp with additional parameter lookup_tag """
        if not isinstance(worker_type, WorkerType):
            logging.error("Worker type is invalid")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Worker type is invalid")
        if organization_id is None or not is_hex(organization_id):
            logging.error("Invalid organization id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                "Invalid organization id")
        if application_type_id is not None:
            for appId in application_type_id:
                if not is_hex(appId):
                    logging.error("Invalid application id")
                    return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                        "Invalid application id")
                    break
        

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerLookUpNext",
            "id": id,
            "params": {
                "workerType": worker_type.value,
                "organizationId": organization_id,
                "applicationTypeId": application_type_id,
                "lookUpTag": lookup_tag
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response
def LocalMain(config):

    if not input_json_str and not input_json_dir:
        logger.error("JSON input file is not provided")
        exit(1)

    if not output_json_file_name:
        logger.error("JSON output file is not provided")
        exit(1)

    if not server_uri:
        logger.error("Server URI is not provided")
        exit(1)

    logger.info("Execute work order")
    uri_client = GenericServiceClient(server_uri)
    response = None
    wo_id = None
    if input_json_dir:
        directory = os.fsencode(input_json_dir)
        files = os.listdir(directory)

        for file in sorted(files):
            logger.info("---------------Input file name: %s ---------------\n",
                        file.decode("utf-8"))
            input_json_str1 = futils.read_json_file(
                (directory.decode("utf-8") + file.decode("utf-8")))
            # -----------------------------------------------------------------

            # If Client request is WorkOrderSubmit, a requester payload's
            # signature with the requester private signing key is generated.
            if "WorkOrderSubmit" in input_json_str1:
                # Update workOrderId , workerId and workloadId
                input_json_obj = json.loads(input_json_str1)
                wo_id = hex(random.randint(1, 2**64 - 1))
                input_json_obj["params"]["workOrderId"] = wo_id
                input_json_obj["params"]["workerId"] = worker_obj.worker_id
                # Convert workloadId to a hex string and update the request
                workload_id = input_json_obj["params"]["workloadId"]
                workload_id_hex = workload_id.encode("UTF-8").hex()
                input_json_obj["params"]["workloadId"] = workload_id_hex
                input_json_str1 = json.dumps(input_json_obj)

                # Generate session iv an encrypted session key
                session_iv = enclave_helper.generate_iv()
                session_key = enclave_helper.generate_key()
                encrypted_session_key = enclave_helper.generate_encrypted_key(
                    session_key, worker_obj.encryption_key)

                input_json_str1, status = sig_obj.generate_client_signature(
                    input_json_str1, worker_obj, private_key, session_key,
                    session_iv, encrypted_session_key)
                if status != SignatureStatus.PASSED:
                    logger.info("Generate signature failed\n")
                    exit(1)
                if input_json_str1 is None:
                    continue
            # -----------------------------------------------------------------

            # Update the worker ID
            if response:
                if "workerId" in input_json_str1:
                    # Retrieve the worker id from the "WorkerRetrieve"
                    # response and update the worker id information for
                    # further json requests.
                    if "result" in response and "ids" in response[
                            "result"].keys():
                        input_json_final = json.loads(input_json_str1)
                        worker_id = response["result"]["ids"][0]
                        input_json_final["params"]["workerId"] = worker_id
                        input_json_str1 = json.dumps(input_json_final)
                        logger.info(
                            "**********Worker details Updated with "
                            "Worker ID*********\n%s\n", input_json_str1)
            # -----------------------------------------------------------------
            if "WorkOrderGetResult" in input_json_str1 or "WorkOrderReceiptRetrieve":
                input_json_obj = json.loads(input_json_str1)
                input_json_obj["params"]["workOrderId"] = wo_id
                input_json_str1 = json.dumps(input_json_obj)

            logger.info("*********Request Json********* \n%s\n",
                        input_json_str1)
            response = uri_client._postmsg(input_json_str1)
            logger.info("**********Received Response*********\n%s\n", response)

            # -----------------------------------------------------------------

            # Worker details are loaded into Worker_Obj
            if "WorkerRetrieve" in input_json_str1 and "result" in response:
                worker_obj.load_worker(response)
            # -----------------------------------------------------------------

            # Polling for the "WorkOrderGetResult" and break when you get the result
            while ("WorkOrderGetResult" in input_json_str1
                   and "result" not in response):
                if response["error"]["code"] != WorkOrderStatus.PENDING:
                    break
                response = uri_client._postmsg(input_json_str1)
                logger.info("Received Response : %s, \n \n ", response)
                time.sleep(3)
            # -----------------------------------------------------------------

            # Verify the signature
            if ("WorkOrderGetResult" in input_json_str1):
                if "error" in response:
                    # Response has error, hence skip Signature verification
                    logger.info("Work order response has error, "
                                "skipping signature verification")
                    continue
                sig_bool = sig_obj.verify_signature(
                    response, worker_obj.verification_key)
                try:
                    if sig_bool > 0:
                        logger.info("Signature Verified")
                        enclave_helper.decrypted_response(
                            response, session_key, session_iv)
                    else:
                        logger.info("Signature verification Failed")
                        exit(1)
                except:
                    logger.error(
                        "ERROR: Failed to analyze Signature Verification")
                    exit(1)

            # -----------------------------------------------------------------
    else:
        logger.info("Input Request %s", input_json_str)
        response = uri_client._postmsg(input_json_str)
        logger.info("Received Response : %s , \n \n ", response)

    exit(0)
class WorkOrderEncryptionKeyJrpcImpl(WorkOrderEncryptionKeyInterface):
    def __init__(self, config):
        self.__uri_client = GenericServiceClient(config["tcf"]["json_rpc_uri"])

    def encryption_key_get(self,
                           worker_id,
                           last_used_key_nonce,
                           tag,
                           requester_id,
                           signature_nonce,
                           signature,
                           id=None):
        if not is_valid_hex_str(worker_id):
            logging.error("Invalid Worker id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid Worker id")
        if last_used_key_nonce is not None and not is_valid_hex_str(
                last_used_key_nonce):
            logging.error("Invalid last used key nonce")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid last used key nonce")
        if tag is not None and not is_valid_hex_str(tag):
            logging.error("Invalid tag")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid tag")
        if requester_id is not None and not is_valid_hex_str(requester_id):
            logging.error("Invalid requester id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid requester id")
        if signature_nonce is not None and not is_valid_hex_str(
                signature_nonce):
            logging.error("Invalid signature nonce")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid signature nonce")
        if signature is not None:
            try:
                base64.b64decode(signature)
            except Exception as e:
                logging.error("Invalid signature")
                return create_jrpc_response(id,
                                            JsonRpcErrorCode.INVALID_PARAMETER,
                                            "Invalid signature")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "EncryptionKeyGet",
            "id": id,
            "params": {
                "workerId": worker_id,
                "lastUsedKeyNonce": last_used_key_nonce,
                "tag": tag,
                "requesterId": requester_id,
                "signatureNonce": signature_nonce,
                "signature": signature
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def encryption_key_set(self,
                           worker_id,
                           encryption_key,
                           encryption_key_nonce,
                           tag,
                           signature_nonce,
                           signature,
                           id=None):
        if not is_valid_hex_str(worker_id):
            logging.error("Invalid Worker id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid Worker id")
        if not is_valid_hex_str(encryption_key):
            logging.error("Invalid encryption key")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid encryption key")
        if encryption_key_nonce is not None and not is_valid_hex_str(
                encryption_key_nonce):
            logging.error("Invalid encryption nonce")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid encryption nonce")
        if tag is not None and not is_valid_hex_str(tag):
            logging.error("Invalid tag")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid tag")
        if signature_nonce is not None and not is_valid_hex_str(
                signature_nonce):
            logging.error("Invalid signature nonce")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid signature nonce")
        if signature is not None:
            try:
                base64.b64decode(signature)
            except Exception as e:
                logging.error("Invalid signature")
                return create_jrpc_response(id,
                                            JsonRpcErrorCode.INVALID_PARAMETER,
                                            "Invalid signature")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "EncryptionKeySet",
            "id": id,
            "params": {
                "workerId": worker_id,
                "encryptionKey": encryption_key,
                "encryptionKeyNonce": encryption_key_nonce,
                "tag": tag,
                "signatureNonce": signature_nonce,
                "signature": signature
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response
Beispiel #7
0
class WorkOrderJRPCImpl(WorkOrderInterface):
    def __init__(self, config):
        self.__uri_client = GenericServiceClient(config["tcf"]["json_rpc_uri"])
        """
        key value pair with field name and boolean indicator that tells 
        whether field is mandatory or not. True is mandatory and False is optional
        """
        self.__param_key_map = {
            "responseTimeoutMSecs": True,
            "payloadFormat": False,
            "resultUri": False,
            "notifyUri": False,
            "workOrderId": True,
            "workerId": True,
            "workloadId": True,
            "requesterId": True,
            "workerEncryptionKey": False,
            "dataEncryptionAlgorithm": False,
            "encryptedSessionKey": True,
            "sessionKeyIv": False,
            "requesterNonce": True,
            "encryptedRequestHash": True,
            "requesterSignature": False,
            "verifyingKey": False
        }
        self.__data_key_map = {
            "index": True,
            "dataHash": False,
            "data": True,
            "encryptedDataEncryptionKey": False,
            "iv": False
        }

    def __validate_parameters(self, params):
        """
        Validate parameter dictionary for existence of 
        fields and mandatory fields 
        Returns False and string with error message on failure and 
        True and empty string on success
        """
        key_list = []
        for key in params.keys():
            if not key in self.__param_key_map.keys():
                logging.error("Invalid parameter %s", key)
                return False, "Invalid parameter {}".format(key)
            else:
                key_list.append(key)
        for k, v in self.__param_key_map.items():
            if v == True and not k in key_list:
                logging.error("Missing parameter %s", k)
                return False, "Missing parameter {}".format(k)

        if not is_hex(params["workOrderId"]):
            logging.error("Invalid work order id")
            return False, "Invalid work order id"
        if not is_hex(params["workloadId"]):
            logging.error("Invalid work load id")
            return False, "Invalid work load id"
        if not is_hex(params["requesterId"]):
            logging.error("Invalid requester id id")
            return False, "Invalid requester id id"
        if not is_hex(params["workerEncryptionKey"]):
            logging.error("Invalid worker encryption key")
            return False, "Invalid worker encryption key"

        return True, ""

    def __validate_data_format(self, data):
        """
        Validate data format of the params data field (in data or out data)
        Returns False and string with error message on failure and 
        True and empty string on success
        """
        for data_item in data:
            in_data_keys = []
            for key in data_item.keys():
                if not key in self.__data_key_map.keys():
                    logging.error("Invalid in data parameter %s", key)
                    return False, "Invalid in data parameter {}".format(key)
                else:
                    in_data_keys.append(key)
            for k, v in self.__data_key_map.items():
                if v == True and not k in in_data_keys:
                    logging.error("Missing in data parameter %s", k)
                    return False, "Missing in data parameter {}".format(k)

            if "dataHash" in data_item:
                data_hash = data_item["dataHash"]
                if not is_hex(data_hash) and data_hash != "":
                    logging.error("Invalid data hash of in data")
                    return False, "Invalid data hash of in data"
            if "encryptedDataEncryptionKey" in data_item:
                enc_key = data_item["encryptedDataEncryptionKey"]
                if enc_key != "-" and \
                    enc_key != "" and \
                    enc_key != "null" and \
                    not is_hex(enc_key):
                    logging.error("Invalid Encryption key of in data")
                    return False, \
                        "Invalid Encryption key of in data"
            if "iv" in data_item and data_item["iv"] != "" and \
                data_item["iv"] != "0" and not is_hex(data_item["iv"]):
                logging.error("Invalid initialization vector of in data")
                return False, \
                    "Invalid initialization vector of in data"
            try:
                base64.b64decode(data_item["data"])
            except Exception as e:
                logging.error("Invalid base64 format of in data")
                return False, \
                    "Invalid base64 format of in data"

        return True, ""

    def work_order_submit(self, params, in_data, out_data=None, id=None):
        valid, err = self.__validate_parameters(params)
        if not valid:
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        err)

        valid, err = self.__validate_data_format(in_data)
        if not valid:
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        err)

        if out_data is not None:
            valid, err = self.__validate_data_format(out_data)
            if not valid:
                return create_jrpc_response(id,
                                            JsonRpcErrorCode.INVALID_PARAMETER,
                                            err)

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderSubmit",
            "id": id
        }
        json_rpc_request["params"] = params
        json_rpc_request["params"]["inData"] = in_data

        if out_data is not None:
            json_rpc_request["outData"] = out_data

        logging.debug("Work order request %s", json.dumps(json_rpc_request))
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_get_result_nonblocking(self, work_order_id, id=None):
        """
        Get the work order result in non-blocking way.
        It return json rpc response of dictionary type
        """
        if not is_hex(work_order_id):
            logging.error("Invalid work order Id")
            return create_jrpc_response(id, JsonRpcErrorCode.INVALID_PARAMETER,
                                        "Invalid work order Id")

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderGetResult",
            "id": id,
            "params": {
                "workOrderId": work_order_id
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_get_result(self, work_order_id, id=None):
        """
        Get the work order result in blocking way until it get the result/error
        It return json rpc response of dictionary type
        """
        response = self.work_order_get_result_nonblocking(work_order_id, id)
        if "error" in response:
            if response["error"]["code"] != WorkOrderStatus.PENDING:
                return response
            else:
                while "error" in response and \
                    response["error"]["code"] == WorkOrderStatus.PENDING:
                    response = self.work_order_get_result_nonblocking(
                        work_order_id, id)
                    # TODO: currently pooling after every 2 sec interval forever.
                    # We should implement feature to timeout after responseTimeoutMsecs in the request
                    time.sleep(2)
                return response
def LocalMain(config) :

    if config.get('KvStorage') is None:
        logger.error("Kv Storage path is missing")
        sys.exit(-1)

    KvHelper = KvStorage()
    KvHelper.open((TCFHOME + '/' + config['KvStorage']['StoragePath']))
    
    if not input_json_str and not input_json_dir:
       logger.error("JSON input file is not provided")
       exit(1)
    
    if not output_json_file_name:
        logger.error("JSON output file is not provided")
        exit(1)
    
    if not server_uri:
        logger.error("Server URI is not provided")
        exit(1)
        
    logger.info('execute work order')
    uri_client = GenericServiceClient(server_uri) 
    
    if input_json_dir:
        directory = os.fsencode(input_json_dir)
        files = os.listdir(directory)
            
        for file in sorted(files) :
            logger.info("------------------Input file name: %s ---------------\n",file.decode("utf-8"))
            input_json_str1 = enclave_helper.read_json_file((directory.decode("utf-8") + file.decode("utf-8")))
            logger.info("*********Request Json********* \n%s\n", input_json_str1)
            response = uri_client._postmsg(input_json_str1)
            logger.info("**********Received Response*********\n%s\n", response)
            
    else :
        j=json.loads(input_json_str)
        
        if(j['method'] == "WorkOrderGetResult"):
            response = {}
            response['id'] =  j['params']['workOrderId']
            response["outData"] = "Processed response"
            KvHelper.set("wo-responses", str(j['params']['workOrderId']), json.dumps(response))
            input_str = json.dumps(j)
            logger.info('input str %s', input_str)
            response = uri_client._postmsg(input_str)
            logger.info("Received Response : %s , \n \n ", response)
            
            j['params']['workOrderId'] = "101"
            input_str = json.dumps(j)
            logger.info('input str %s', input_str)
            response = uri_client._postmsg(input_str)
            logger.info("Received Response : %s , \n \n ", response)
            
            j['params']['workOrderId'] = "121"
            input_str = json.dumps(j)
            logger.info('input str %s', input_str)
            response = uri_client._postmsg(input_str)
            logger.info("Received Response : %s , \n \n ", response)
            
        else:
            id = 100
            logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
            logger.info("Test adding new time stamps entries")
            for x in range(5):
                j['params']['workOrderId'] = id + x
                input_str = json.dumps(j)
                logger.info('input str %s', input_str)
                response = uri_client._postmsg(input_str)
                logger.info("Received Response : %s , \n \n ", response)
            
                logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
                
            logger.info("Work order id exists")
            id = 100    
            for x in range(5):
                j['params']['workOrderId'] = id + x
                input_str = json.dumps(j)
                logger.info('input str %s', input_str)
                response = uri_client._postmsg(input_str)
                logger.info("Received Response : %s , \n \n ", response);
            
            logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
                
            logger.info("Test max count reached and buys status")
            id = 105
            for x in range(10):
                j['params']['workOrderId'] = id + x
                input_str = json.dumps(j)
                logger.info('input str %s', input_str)
                response = uri_client._postmsg(input_str)
                logger.info("Received Response : %s , \n \n ", response);
                
            logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
            
            logger.info("Adding a work order id 109 into processed table")
            KvHelper.set("wo-processed", "109", "109")
            
            logger.info("Sending a new request with work order id %s", id + x)
            j['params']['workOrderId'] = id + x
            input_str = json.dumps(j)
            logger.info('input str %s', input_str)
            response = uri_client._postmsg(input_str)
            logger.info("Received Response : %s , \n \n ", response);
            
            logger.info("time stamp lookup  : %s", KvHelper.lookup("wo-timestamps"))
            
            work_orders = KvHelper.lookup("wo-scheduled")
            for wo_id in work_orders:
                KvHelper.remove("wo-scheduled", wo_id)
            
            logger.info("adding 3 entries into processing scheduled and processed table to test boot flow")
            KvHelper.set("wo-scheduled", "100", input_str)
            KvHelper.set("wo-processing", "101", input_str)
            KvHelper.set("wo-processed", "102", input_str)
            
            logger.info("restart tcf listener and verify it adds to its internal list during boot up")

    exit(0)
def LocalMain(config) :
    
    if not input_json_str and not input_json_dir:
       logger.error("JSON input file is not provided")
       exit(1)
    
    if not output_json_file_name:
        logger.error("JSON output file is not provided")
        exit(1)
    
    if not server_uri:
        logger.error("Server URI is not provided")
        exit(1)
        
    logger.info('Execute work order')
    uri_client = GenericServiceClient(server_uri) 
    response = None
    if input_json_dir:
        directory = os.fsencode(input_json_dir)
        files = os.listdir(directory)
            
        for file in sorted(files) :
            logger.info("------------------Input file name: %s ---------------\n",file.decode("utf-8"))
            input_json_str1 = helper.read_json_file((directory.decode("utf-8") + file.decode("utf-8")))
            
            #----------------------------------------------------------------------------------

            #If Client request is WorkOrderSubmit,a requester payload’s signature with the requester private signing key is generated.
            if "WorkOrderSubmit" in input_json_str1 :
                session_iv = helper.generate_sessioniv()
                encrypted_session_key = helper.generate_encrypted_session_key(session_iv, worker_obj.worker_encryption_key)
                input_json_obj = json.loads(input_json_str1)
                wo_id = None
                input_json_str1 = sig_obj.generate_client_signature(input_json_str1, worker_obj, private_key, session_iv, encrypted_session_key)
                if input_json_str1 is None :
                    logger.error("Request could not be signed hence rejecting this workorder submit request")
                    wo_id = input_json_obj["params"]["workOrderId"]
                    continue
            #----------------------------------------------------------------------------------

            # Update the worker ID
            if response:
                if "workerId" in input_json_str1 :
                   #Retrieving the worker id from the "WorkerRetrieve" response and update the worker id information for the further json requests
                   if 'result' in response and 'ids' in response["result"].keys():
                       input_json_final = json.loads(input_json_str1)
                       input_json_final['params']['workerId'] = response['result']['ids'][0]
                       input_json_str1 = json.dumps(input_json_final)
                       logger.info("**********Worker details Updated with Worker ID*********\n%s\n", response['result']['ids'][0])
            #-----------------------------------------------------------------------------------

            logger.info("*********Request Json********* \n%s\n", input_json_str1)
            response = uri_client._postmsg(input_json_str1)
            logger.info("**********Received Response*********\n%s\n", response)
             #-----------------------------------------------------------------------------------

            #Worker details are loaded into Worker_Obj
            if "WorkerRetrieve" in input_json_str1  and 'result' in response:
                    worker_obj.load_worker(response)
            #----------------------------------------------------------------------------------

            # Polling for the "WorkOrderGetResult" and break when you get the result
            while('WorkOrderGetResult' in input_json_str1 and 'result' not in response):
                if response["error"]["code"] == 9:
                    break
                input_json_obj = json.loads(input_json_str1)
                if wo_id ==  input_json_obj["params"]["workOrderId"] :
                    logger.error("This work order request was rejected by client. Hence no result ")
                    break
                response = uri_client._postmsg(input_json_str1)
                logger.info(" Received Response : %s, \n \n ", response)
                time.sleep(3)
            #----------------------------------------------------------------------------------

            #Verify the signature
            if ( 'WorkOrderGetResult' in input_json_str1 ):
                sig_bool = sig_obj.verify_signature(json.dumps(response),worker_obj)
                try:
                    if sig_bool > 0:
                        logger.info('Signature Verified')
                    else :
                        logger.info('Signature Failed')
                except:
                        logger.error("ERROR: Failed to analyze Signature Verification")
                helper.decrypted_response(json.dumps(response), encrypted_session_key)

            #----------------------------------------------------------------------------------
    else :
        logger.info('Input Request %s', input_json_str)
        response = uri_client._postmsg(input_json_str_1)
        logger.info("Received Response : %s , \n \n ", response);

    exit(0)
Beispiel #10
0
def LocalMain(config):

    if config.get('KvStorage') is None:
        logger.error("Kv Storage path is missing")
        sys.exit(-1)

    KvHelper = KvStorage()
    KvHelper.open((TCFHOME + '/' + config['KvStorage']['StoragePath']))

    if not input_json_str and not input_json_dir:
        logger.error("JSON input file is not provided")
        exit(1)

    if not output_json_file_name:
        logger.error("JSON output file is not provided")
        exit(1)

    if not server_uri:
        logger.error("Server URI is not provided")
        exit(1)

    logger.info('Execute work order')
    uri_client = GenericServiceClient(server_uri)
    response = None
    if input_json_dir:
        directory = os.fsencode(input_json_dir)
        files = os.listdir(directory)

        for file in sorted(files):
            input_json_str1 = enclave_helper.read_json_file(
                (directory.decode("utf-8") + file.decode("utf-8")))

            #----------------------------------------------------------------------------------

            #If Client request is WorkOrderSubmit,a requester payload’s signature with the requester private signing key is generated.
            if "WorkOrderSubmit" in input_json_str1:
                input_json_str1 = signature_generate(input_json_str1)
                if input_json_str1 is None:
                    continue
            #----------------------------------------------------------------------------------

            # Update the worker ID
            if response:
                if "workerId" in input_json_str1:
                    #Retrieving the worker id from the "WorkerRetrieve" response and update the worker id information for further json requests
                    if 'result' in response and 'ids' in response[
                            "result"].keys():
                        input_json_final = json.loads(input_json_str1)
                        input_json_final['params']['workerId'] = response[
                            'result']['ids'][0]
                        input_json_str1 = json.dumps(input_json_final)
                        logger.info(
                            "**********Worker details Updated with Worker ID*********\n%s\n",
                            response['result']['ids'][0])
            #-----------------------------------------------------------------------------------

            logger.info("*********Request Json********* \n%s\n",
                        input_json_str1)
            response = uri_client._postmsg(input_json_str1)
            logger.info("**********Received Response*********\n%s\n", response)

            #-----------------------------------------------------------------------------------

            #Worker details are loaded into Worker_Obj
            if "WorkerRetrieve" in input_json_str1:
                worker_obj.load_worker(response)
            #----------------------------------------------------------------------------------

            # Key already exist test scenario "test_wo_submit_key_already_exist"
            response = uri_client._postmsg(input_json_str1)
            if 'WorkOrderSubmit' in input_json_str1 and 'result' not in response:
                logger.info("*****key already exist *****")
                assert response['error']['message'], 'key already exist'
                assert response['error']['code'], 8
            #----------------------------------------------------------------------------------

            # Polling for the "WorkOrderGetResult" and break when you get the result
            while ('WorkOrderGetResult' in input_json_str1
                   and 'result' not in response):
                response = uri_client._postmsg(input_json_str1)
                logger.info(" Received Response : %s, \n \n ", response)
                time.sleep(3)
            #----------------------------------------------------------------------------------

            #Verify the signature
            if ('WorkOrderGetResult' in input_json_str1):
                sig_bool = verify_signature(json.dumps(response))
            #----------------------------------------------------------------------------------
    else:
        logger.info('Input Request %s', input_json_str)
        input_json_str_1 = signature_generate(input_json_str)
        response = uri_client._postmsg(input_json_str_1)
        logger.info("Received Response : %s , \n \n ", response)
        sig_bool = verify_signature(json.dumps(response))

    exit(0)
Beispiel #11
0
class WorkOrderReceiptJRPCImpl(WorkOrderReceiptInterface):
    """
    WorkOrderReceiptJRPCImpl is an implementation of WorkOrderReceiptInterface
    """
    def __init__(self, config):
        self.__uri_client = GenericServiceClient(config["tcf"]["json_rpc_uri"])

    def work_order_receipt_create(self,
                                  work_order_id,
                                  worker_service_id,
                                  worker_id,
                                  requester_id,
                                  receipt_create_status,
                                  work_order_request_hash,
                                  requester_nonce,
                                  requester_signature,
                                  signature_rules,
                                  receipt_verification_key,
                                  id=None):
        """
        Creating a Work Order Receipt json rpc request and submit tcs listener
        """
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptCreate",
            "id": id,
            "params": {
                "workOrderId": work_order_id,
                "workerServiceId": worker_service_id,
                "workerId": worker_id,
                "requesterId": requester_id,
                "receiptCreateStatus": receipt_create_status,
                "workOrderRequestHash": work_order_request_hash,
                "requesterGeneratedNonce": requester_nonce,
                "requesterSignature": requester_signature,
                "signatureRules": signature_rules,
                "receiptVerificationKey": receipt_verification_key
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_receipt_update(self,
                                  work_order_id,
                                  updater_id,
                                  update_type,
                                  update_data,
                                  update_signature,
                                  signature_rules,
                                  id=None):
        """
        Update a Work Order Receipt json rpc request and submit tcs listener
        """
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptUpdate",
            "id": id,
            "params": {
                "workOrderId": work_order_id,
                "updaterId": updater_id,
                "updateType": update_type,
                "updateData": update_data,
                "updateSignature": update_signature,
                "signatureRules": signature_rules
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_receipt_retrieve(self, work_order_id, id=None):
        """
        Retrieve a Work Order Receipt json rpc request and submit tcs listener
        """
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptRetrieve",
            "id": id,
            "params": {
                "workOrderId": work_order_id
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_receipt_update_retrieve(self,
                                           work_order_id,
                                           updater_id,
                                           update_index,
                                           id=None):
        """
        Retrieving a Work Order Receipt Update
        """
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptUpdateRetrieve",
            "id": id,
            "params": {
                "workOrderId": work_order_id,
                "updaterId": updater_id,
                "updateIndex": update_index
            }
        }
        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_receipt_lookup(self,
                                  worker_service_id=None,
                                  worker_id=None,
                                  requester_id=None,
                                  receipt_status=None,
                                  id=None):
        """
        Work Order Receipt Lookup
        """
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptLookUp",
            "id": id,
            "params": {}
        }

        if worker_service_id is not None:
            json_rpc_request["params"]["workerServiceId"] = worker_service_id

        if worker_id is not None:
            json_rpc_request["params"]["workerId"] = worker_id

        if requester_id is not None:
            json_rpc_request["params"]["requesterId"] = requester_id

        if receipt_status is not None:
            json_rpc_request["params"]["requestCreateStatus"] = receipt_status

        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response

    def work_order_receipt_lookup_next(self,
                                       last_lookup_tag,
                                       worker_service_id=None,
                                       worker_id=None,
                                       requester_id=None,
                                       receipt_status=None,
                                       id=None):
        """
        Work Order Receipt Lookup Next
        """
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderReceiptLookUpNext",
            "id": id,
            "params": {
                "lastLookUpTag": last_lookup_tag
            }
        }

        if worker_service_id is not None:
            json_rpc_request["params"]["workerServiceId"] = worker_service_id

        if worker_id is not None:
            json_rpc_request["params"]["workerId"] = worker_id

        if requester_id is not None:
            json_rpc_request["params"]["requesterId"] = requester_id

        if receipt_status is not None:
            json_rpc_request["params"]["requestCreateStatus"] = receipt_status

        response = self.__uri_client._postmsg(json.dumps(json_rpc_request))
        return response