Ejemplo n.º 1
0
    async def icx_sendTransaction(**kwargs):
        channel = kwargs['context']['channel']
        url = kwargs['context']['url']
        path = urlparse(url).path
        del kwargs['context']

        method = 'icx_sendTransaction'
        request = make_request(method, kwargs)
        score_stub = get_icon_stub_by_channel_name(channel)
        icon_stub = score_stub
        response = await icon_stub.async_task().validate_transaction(request)
        # Error Check
        response_to_json_query(response)

        channel_tx_creator_stub = StubCollection().channel_tx_creator_stubs[channel]
        response_code, tx_hash = await channel_tx_creator_stub.async_task().create_icx_tx(kwargs)

        if response_code == message_code.Response.fail_no_permission:
            return await IcxDispatcher.__relay_icx_transaction(url, path, kwargs)

        if response_code != message_code.Response.success:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_REQUEST,
                message=message_code.responseCodeMap[response_code][1],
                http_status=message_code.get_response_http_status_code(response_code, status.HTTP_BAD_REQUEST)
            )

        if tx_hash is None:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_REQUEST,
                message='txHash is None',
                http_status=status.HTTP_BAD_REQUEST
            )

        return convert_params(tx_hash, ParamType.send_tx_response)
Ejemplo n.º 2
0
    async def icx_getTransactionResult(**kwargs):
        channel = kwargs['context']['channel']
        request = convert_params(kwargs, RequestParamType.get_tx_result)
        channel_stub = StubCollection().channel_stubs[channel]
        verify_result = dict()

        tx_hash = request["txHash"]
        response_code, result = await channel_stub.async_task(
        ).get_invoke_result(tx_hash)

        if response_code == message_code.Response.fail_tx_not_invoked:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_PARAMS,
                message=message_code.responseCodeMap[response_code][1],
                http_status=status.HTTP_BAD_REQUEST)
        elif response_code == message_code.Response.fail_invalid_key_error or \
                response_code == message_code.Response.fail:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_PARAMS,
                message='Invalid params txHash',
                http_status=status.HTTP_BAD_REQUEST)

        if result:
            try:
                result_dict = json.loads(result)
                verify_result = result_dict
            except json.JSONDecodeError as e:
                Logger.warning(
                    f"your result is not json, result({result}), {e}")

        response = convert_params(verify_result,
                                  ResponseParamType.get_tx_result)
        return response
Ejemplo n.º 3
0
    async def icx_sendTransaction(**kwargs):
        channel = kwargs['context']['channel']
        url = kwargs['context']['url']
        path = urlparse(url).path
        del kwargs['context']

        if RestProperty().node_type == NodeType.CitizenNode:
            dispatch_protocol = IcxDispatcher.get_dispatch_protocol_from_url(
                url)
            Logger.debug(f'Dispatch Protocol: {dispatch_protocol}')
            redirect_protocol = StubCollection().conf.get(
                ConfigKey.REDIRECT_PROTOCOL)
            Logger.debug(f'Redirect Protocol: {redirect_protocol}')
            if redirect_protocol:
                dispatch_protocol = redirect_protocol
            Logger.debug(f'Protocol: {dispatch_protocol}')

            return await redirect_request_to_rs(dispatch_protocol,
                                                kwargs,
                                                RestProperty().rs_target,
                                                path=path[1:])

        method = 'icx_sendTransaction'
        request = make_request(method, kwargs)
        score_stub = get_icon_stub_by_channel_name(channel)
        icon_stub = score_stub
        response = await icon_stub.async_task().validate_transaction(request)
        # Error Check
        response_to_json_query(response)

        channel_tx_creator_stub = StubCollection(
        ).channel_tx_creator_stubs[channel]
        response_code, tx_hash = await channel_tx_creator_stub.async_task(
        ).create_icx_tx(kwargs)

        if response_code != message_code.Response.success:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_REQUEST,
                message=message_code.responseCodeMap[response_code][1],
                http_status=status.HTTP_BAD_REQUEST)

        if tx_hash is None:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_REQUEST,
                message='txHash is None',
                http_status=status.HTTP_BAD_REQUEST)

        return convert_params(tx_hash, ParamType.send_tx_response)
Ejemplo n.º 4
0
    async def icx_getBlock(**kwargs):
        channel = kwargs['context']['channel']
        request = convert_params(kwargs, RequestParamType.get_block)
        if all(param in request for param in ["hash", "height"]):
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_PARAMS,
                message='Invalid params (only one parameter is allowed)',
                http_status=status.HTTP_BAD_REQUEST)
        if 'hash' in request:
            block_hash, result = await get_block_by_params(
                block_hash=request['hash'], channel_name=channel)
        elif 'height' in request:
            block_hash, result = await get_block_by_params(
                block_height=request['height'], channel_name=channel)
        else:
            block_hash, result = await get_block_by_params(
                block_height=-1, channel_name=channel)

        response_code = result['response_code']
        check_response_code(response_code)

        block = result['block']
        if block['version'] == BLOCK_v0_1a:
            response = convert_params(result['block'],
                                      ResponseParamType.get_block_v0_1a_tx_v3)
        elif block['version'] == BLOCK_v0_3:
            response = convert_params(result['block'],
                                      ResponseParamType.get_block_v0_3_tx_v3)
        else:
            response = block
        return response_to_json_query(response)
