Exemplo n.º 1
0
    def process_call(self, call: Call, network: IconService = None):
        if self._network_only and network is None:
            raise URLException("Set network URL")

        try:
            if network is not None:
                response = network.call(call)
            else:
                request = {
                    "from": Address.from_string(call.from_),
                    "to": Address.from_string(call.to),
                    "dataType": "call",
                    "data": {
                        "method": call.method
                    }
                }

                if isinstance(call.params, dict):
                    request["data"]["params"] = call.params

                response = self._query(request=request)
        except IconServiceBaseException as e:
            response = e.message

        return response
Exemplo n.º 2
0
 def _get_channel(path: str):
     tokens = re.split("/(?=[^/]+$)", path.rstrip('/'))
     if tokens[0] == '/api/v3':
         return tokens[1]
     elif tokens == ['/api', 'v3']:
         return ''
     raise URLException('Invalid URI path')
Exemplo n.º 3
0
    def __init__(self,
                 base_domain_url: str,
                 version: int,
                 request_kwargs: dict = None):
        """
        The initializer to be set with base domain URL and version.

        :param base_domain_url: base domain URL as like <scheme>://<host>:<port>
        :param version: version for RPC server
        :param request_kwargs: kwargs for setting to head of request
        """
        if not self._validate_base_domain_url(base_domain_url):
            logger.error(
                f"While setting HTTPProvider, raised URLException because the URL is invalid. "
                f"URL: {base_domain_url}")
            raise URLException(
                "Invalid base domain URL. "
                "Valid base domain URL format is as like <scheme>://<host>:<port>."
            )
        self._full_path_url = None
        self._base_domain_url = base_domain_url
        self._version = version
        self._request_kwargs = request_kwargs or {}
        logger.info(
            f"Set HTTPProvider. "
            f"Base domain URL: {base_domain_url}, Version: {version}, Request kwargs: {self._request_kwargs}"
        )
Exemplo n.º 4
0
 def _return_customed_response(response):
     if response.ok:
         content_as_dict = json.loads(response.content)
         return content_as_dict["result"]
     else:
         try:
             content_as_dict = json.loads(response.content)
         except (JSONDecodeError, KeyError):
             raise URLException(response.content.decode("utf-8"))
         else:
             raise JSONRPCException(content_as_dict["error"])
    def __init__(self, base_domain_url: str, version: int, request_kwargs: dict = None):
        """
        The new initializer to be set with base domain URL and version.

        :param base_domain_url: base domain URL as like <scheme>://<host>:<port>
        :param version: version for RPC server
        :param request_kwargs: kwargs for setting to head of request
        """
        if not self.validate_base_domain_url(base_domain_url):
            raise URLException("Invalid base domain URL. "
                               "Valid base domain URL format is as like <scheme>://<host>:<port>.")
        self.base_domain_url = base_domain_url
        self.version = version
        self._request_kwargs = request_kwargs or {}
    def __init__(self, full_path_url: str, request_kwargs: dict = None):
        """
        The previous initializer to be set with full path url which is only as like <scheme>://<host>/api/v3 without version.

        :param full_path_url: full path URL as like <scheme>://<host>:<port>/api/v3
        :param request_kwargs: kwargs for setting to head of request
        """
        warn('This initializer is deprecated and replaced with new initializer '
             'where parameters are not only endpoint but also version.')
        url_components = urlparse(full_path_url)
        if url_components.path != '/api/v3':
            raise URLException("Invalid full path URL. "
                               "The only valid full path for the previous initializer is "
                               "'<scheme>://<host>:<port>/api/v3'.")
        self.__init__(url_components.geturl(), int(url_components.path[-1:]))
        self._request_kwargs = request_kwargs or {}
Exemplo n.º 7
0
    def __init__(self,
                 base_domain_url: str,
                 version: int,
                 request_kwargs: dict = None):
        """
        The initializer to be set with base domain URL and version.

        :param base_domain_url: base domain URL as like <scheme>://<host>:<port>
        :param version: version for RPC server
        :param request_kwargs: kwargs for setting to head of request
        """
        uri = urlparse(base_domain_url)
        if uri.path != '':
            raise URLException('Path is not allowed')
        self._serverUri = f'{uri.scheme}://{uri.netloc}'
        self._channel = ''
        self._version = version
        self._request_kwargs = request_kwargs or {}
        self._generate_url_map()
