Пример #1
0
class BlockchainInterface:
    def __init__(self, config):
        # TODO: store list of contracts?
        self._config = config
        self._uri_client = HttpJrpcClient(config["ethereum"]["event_provider"])

    def newListener(self, contract, event, fromBlock='latest'):
        if self._is_jrpc_evt_required():
            # This will return the filter_id of newly created filter
            return self._new_JRPC_listener(event)
        else:
            return contract.events[event].createFilter(fromBlock=fromBlock)

    def _new_JRPC_listener(self, event, fromBlock='latest'):
        evt_hash = None
        if event == "workOrderCompleted":
            evt_hash = get_keccak_for_text(
                "workOrderCompleted(bytes32,bytes32,uint256,string," +
                "uint256,bytes4)")
        elif event == "workOrderSubmitted":
            evt_hash = get_keccak_for_text(
                "workOrderSubmitted(bytes32,bytes32,bytes32,string," +
                "uint256,address,bytes4)")
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "eth_newFilter",
            "id": random.randint(0, 100000)
        }
        contract_address = self\
            ._config["ethereum"]["work_order_contract_address"]
        json_rpc_request["params"] = get_new_filter_payload(
            evt_hash, contract_address)

        logging.debug("New filter request : %s", json.dumps(json_rpc_request))
        response = self._uri_client._postmsg(json.dumps(json_rpc_request))
        return response['result']

    def _is_jrpc_evt_required(self):
        """
        This function checks if the Ethereum client configured
        uses different endpoints for events & transaction calls
        """
        provider = self._config["ethereum"]["provider"]
        evt_provider = self._config["ethereum"]["event_provider"]

        if provider == evt_provider:
            return False
        else:
            return True
Пример #2
0
class JRPCWorkOrderReceiptImpl(WorkOrderReceipt):
    """
    This class is an implementation of WorkOrderReceiptInterface
    to manage work order receipts from the client side.
    """
    def __init__(self, config):
        self.__uri_client = HttpJrpcClient(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):
        """
        Create a Work Order Receipt JSON RPC request and submit to an
        Avalon listener.

        Parameters:
        work_order_id            Work order ID
        worker_service_id        Worker service ID
        worker_id                Worker ID value derived from the worker's DID
        requester_id             Requester ID
        receipt_create_status    Receipt creation status
        work_order_request_hash  Work order request hash value
        requester_nonce          Requester generated nonce
        requester_signature      Signature generated by the requester
        signature_rules          Defines hashing and signing algorithms;
                                 separated by forward slash '/'
        receipt_verification_key Receipt verification key
        id                       Optional JSON RPC request ID
        """
        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 an
        Avalon listener.

        Parameters:
        work_order_id    Work Order ID
        updater_id       Updater ID
        update_type      Updater type
        update_data      Receipt update data
        update_signature Signature of the update
        signature_rules  Defines hashing and signing algorithms;
                         separated by forward slash '/'
        id               Optional JSON RPC request ID
        """
        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 to an
        Avalon listener.

        Parameters:
        work_order_id Work order ID
        id            Optional Optional JSON RPC request ID
        """
        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):
        """
        Retrieve a work order receipt update JSON RPC request and submit to an
        Avalon listener.

        Parameters:
        work_order_id Work order ID
        id            Optional Optional JSON RPC request ID
        """
        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
        All fields are optional and, if present, condition should match for
        all fields. If none are passed it should return all
        work order receipts.

        Parameters:
        worker_service_id        Optional worker service ID to lookup
        worker_id                Optional worker ID value derived from
                                 the worker's DID
        requester_id             Optional requester ID to lookup
        receipt_status           Optional receipt status
        id                       Optional JSON RPC request ID
        """
        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.
        Call to retrieve subsequent results after calling
        work_order_receipt_lookup or

        Parameters:
        last_lookup_tag          Last lookup tag returned by
                                 work_order_receipt_lookup
        worker_service_id        Optional worker service ID to lookup
        worker_id                Optional worker ID value derived from
                                 the worker's DID
        requester_id             Optional requester ID to lookup
        receipt_status           Optional receipt status
        id                       Optional JSON RPC request ID
        """
        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