Ejemplo n.º 5
0
    def process_response(self, response, log_extra=None, log_format=None):
        """
        Process the response and return the 'result' portion if present.

        :param response: The JSON-RPC response string to process.
        :return: The response string, or None
        """
        if response:
            # Log the response before processing it
            self.log_response(response, log_extra, log_format)
            # If it's a json string, parse to object
            if isinstance(response, basestring):
                try:
                    response = json.loads(response)
                except ValueError:
                    raise exceptions.ParseResponseError()
            # Validate the response against the Response schema (raises
            # jsonschema.ValidationError if invalid)
            if config.validate:
                self.validator.validate(response)
            if isinstance(response, list):
                # Batch request - just return the whole response
                return response
            else:
                # If the response was "error", raise to ensure it's handled
                if 'error' in response and response['error'] is not None:
                    raise GenericJsonRpcServerError(
                        code=JsonError.INVALID_REQUEST,
                        message=response['error'].get('message'),
                        http_status=status.HTTP_BAD_REQUEST
                    )
                # All was successful, return just the result part
                return response.get('result')
        # No response was given
        return None
Ejemplo n.º 6
0
    async def __relay_icx_transaction(path, message: dict, relay_target):
        if not relay_target:
            raise GenericJsonRpcServerError(
                code=JsonError.INTERNAL_ERROR,
                message=message_code.responseCodeMap[
                    message_code.Response.fail_invalid_peer_target][1],
                http_status=status.HTTP_INTERNAL_ERROR)

        return await relay_tx_request(relay_target, message, path=path[1:])
Ejemplo n.º 7
0
def get_channel_stub_by_channel_name(channel_name):
    try:
        channel_stub = StubCollection().channel_stubs[channel_name]
    except KeyError:
        raise GenericJsonRpcServerError(code=JsonError.INVALID_REQUEST,
                                        message="Invalid channel name",
                                        http_status=status.HTTP_BAD_REQUEST)
    else:
        return channel_stub
Ejemplo n.º 8
0
    async def icx_sendTransaction(context: Dict[str, str], **kwargs):
        channel = context.get('channel')
        url = context.get('url')

        path = urlparse(url).path

        method = 'icx_sendTransaction'
        request = make_request(method, kwargs)
        score_stub = get_icon_stub_by_channel_name(channel)
        icon_stub = score_stub
        response = await icon_stub.async_task().validate_transaction(request)
        # Error Check
        response_to_json_query(response)

        # DosGuard
        if StubCollection().conf.get(ConfigKey.DOS_GUARD_ENABLE, False):
            response = await icon_stub.async_task().dos_guard(kwargs)
            # Error Check
            response_to_json_query(response)

        channel_tx_creator_stub = StubCollection(
        ).channel_tx_creator_stubs[channel]
        response_code, tx_hash, relay_target = \
            await channel_tx_creator_stub.async_task().create_icx_tx(kwargs)

        if response_code == message_code.Response.fail_no_permission:
            return await IcxDispatcher.__relay_icx_transaction(
                path, kwargs, relay_target)

        if response_code != message_code.Response.success:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_REQUEST,
                message=message_code.responseCodeMap[response_code][1],
                http_status=message_code.get_response_http_status_code(
                    response_code, status.HTTP_BAD_REQUEST))

        if tx_hash is None:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_REQUEST,
                message='txHash is None',
                http_status=status.HTTP_BAD_REQUEST)

        return convert_params(tx_hash, ResponseParamType.send_tx)
Ejemplo n.º 9
0
    async def icx_getBlockByHeight(**kwargs):
        channel = kwargs['context']['channel']
        request = convert_params(kwargs, ParamType.get_block_by_height_request)
        block_hash, result = await get_block_by_params(block_height=request['height'],
                                                       channel_name=channel)
        response_code = result['response_code']
        if response_code != message_code.Response.success:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_PARAMS,
                message=message_code.responseCodeMap[response_code][1],
                http_status=status.HTTP_BAD_REQUEST
            )

        response = convert_params(result['block'], ParamType.get_block_response)
        return response
Ejemplo n.º 10
0
def response_to_json_query(response, is_convert: bool = False):
    from iconrpcserver.dispatcher import GenericJsonRpcServerError
    if check_error_response(response):
        response = response['error']
        raise GenericJsonRpcServerError(
            code=-response['code'],
            message=response['message'],
            http_status=status.HTTP_BAD_REQUEST
        )
    else:
        if is_convert:
            response = {
                'response': response,
                "response_code": 0
            }

    return response