Exemplo n.º 8
0
    def process_message_tx(self,
                           network: IconService = None,
                           msg: str = "dummy",
                           block_confirm_interval: int = -1) -> dict:
        if self._network_only and network is None:
            raise URLException("Set network URL")

        if block_confirm_interval == -1:
            block_confirm_interval = self._block_confirm_interval

        msg_byte = msg.encode('utf-8')

        # build message tx
        transaction = MessageTransactionBuilder() \
            .from_(self._test1.get_address()) \
            .to(self._test1.get_address()) \
            .step_limit(10000000000) \
            .nid(3) \
            .nonce(100) \
            .data(f"0x{msg_byte.hex()}") \
            .build()

        # signing message tx
        request = SignedTransaction(transaction, self._test1)

        try:
            if network is not None:
                # Send the transaction to network
                tx_hash = network.send_transaction(request)
                sleep(block_confirm_interval)
                # Get transaction result
                tx_result = network.get_transaction_result(tx_hash)
            else:
                # process the transaction in local
                tx_results = self._process_transaction_in_local(
                    request.signed_transaction_dict)
        except IconServiceBaseException as e:
            tx_result = e.message

        return tx_result
Exemplo n.º 9
0
    def process_transaction(self,
                            request: SignedTransaction,
                            network: IconService = None,
                            block_confirm_interval: int = -1) -> dict:
        if self._network_only and network is None:
            raise URLException("Set network URL")

        if block_confirm_interval == -1:
            block_confirm_interval = self._block_confirm_interval

        if network is not None:
            # Send the transaction to network
            tx_hash: str = network.send_transaction(request)
            sleep(block_confirm_interval + 0.1)
            # Get transaction result
            tx_result: dict = network.get_transaction_result(tx_hash)
        else:
            # process the transaction in local
            tx_hash: str = self._process_transaction_in_local(
                request.signed_transaction_dict)
            tx_result: dict = self._get_tx_result(tx_hash)
        return tx_result
Exemplo n.º 10
0
    def _return_custom_response(
            response: requests.Response,
            full_response: bool = False) -> Union[str, list, dict]:
        if full_response:
            return json.loads(response.content)

        if response.ok:
            content_as_dict = json.loads(response.content)
            return content_as_dict["result"]
        else:
            try:
                content_as_dict = json.loads(response.content)
            except (JSONDecodeError, KeyError):
                logger.exception(
                    f"Raised URLException while returning the custom response. "
                    f"Response content: {response.content.decode('utf-8')}")
                raise URLException(response.content.decode("utf-8"))
            else:
                logger.error(
                    f"Raised JSONRPCException while returning the custom response. "
                    f"Error message: {content_as_dict['error']}")
                raise JSONRPCException(content_as_dict["error"])
Exemplo n.º 11
0
    def process_transaction_bulk(self,
                                 requests: list,
                                 network: IconService = None,
                                 block_confirm_interval: int = -1) -> list:
        if self._network_only and network is None:
            raise URLException("Set network URL")

        if block_confirm_interval == -1:
            block_confirm_interval = self._block_confirm_interval

        tx_results: list = []

        try:
            if network is not None:
                tx_hashes: list = []
                for req in requests:
                    # Send the transaction to network
                    tx_hash = network.send_transaction(req)
                    tx_hashes.append(tx_hash)

                sleep(block_confirm_interval)

                # Get transaction result
                for h in tx_hashes:
                    tx_result = network.get_transaction_result(h)
                    tx_results.append(tx_result)
            else:
                for req in requests:
                    # process the transaction in local
                    tx_result = self._process_transaction_in_local(
                        req.signed_transaction_dict)
                    tx_results.append(tx_result)
        except IconServiceBaseException as e:
            tx_result = e.message
            tx_results.append(tx_result)

        return tx_results