Пример #3
0
class JRPCWorkerRegistryImpl(WorkerRegistry):
    """
    This class is to read the worker registry to get the more details
    of worker.
    """
    def __init__(self, config):
        self.__uri_client = HttpJrpcClient(config["tcf"]["json_rpc_uri"])

    def worker_retrieve(self, worker_id, id=None):
        """
        Retrieve the worker identified by worker ID.

        Parameters:
        worker_id Worker ID value derived from the worker's DID
        id        Optional Optional JSON RPC request ID

        Returns:
        JRPC response containing:
        organization ID, application ID, worker status,
        and worker details.
        """

        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=None,
                      organization_id=None,
                      application_type_id=None,
                      id=None):
        """
        Worker lookup based on worker type, organization ID,
        and application ID.
        All fields are optional and, if present, condition should match for
        all fields. If none are passed it should return all workers.

        Parameters:
        worker_type         Optional characteristic of Workers for which you
                            may wish to search. Currently defined types are:
                            * "TEE-SGX": an Intel SGX Trusted Execution
                              Environment
                            * "MPC": Multi-Party Compute
                            * "ZK": Zero-Knowledge
        organization_id     Optional parameter representing the
                            organization that hosts the Worker,
                            e.g. a bank in the consortium or
                            anonymous entity
        application_type_id Optional application type that has to be supported
                            by the worker
        id                  Optional Optional JSON RPC request ID


        Returns:
        JRPC response containing number of workers,
        lookup tag, and list of worker IDs.
        """
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerLookUp",
            "id": id,
            "params": {}
        }

        if worker_type is not None:
            json_rpc_request["params"]["workerType"] = worker_type.value

        if organization_id is not None:
            json_rpc_request["params"]["organizationId"] = organization_id

        if application_type_id is not None:
            json_rpc_request["params"]["applicationTypeId"] = \
                application_type_id

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

    def worker_lookup_next(self,
                           lookup_tag,
                           worker_type=None,
                           organization_id=None,
                           application_type_id=None,
                           id=None):
        """
        Retrieve subsequent Worker lookup results based on worker type,
        organization ID, and application ID.
        Similar to workerLookUp with additional parameter lookup_tag.

        Parameters:
        lookup_tag          Used to lookup subsequent results after calling
                            worker_lookup
        worker_type         Optional characteristic of Workers for which you
                            may wish to search. Currently defined types are:
                            * "TEE-SGX": an Intel SGX Trusted Execution
                              Environment
                            * "MPC": Multi-Party Compute
                            * "ZK": Zero-Knowledge
        organization_id     Optional parameter representing the
                            organization that hosts the Worker,
                            e.g. a bank in the consortium or
                            anonymous entity
        application_type_id Optional application type that has to be supported
                            by the worker
        id                  Optional Optional JSON RPC request ID

        Returns:
        JRPC response containing number of workers,
        lookup tag, and list of worker IDs.
        """

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerLookUpNext",
            "id": id,
            "params": {
                "lookUpTag": lookup_tag
            }
        }

        if worker_type is not None:
            json_rpc_request["params"]["workerType"] = worker_type.value

        if organization_id is not None:
            json_rpc_request["params"]["organizationId"] = organization_id

        if application_type_id is not None:
            json_rpc_request["params"]["applicationTypeId"] = \
                application_type_id

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

    def worker_register(self,
                        worker_id,
                        worker_type,
                        org_id,
                        application_type_ids,
                        details,
                        id=None):
        """
        Adds worker details to registry

        Parameters:
        worker_id            Worker ID value derived from the worker's DID
        worker_type          Type of Worker. Currently defined types are:
                             * "TEE-SGX": an Intel SGX Trusted Execution
                               Environment
                             * "MPC": Multi-Party Compute
                             * "ZK": Zero-Knowledge
        org_id               Organization that hosts the Worker,
                             e.g. a bank in the consortium or
                             anonymous entity
        application_type_ids Application types supported by the worker
        id                   Optional JSON RPC request ID

        Returns:
        JRPC response with worker registry status.
        """
        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": json.loads(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.

        Parameters:
        worker_id Worker ID value derived from the worker's DID
        details   Detailed information about the worker in
                  JSON RPC format as defined in
        id        Optional JSON RPC request ID

        Returns:
        JRPC response with update status.
        """
        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.

        Parameters:
        worker_id  Worker ID value derived from the worker's DID
        status     Worker status value to set
        id         Optional JSON RPC request ID

        Returns:
        JRPC response with status.
        """
        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