Ejemplo n.º 11
0
    async def __relay_icx_transaction(url, path, message):
        relay_target = RestProperty().relay_target
        relay_target = relay_target if relay_target is not None else RestProperty().rs_target
        if not relay_target:
            raise GenericJsonRpcServerError(
                code=JsonError.INTERNAL_ERROR,
                message=message_code.responseCodeMap[message_code.Response.fail_invalid_peer_target][1],
                http_status=status.HTTP_INTERNAL_ERROR
            )

        dispatch_protocol = IcxDispatcher.get_dispatch_protocol_from_url(url)
        Logger.debug(f'Dispatch Protocol: {dispatch_protocol}')
        redirect_protocol = StubCollection().conf.get(ConfigKey.REDIRECT_PROTOCOL)
        Logger.debug(f'Redirect Protocol: {redirect_protocol}')
        if redirect_protocol:
            dispatch_protocol = redirect_protocol
        Logger.debug(f'Protocol: {dispatch_protocol}')

        return await relay_tx_request(dispatch_protocol, message, relay_target, path=path[1:])
Ejemplo n.º 12
0
async def get_block_by_params(channel_name=None,
                              block_height=None,
                              block_hash="",
                              with_commit_state=False):
    channel_name = StubCollection().conf[
        ConfigKey.CHANNEL] if channel_name is None else channel_name
    block_data_filter = "prev_block_hash, height, block_hash, merkle_tree_root_hash," \
                        " time_stamp, peer_id, signature"
    tx_data_filter = "icx_origin_data"

    try:
        channel_stub = get_channel_stub_by_channel_name(channel_name)
    except KeyError:
        raise GenericJsonRpcServerError(code=JsonError.INVALID_REQUEST,
                                        message="Invalid channel name",
                                        http_status=status.HTTP_BAD_REQUEST)

    response_code, block_hash, confirm_info, block_data_json, tx_data_json_list = \
        await channel_stub.async_task().get_block(
            block_height=block_height,
            block_hash=block_hash,
            block_data_filter=block_data_filter,
            tx_data_filter=tx_data_filter
        )

    try:
        block = json.loads(
            block_data_json
        ) if response_code == message_code.Response.success else {}
    except Exception as e:
        logging.error(f"get_block_by_params error caused by : {e}")
        block = {}

    result = {
        'response_code': response_code,
        'block': block,
        'confirm_info': confirm_info.decode('utf-8')
    }

    if 'commit_state' in result['block'] and not with_commit_state:
        del result['block']['commit_state']

    return block_hash, result
Ejemplo n.º 13
0
    async def icx_getTransactionByHash(**kwargs):
        channel = kwargs['context']['channel']
        request = convert_params(kwargs, RequestParamType.get_tx_result)
        channel_stub = StubCollection().channel_stubs[channel]

        response_code, tx_info = await channel_stub.async_task().get_tx_info(
            request["txHash"])
        if response_code == message_code.Response.fail_invalid_key_error:
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_PARAMS,
                message='Invalid params txHash',
                http_status=status.HTTP_BAD_REQUEST)

        result = tx_info["transaction"]
        result['txHash'] = request['txHash']
        result["txIndex"] = tx_info["tx_index"]
        result["blockHeight"] = tx_info["block_height"]
        result["blockHash"] = tx_info["block_hash"]

        response = convert_params(result, ResponseParamType.get_tx_by_hash)
        return response
Ejemplo n.º 14
0
    async def icx_getBlockReceipts(context: Dict[str, str], **kwargs):
        channel = context.get('channel')
        request = convert_params(kwargs, RequestParamType.get_block_receipts)
        if all(param in request for param in ["hash", "height"]):
            raise GenericJsonRpcServerError(
                code=JsonError.INVALID_PARAMS,
                message='Invalid params (only one parameter is allowed)',
                http_status=status.HTTP_BAD_REQUEST)
        if 'hash' in request:
            code, block_receipts = await get_block_recipts_by_params(
                block_hash=request['hash'], channel_name=channel)
        elif 'height' in request:
            code, block_receipts = await get_block_recipts_by_params(
                block_height=request['height'], channel_name=channel)
        else:
            code, block_receipts = await get_block_recipts_by_params(
                block_height=-1, channel_name=channel)

        check_response_code(code)
        response = convert_params(block_receipts,
                                  ResponseParamType.get_block_receipts)
        return response_to_json_query(response)
Ejemplo n.º 15
0
def check_response_code(response_code: message_code.Response):
    if response_code != message_code.Response.success:
        raise GenericJsonRpcServerError(
            code=JsonError.INVALID_PARAMS,
            message=message_code.responseCodeMap[response_code][1],
            http_status=status.HTTP_BAD_REQUEST)