Пример #4
0
class EventProcessor:
    def __init__(self, config):
        self._config = config
        self._uri_client = HttpJrpcClient(config["ethereum"]["event_provider"])
        self._wo_completed_hash = get_keccak_for_text(
            "workOrderCompleted(bytes32,bytes32,uint256,string," +
            "uint256,bytes4)")
        self._wo_submitted_hash = get_keccak_for_text(
            "workOrderSubmitted(bytes32,bytes32,bytes32,string," +
            "uint256,address,bytes4)")

    async def listener(self, eventListener):
        logging.info("Started listener for events")
        while True:
            for event in eventListener.get_new_entries():
                await self.queue.put(event)
                logging.debug("Event pushed into listener Queue")
            await asyncio.sleep(LISTENER_SLEEP_DURATION)

    async def jrpc_listener(self, eventListener):
        logging.info("Started jrpc listener for events")
        while True:
            json_rpc_request = {
                "jsonrpc": "2.0",
                "method": "eth_getFilterLogs",
                "id": random.randint(0, 100000)
            }
            json_rpc_request["params"] = [eventListener]

            logging.debug("New events request %s",
                          json.dumps(json_rpc_request))
            response = self._uri_client._postmsg(json.dumps(json_rpc_request))

            events = response['result']
            last_processed_block = get_last_read_block()

            for event in events:
                block_num = event["blockNumber"]
                block_num = int(block_num, 16) if is_valid_hex_str(block_num)\
                    else block_num
                if block_num > last_processed_block:
                    # Placeholder flag to mark event format
                    event["jsonrpc"] = "2.0"
                    await self.queue.put(event)
                    logging.info("Event pushed into listener Queue")

            await asyncio.sleep(LISTENER_SLEEP_DURATION)

    async def handler(self, callback, *kargs, **kwargs):
        logging.info("Started handler to handle events")
        while True:
            event = await self.queue.get()
            logging.info("Event popped from listener Queue")
            normalized_event = normalize_event(event, self._wo_submitted_hash,
                                               self._wo_completed_hash)

            set_last_read_block(normalized_event["blockNumber"])

            callback(normalized_event, *kargs, **kwargs)
            self.queue.task_done()

    async def start(self, eventListener, callback, *kargs, **kwargs):
        self.queue = asyncio.Queue()
        loop = asyncio.get_event_loop()
        # Check if the eventListener is an id returned from createNewFilter
        # JRPC call in which case it should be a hex string. Else it is a
        # filter created using web3 library
        if isinstance(eventListener, str) and is_valid_hex_str(eventListener):
            self.listeners = [
                loop.create_task(self.jrpc_listener(eventListener))
                for _ in range(1)
            ]
        else:
            self.listeners = [
                loop.create_task(self.listener(eventListener))
                for _ in range(1)
            ]
        self.handlers = [
            loop.create_task(self.handler(callback, *kargs, **kwargs))
            for _ in range(1)
        ]

        await asyncio.gather(*self.listeners)  # infinite loop
        await self.queue.join()  # this code should never run
        await self.stop()  # this code should never run

    async def stop(self):
        for process in self.listeners:
            process.cancel()
        for process in self.handlers:
            process.cancel()
        logging.debug("---exit---")
Пример #5
0
def local_main(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 = HttpJrpcClient(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["result"]["details"])
            # -----------------------------------------------------------------

            # Poll for "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['result'], worker_obj.verification_key)
                try:
                    if sig_bool > 0:
                        LOGGER.info("Signature Verified")
                        enclave_helper.decrypted_response(
                            response['result'], session_key, session_iv)
                    else:
                        LOGGER.info("Signature verification Failed")
                        exit(1)
                except Exception as e:
                    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)
Пример #6
0
class JRPCWorkOrderImpl(WorkOrder):
    """
    This class is for to manage to the work orders from client side.
    """

    def __init__(self, config):
        self.__uri_client = HttpJrpcClient(config["tcf"]["json_rpc_uri"])

    def work_order_submit(self, work_order_id, worker_id,
                          requester_id, work_order_request, id=None):
        """
        Submit work order request to avalon listener.
        work_order_request is work order request in json string format.
        """
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkOrderSubmit",
            "id": id
        }
        json_rpc_request["params"] = json.loads(work_order_request)

        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
        """
        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 encryption_key_get(self, worker_id, requester_id,
                           last_used_key_nonce=None, tag=None,
                           signature_nonce=None, signature=None, id=None):
        """
        API to receive a Worker's key
        parameters
            worker_id is the id of the worker whose
            encryption key is requested.
            last_used_key_nonce is an optional nonce associated
            with last retrieved key. If it is provided,
            the key retrieved should be newer than this one.
            Otherwise any key can be retrieved.
            tag is tag that should be associated with the returned key
            e.g. requester id. This is an optional parameter.
            If it is not provided, requesterId is used as a key.
            requester_id is the id of the requester that plans to use
            the returned key to submit one or more work orders using this key.
            signature_nonce is an optional parameter and is used only if
            signature below is also provided.
            signature is an optional signature
            of worker_id, last_used_key_nonce, tag, and signature_nonce.
        """
        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_nonce,
                           tag, signature_nonce, signature, id=None):
        """
        API called by a Worker or Worker Service to receive a Worker's key.
        parameters
            1. worker_id is an id of the worker to retrieve an encryption
            key for.
            2. encryption_key is an encryption key.
            3. encryption_nonce is a nonce associated with the key.
            4. tag is tag that should be associated with the returned key,
            e.g. requester id. This is an optional parameter. If it is not
             provided, requesterId below is used as a key.
            5.signature is a signature generated by
            the worker on the worker_id, tag and encryption_nonce.
        Returns
            jrpc response with the result of the operation.
        """
        # Not supported for direct model.
        return {
            "jsonrpc": "2.0",
            "method": "EncryptionKeySet",
            "id": id,
            "result": {
                "code": JRPCErrorCodes.INVALID_PARAMETER_FORMAT_OR_VALUE,
                "message": "Unsupported method"
            }
        }
Пример #7
0
class JRPCWorkerRegistryImpl(WorkerRegistry):
    """
    This class is to read the worker registry to get the more details
    of worker.
    """

    def __init__(self, config):
        self.__uri_client = HttpJrpcClient(config["tcf"]["json_rpc_uri"])

    def worker_retrieve(self, worker_id, id=None):
        """
        Retrieve the worker identified by worker id
        Returns jrpc response containing
        organization id, application id, worker status,
        worker details
        """

        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=None, organization_id=None,
                      application_type_id=None, id=None):
        """
        Worker lookup based on worker type, organization id
        and application id
        Returns jrpc response containing number of workers,
        lookup tag and list of worker ids.
        """
        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerLookUp",
            "id": id,
            "params": {
            }
        }

        if worker_type is not None:
            json_rpc_request["params"]["workerType"] = worker_type.value

        if organization_id is not None:
            json_rpc_request["params"]["organizationId"] = organization_id

        if application_type_id is not None:
            json_rpc_request["params"]["applicationTypeId"] = \
                application_type_id

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

    def worker_lookup_next(self, lookup_tag, worker_type=None,
                           organization_id=None, application_type_id=None,
                           id=None):
        """
        Similar to workerLookUp with additional
        parameter lookup_tag
        Returns jrpc response containing number of workers,
        lookup tag and list of worker ids.
        """

        json_rpc_request = {
            "jsonrpc": "2.0",
            "method": "WorkerLookUpNext",
            "id": id,
            "params": {
                "lookUpTag": lookup_tag
            }
        }

        if worker_type is not None:
            json_rpc_request["params"]["workerType"] = worker_type.value

        if organization_id is not None:
            json_rpc_request["params"]["organizationId"] = organization_id

        if application_type_id is not None:
            json_rpc_request["params"]["applicationTypeId"] = \
                application_type_id

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

    def worker_register(self, worker_id, worker_type, org_id,
                        application_type_ids, details, id=None):
        """
        Adds worker details to registry
        Returns jrpc response with worker registry status.
        """
        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": json.loads(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
        Returns jrpc response with update status.
        """
        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
        Returns jrpc response with status.
        """
        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
Пример #8
0
class JRPCWorkOrderReceiptImpl(WorkOrderReceipt):
    """
    This class is an implementation of WorkOrderReceiptInterface
    to manage work order receipt from client side.
    """
    def __init__(self, config):
        self.__uri_client = HttpJrpcClient(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