Search in sources :

Example 1 with INVALID_REQUEST

use of org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST in project besu by hyperledger.

the class JsonRpcHttpService method handleJsonBatchRequest.

@SuppressWarnings("rawtypes")
private void handleJsonBatchRequest(final RoutingContext routingContext, final JsonArray jsonArray, final Optional<User> user) {
    // Interpret json as rpc request
    final List<Future> responses = jsonArray.stream().map(obj -> {
        if (!(obj instanceof JsonObject)) {
            return Future.succeededFuture(errorResponse(null, INVALID_REQUEST));
        }
        final JsonObject req = (JsonObject) obj;
        return vertx.executeBlocking(future -> future.complete(process(routingContext, req, user)));
    }).collect(toList());
    CompositeFuture.all(responses).onComplete((res) -> {
        final HttpServerResponse response = routingContext.response();
        if (response.closed() || response.headWritten()) {
            return;
        }
        if (res.failed()) {
            response.setStatusCode(HttpResponseStatus.BAD_REQUEST.code()).end();
            return;
        }
        final JsonRpcResponse[] completed = res.result().list().stream().map(JsonRpcResponse.class::cast).filter(this::isNonEmptyResponses).toArray(JsonRpcResponse[]::new);
        try {
            // underlying output stream lifecycle is managed by the json object writer
            JSON_OBJECT_WRITER.writeValue(new JsonResponseStreamer(response, routingContext.request().remoteAddress()), completed);
        } catch (IOException ex) {
            LOG.error("Error streaming JSON-RPC response", ex);
        }
    });
}
Also used : VertxException(io.vertx.core.VertxException) TlsConfiguration(org.hyperledger.besu.ethereum.api.tls.TlsConfiguration) StatusCode(io.opentelemetry.api.trace.StatusCode) DecodeException(io.vertx.core.json.DecodeException) AuthenticationService(org.hyperledger.besu.ethereum.api.jsonrpc.authentication.AuthenticationService) TlsClientAuthConfiguration(org.hyperledger.besu.ethereum.api.tls.TlsClientAuthConfiguration) HttpServer(io.vertx.core.http.HttpServer) JsonRpcRequest(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest) JsonRpcNoResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcNoResponse) NetworkProtocol(org.hyperledger.besu.nat.core.domain.NetworkProtocol) LoggerFactory(org.slf4j.LoggerFactory) Router(io.vertx.ext.web.Router) RoutingContext(io.vertx.ext.web.RoutingContext) JsonRpcRequestId(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestId) ExceptionUtils(org.hyperledger.besu.util.ExceptionUtils) BodyHandler(io.vertx.ext.web.handler.BodyHandler) HandlerFactory(org.hyperledger.besu.ethereum.api.handlers.HandlerFactory) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) B3Propagator(io.opentelemetry.extension.trace.propagation.B3Propagator) JsonObject(io.vertx.core.json.JsonObject) JaegerPropagator(io.opentelemetry.extension.trace.propagation.JaegerPropagator) NetworkUtility(org.hyperledger.besu.util.NetworkUtility) Path(java.nio.file.Path) Splitter(com.google.common.base.Splitter) Context(io.opentelemetry.context.Context) Span(io.opentelemetry.api.trace.Span) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) BesuMetricCategory(org.hyperledger.besu.metrics.BesuMetricCategory) NatServiceType(org.hyperledger.besu.nat.core.domain.NatServiceType) HttpHeaders(io.vertx.core.http.HttpHeaders) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse) InetSocketAddress(java.net.InetSocketAddress) SpanKind(io.opentelemetry.api.trace.SpanKind) Future(io.vertx.core.Future) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) List(java.util.List) User(io.vertx.ext.auth.User) HttpServerResponse(io.vertx.core.http.HttpServerResponse) TextMapGetter(io.opentelemetry.context.propagation.TextMapGetter) UpnpNatManager(org.hyperledger.besu.nat.upnp.UpnpNatManager) Optional(java.util.Optional) MetricsSystem(org.hyperledger.besu.plugin.services.MetricsSystem) JsonRpcUnauthorizedResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcUnauthorizedResponse) Iterables(com.google.common.collect.Iterables) HttpServerRequest(io.vertx.core.http.HttpServerRequest) Json(io.vertx.core.json.Json) JsonRpcError(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError) VertxTrustOptions.allowlistClients(org.apache.tuweni.net.tls.VertxTrustOptions.allowlistClients) W3CBaggagePropagator(io.opentelemetry.api.baggage.propagation.W3CBaggagePropagator) CompletableFuture(java.util.concurrent.CompletableFuture) JsonRpcResponseType(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponseType) Tracer(io.opentelemetry.api.trace.Tracer) PfxOptions(io.vertx.core.net.PfxOptions) TextMapPropagator(io.opentelemetry.context.propagation.TextMapPropagator) CompositeFuture(io.vertx.core.CompositeFuture) HealthService(org.hyperledger.besu.ethereum.api.jsonrpc.health.HealthService) AuthenticationUtils(org.hyperledger.besu.ethereum.api.jsonrpc.authentication.AuthenticationUtils) JsonRpcRequestContext(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext) HttpConnection(io.vertx.core.http.HttpConnection) TimeoutOptions(org.hyperledger.besu.ethereum.api.handlers.TimeoutOptions) DefaultAuthenticationService(org.hyperledger.besu.ethereum.api.jsonrpc.authentication.DefaultAuthenticationService) Nullable(javax.annotation.Nullable) OperationTimer(org.hyperledger.besu.plugin.services.metrics.OperationTimer) SocketAddress(io.vertx.core.net.SocketAddress) MultiTenancyValidationException(org.hyperledger.besu.ethereum.privacy.MultiTenancyValidationException) Logger(org.slf4j.Logger) INVALID_REQUEST(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) NatMethod(org.hyperledger.besu.nat.NatMethod) IOException(java.io.IOException) InvalidJsonRpcParameters(org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters) ContextKey(org.hyperledger.besu.ethereum.api.jsonrpc.context.ContextKey) LabelledMetric(org.hyperledger.besu.plugin.services.metrics.LabelledMetric) GlobalOpenTelemetry(io.opentelemetry.api.GlobalOpenTelemetry) Streams.stream(com.google.common.collect.Streams.stream) JsonArray(io.vertx.core.json.JsonArray) Collectors.toList(java.util.stream.Collectors.toList) Feature(com.fasterxml.jackson.core.JsonGenerator.Feature) HttpMethod(io.vertx.core.http.HttpMethod) StringJoiner(java.util.StringJoiner) ClientAuth(io.vertx.core.http.ClientAuth) HttpServerOptions(io.vertx.core.http.HttpServerOptions) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Handler(io.vertx.core.Handler) CorsHandler(io.vertx.ext.web.handler.CorsHandler) JsonRpcMethod(org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod) NatService(org.hyperledger.besu.nat.NatService) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Future(io.vertx.core.Future) CompletableFuture(java.util.concurrent.CompletableFuture) CompositeFuture(io.vertx.core.CompositeFuture) JsonObject(io.vertx.core.json.JsonObject) IOException(java.io.IOException)

Example 2 with INVALID_REQUEST

use of org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST in project besu by hyperledger.

the class WebSocketMessageHandler method handle.

public void handle(final ServerWebSocket websocket, final Buffer buffer, final Optional<User> user) {
    if (buffer.length() == 0) {
        replyToClient(websocket, errorResponse(null, JsonRpcError.INVALID_REQUEST));
    } else {
        try {
            final JsonObject jsonRpcRequest = buffer.toJsonObject();
            vertx.<JsonRpcResponse>executeBlocking(promise -> {
                try {
                    final JsonRpcResponse jsonRpcResponse = jsonRpcExecutor.execute(user, null, null, new IsAliveHandler(ethScheduler, timeoutSec), jsonRpcRequest, req -> {
                        final WebSocketRpcRequest websocketRequest = req.mapTo(WebSocketRpcRequest.class);
                        websocketRequest.setConnectionId(websocket.textHandlerID());
                        return websocketRequest;
                    });
                    promise.complete(jsonRpcResponse);
                } catch (RuntimeException e) {
                    promise.fail(e);
                }
            }).onSuccess(jsonRpcResponse -> replyToClient(websocket, jsonRpcResponse)).onFailure(throwable -> {
                try {
                    final Integer id = jsonRpcRequest.getInteger("id", null);
                    replyToClient(websocket, errorResponse(id, JsonRpcError.INTERNAL_ERROR));
                } catch (ClassCastException idNotIntegerException) {
                    replyToClient(websocket, errorResponse(null, JsonRpcError.INTERNAL_ERROR));
                }
            });
        } catch (DecodeException jsonObjectDecodeException) {
            try {
                final JsonArray batchJsonRpcRequest = buffer.toJsonArray();
                vertx.<List<JsonRpcResponse>>executeBlocking(promise -> {
                    List<JsonRpcResponse> responses = new ArrayList<>();
                    for (int i = 0; i < batchJsonRpcRequest.size(); i++) {
                        final JsonObject jsonRequest;
                        try {
                            jsonRequest = batchJsonRpcRequest.getJsonObject(i);
                        } catch (ClassCastException e) {
                            responses.add(new JsonRpcErrorResponse(null, INVALID_REQUEST));
                            continue;
                        }
                        responses.add(jsonRpcExecutor.execute(user, null, null, new IsAliveHandler(ethScheduler, timeoutSec), jsonRequest, req -> {
                            final WebSocketRpcRequest websocketRequest = req.mapTo(WebSocketRpcRequest.class);
                            websocketRequest.setConnectionId(websocket.textHandlerID());
                            return websocketRequest;
                        }));
                    }
                    promise.complete(responses);
                }).onSuccess(jsonRpcBatchResponse -> {
                    final JsonRpcResponse[] completed = jsonRpcBatchResponse.stream().filter(jsonRpcResponse -> jsonRpcResponse.getType() != JsonRpcResponseType.NONE).toArray(JsonRpcResponse[]::new);
                    replyToClient(websocket, completed);
                }).onFailure(throwable -> replyToClient(websocket, errorResponse(null, JsonRpcError.INTERNAL_ERROR)));
            } catch (RuntimeException jsonArrayDecodeException) {
                replyToClient(websocket, errorResponse(null, JsonRpcError.INTERNAL_ERROR));
            }
        }
    }
}
Also used : JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) ServerWebSocket(io.vertx.core.http.ServerWebSocket) JsonRpcError(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError) DecodeException(io.vertx.core.json.DecodeException) LoggerFactory(org.slf4j.LoggerFactory) IsAliveHandler(org.hyperledger.besu.ethereum.api.handlers.IsAliveHandler) JsonRpcResponseType(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponseType) ArrayList(java.util.ArrayList) EthScheduler(org.hyperledger.besu.ethereum.eth.manager.EthScheduler) JsonObject(io.vertx.core.json.JsonObject) WebSocketRpcRequest(org.hyperledger.besu.ethereum.api.jsonrpc.websocket.methods.WebSocketRpcRequest) Logger(org.slf4j.Logger) INVALID_REQUEST(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) Feature(com.fasterxml.jackson.core.JsonGenerator.Feature) User(io.vertx.ext.auth.User) Buffer(io.vertx.core.buffer.Buffer) Optional(java.util.Optional) JsonRpcExecutor(org.hyperledger.besu.ethereum.api.jsonrpc.execution.JsonRpcExecutor) JsonObject(io.vertx.core.json.JsonObject) WebSocketRpcRequest(org.hyperledger.besu.ethereum.api.jsonrpc.websocket.methods.WebSocketRpcRequest) DecodeException(io.vertx.core.json.DecodeException) JsonArray(io.vertx.core.json.JsonArray) IsAliveHandler(org.hyperledger.besu.ethereum.api.handlers.IsAliveHandler) ArrayList(java.util.ArrayList) List(java.util.List) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)

Example 3 with INVALID_REQUEST

use of org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST in project besu by hyperledger.

the class JsonRpcIpcService method start.

public Future<NetServer> start() {
    netServer = vertx.createNetServer(buildNetServerOptions());
    netServer.connectHandler(socket -> {
        AtomicBoolean closedSocket = new AtomicBoolean(false);
        socket.closeHandler(unused -> closedSocket.set(true)).handler(buffer -> {
            if (buffer.length() == 0) {
                errorReturn(socket, null, JsonRpcError.INVALID_REQUEST);
            } else {
                try {
                    final JsonObject jsonRpcRequest = buffer.toJsonObject();
                    vertx.<JsonRpcResponse>executeBlocking(promise -> {
                        final JsonRpcResponse jsonRpcResponse = jsonRpcExecutor.execute(Optional.empty(), null, null, closedSocket::get, jsonRpcRequest, req -> req.mapTo(JsonRpcRequest.class));
                        promise.complete(jsonRpcResponse);
                    }).onSuccess(jsonRpcResponse -> {
                        try {
                            socket.write(JSON_OBJECT_WRITER.writeValueAsString(jsonRpcResponse) + '\n');
                        } catch (JsonProcessingException e) {
                            LOG.error("Error streaming JSON-RPC response", e);
                        }
                    }).onFailure(throwable -> {
                        try {
                            final Integer id = jsonRpcRequest.getInteger("id", null);
                            errorReturn(socket, id, JsonRpcError.INTERNAL_ERROR);
                        } catch (ClassCastException idNotIntegerException) {
                            errorReturn(socket, null, JsonRpcError.INTERNAL_ERROR);
                        }
                    });
                } catch (DecodeException jsonObjectDecodeException) {
                    try {
                        final JsonArray batchJsonRpcRequest = buffer.toJsonArray();
                        if (batchJsonRpcRequest.isEmpty()) {
                            errorReturn(socket, null, JsonRpcError.INVALID_REQUEST);
                        } else {
                            vertx.<List<JsonRpcResponse>>executeBlocking(promise -> {
                                List<JsonRpcResponse> responses = new ArrayList<>();
                                for (int i = 0; i < batchJsonRpcRequest.size(); i++) {
                                    final JsonObject jsonRequest;
                                    try {
                                        jsonRequest = batchJsonRpcRequest.getJsonObject(i);
                                    } catch (ClassCastException e) {
                                        responses.add(new JsonRpcErrorResponse(null, INVALID_REQUEST));
                                        continue;
                                    }
                                    responses.add(jsonRpcExecutor.execute(Optional.empty(), null, null, closedSocket::get, jsonRequest, req -> req.mapTo(JsonRpcRequest.class)));
                                }
                                promise.complete(responses);
                            }).onSuccess(jsonRpcBatchResponse -> {
                                try {
                                    final JsonRpcResponse[] completed = jsonRpcBatchResponse.stream().filter(jsonRpcResponse -> jsonRpcResponse.getType() != JsonRpcResponseType.NONE).toArray(JsonRpcResponse[]::new);
                                    socket.write(JSON_OBJECT_WRITER.writeValueAsString(completed) + '\n');
                                } catch (JsonProcessingException e) {
                                    LOG.error("Error streaming JSON-RPC response", e);
                                }
                            }).onFailure(throwable -> errorReturn(socket, null, JsonRpcError.INTERNAL_ERROR));
                        }
                    } catch (DecodeException jsonArrayDecodeException) {
                        errorReturn(socket, null, JsonRpcError.PARSE_ERROR);
                    }
                }
            }
        });
    });
    return netServer.listen(SocketAddress.domainSocketAddress(path.toString())).onSuccess(successServer -> LOG.info("IPC endpoint opened: {}", path)).onFailure(throwable -> LOG.error("Unable to open IPC endpoint", throwable));
}
Also used : Json(io.vertx.core.json.Json) JsonRpcError(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError) DecodeException(io.vertx.core.json.DecodeException) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) JsonRpcRequest(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) JsonRpcResponseType(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponseType) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) Path(java.nio.file.Path) SocketAddress(io.vertx.core.net.SocketAddress) Logger(org.slf4j.Logger) INVALID_REQUEST(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST) Files(java.nio.file.Files) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse) Future(io.vertx.core.Future) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) NetServerOptions(io.vertx.core.net.NetServerOptions) Buffer(io.vertx.core.buffer.Buffer) NetServer(io.vertx.core.net.NetServer) Optional(java.util.Optional) JsonRpcExecutor(org.hyperledger.besu.ethereum.api.jsonrpc.execution.JsonRpcExecutor) NetSocket(io.vertx.core.net.NetSocket) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) JsonRpcRequest(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest) JsonObject(io.vertx.core.json.JsonObject) DecodeException(io.vertx.core.json.DecodeException) JsonArray(io.vertx.core.json.JsonArray) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) List(java.util.List) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)

Example 4 with INVALID_REQUEST

use of org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST in project besu by hyperledger.

the class JsonRpcExecutorHandler method handler.

public static Handler<RoutingContext> handler(final JsonRpcExecutor jsonRpcExecutor, final Tracer tracer) {
    return ctx -> {
        HttpServerResponse response = ctx.response();
        try {
            Optional<User> user = ContextKey.AUTHENTICATED_USER.extractFrom(ctx, Optional::empty);
            Context spanContext = ctx.get(SPAN_CONTEXT);
            response = response.putHeader("Content-Type", APPLICATION_JSON);
            if (ctx.data().containsKey(ContextKey.REQUEST_BODY_AS_JSON_OBJECT.name())) {
                JsonObject jsonRequest = ctx.get(ContextKey.REQUEST_BODY_AS_JSON_OBJECT.name());
                JsonRpcResponse jsonRpcResponse = jsonRpcExecutor.execute(user, tracer, spanContext, () -> !ctx.response().closed(), jsonRequest, req -> req.mapTo(JsonRpcRequest.class));
                response.setStatusCode(status(jsonRpcResponse).code());
                if (jsonRpcResponse.getType() == JsonRpcResponseType.NONE) {
                    response.end();
                } else {
                    try (final JsonResponseStreamer streamer = new JsonResponseStreamer(response, ctx.request().remoteAddress())) {
                        // underlying output stream lifecycle is managed by the json object writer
                        JSON_OBJECT_WRITER.writeValue(streamer, jsonRpcResponse);
                    }
                }
            } else if (ctx.data().containsKey(ContextKey.REQUEST_BODY_AS_JSON_ARRAY.name())) {
                JsonArray batchJsonRequest = ctx.get(ContextKey.REQUEST_BODY_AS_JSON_ARRAY.name());
                List<JsonRpcResponse> jsonRpcBatchResponse;
                try {
                    List<JsonRpcResponse> responses = new ArrayList<>();
                    for (int i = 0; i < batchJsonRequest.size(); i++) {
                        final JsonObject jsonRequest;
                        try {
                            jsonRequest = batchJsonRequest.getJsonObject(i);
                        } catch (ClassCastException e) {
                            responses.add(new JsonRpcErrorResponse(null, INVALID_REQUEST));
                            continue;
                        }
                        responses.add(jsonRpcExecutor.execute(user, tracer, spanContext, () -> !ctx.response().closed(), jsonRequest, req -> req.mapTo(JsonRpcRequest.class)));
                    }
                    jsonRpcBatchResponse = responses;
                } catch (RuntimeException e) {
                    response.setStatusCode(HttpResponseStatus.BAD_REQUEST.code()).end();
                    return;
                }
                final JsonRpcResponse[] completed = jsonRpcBatchResponse.stream().filter(jsonRpcResponse -> jsonRpcResponse.getType() != JsonRpcResponseType.NONE).toArray(JsonRpcResponse[]::new);
                try (final JsonResponseStreamer streamer = new JsonResponseStreamer(response, ctx.request().remoteAddress())) {
                    // underlying output stream lifecycle is managed by the json object writer
                    JSON_OBJECT_WRITER.writeValue(streamer, completed);
                }
            } else {
                handleJsonRpcError(ctx, null, JsonRpcError.PARSE_ERROR);
            }
        } catch (IOException ex) {
            LOG.error("Error streaming JSON-RPC response", ex);
        } catch (RuntimeException e) {
            handleJsonRpcError(ctx, null, JsonRpcError.INTERNAL_ERROR);
        }
    };
}
Also used : Json(io.vertx.core.json.Json) JsonRpcError(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) JsonRpcRequest(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest) LoggerFactory(org.slf4j.LoggerFactory) RoutingContext(io.vertx.ext.web.RoutingContext) JsonRpcResponseType(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponseType) Tracer(io.opentelemetry.api.trace.Tracer) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) JsonResponseStreamer(org.hyperledger.besu.ethereum.api.jsonrpc.JsonResponseStreamer) Context(io.opentelemetry.context.Context) Logger(org.slf4j.Logger) INVALID_REQUEST(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) IOException(java.io.IOException) HttpResponseStatus(io.netty.handler.codec.http.HttpResponseStatus) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse) ContextKey(org.hyperledger.besu.ethereum.api.jsonrpc.context.ContextKey) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) JsonArray(io.vertx.core.json.JsonArray) List(java.util.List) User(io.vertx.ext.auth.User) HttpServerResponse(io.vertx.core.http.HttpServerResponse) Optional(java.util.Optional) Handler(io.vertx.core.Handler) JsonRpcExecutor(org.hyperledger.besu.ethereum.api.jsonrpc.execution.JsonRpcExecutor) RoutingContext(io.vertx.ext.web.RoutingContext) Context(io.opentelemetry.context.Context) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) Optional(java.util.Optional) JsonResponseStreamer(org.hyperledger.besu.ethereum.api.jsonrpc.JsonResponseStreamer) ArrayList(java.util.ArrayList) JsonObject(io.vertx.core.json.JsonObject) IOException(java.io.IOException) JsonArray(io.vertx.core.json.JsonArray) HttpServerResponse(io.vertx.core.http.HttpServerResponse) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)

Example 5 with INVALID_REQUEST

use of org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST in project besu by hyperledger.

the class WebSocketRequestHandler method executeHandler.

private Handler<Promise<Object>> executeHandler(final Optional<AuthenticationService> authenticationService, final ServerWebSocket websocket, final String payload, final Optional<User> user, final Collection<String> noAuthApiMethods) {
    return future -> {
        final String json = payload.trim();
        if (!json.isEmpty() && json.charAt(0) == '{') {
            try {
                handleSingleRequest(authenticationService, websocket, user, future, getRequest(payload), noAuthApiMethods);
            } catch (final IllegalArgumentException | DecodeException e) {
                LOG.debug("Error mapping json to WebSocketRpcRequest", e);
                future.complete(new JsonRpcErrorResponse(null, JsonRpcError.INVALID_REQUEST));
                return;
            }
        } else if (json.length() == 0) {
            future.complete(errorResponse(null, INVALID_REQUEST));
            return;
        } else {
            final JsonArray jsonArray = new JsonArray(json);
            if (jsonArray.size() < 1) {
                future.complete(errorResponse(null, INVALID_REQUEST));
                return;
            }
            // handle batch request
            LOG.debug("batch request size {}", jsonArray.size());
            handleJsonBatchRequest(authenticationService, websocket, jsonArray, user, noAuthApiMethods);
        }
    };
}
Also used : JsonRpcUnauthorizedResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcUnauthorizedResponse) ServerWebSocket(io.vertx.core.http.ServerWebSocket) Json(io.vertx.core.json.Json) JsonRpcError(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError) DecodeException(io.vertx.core.json.DecodeException) AuthenticationService(org.hyperledger.besu.ethereum.api.jsonrpc.authentication.AuthenticationService) LoggerFactory(org.slf4j.LoggerFactory) IsAliveHandler(org.hyperledger.besu.ethereum.api.handlers.IsAliveHandler) JsonRpcResponseType(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponseType) CompositeFuture(io.vertx.core.CompositeFuture) EthScheduler(org.hyperledger.besu.ethereum.eth.manager.EthScheduler) Map(java.util.Map) RpcMethodTimeoutException(org.hyperledger.besu.ethereum.api.handlers.RpcMethodTimeoutException) JsonRpcRequestContext(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext) JsonObject(io.vertx.core.json.JsonObject) AsyncResult(io.vertx.core.AsyncResult) WebSocketRpcRequest(org.hyperledger.besu.ethereum.api.jsonrpc.websocket.methods.WebSocketRpcRequest) Logger(org.slf4j.Logger) INVALID_REQUEST(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST) ObjectWriter(com.fasterxml.jackson.databind.ObjectWriter) JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) Collection(java.util.Collection) Promise(io.vertx.core.Promise) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) Vertx(io.vertx.core.Vertx) IOException(java.io.IOException) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse) InvalidJsonRpcParameters(org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters) Future(io.vertx.core.Future) Jdk8Module(com.fasterxml.jackson.datatype.jdk8.Jdk8Module) JsonArray(io.vertx.core.json.JsonArray) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) Feature(com.fasterxml.jackson.core.JsonGenerator.Feature) User(io.vertx.ext.auth.User) Optional(java.util.Optional) Handler(io.vertx.core.Handler) Collections(java.util.Collections) JsonRpcMethod(org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod) JsonArray(io.vertx.core.json.JsonArray) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)

Aggregations

ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)5 ObjectWriter (com.fasterxml.jackson.databind.ObjectWriter)5 Jdk8Module (com.fasterxml.jackson.datatype.jdk8.Jdk8Module)5 JsonArray (io.vertx.core.json.JsonArray)5 JsonObject (io.vertx.core.json.JsonObject)5 IOException (java.io.IOException)5 List (java.util.List)5 Optional (java.util.Optional)5 JsonRpcError (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError)5 INVALID_REQUEST (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError.INVALID_REQUEST)5 JsonRpcErrorResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)5 JsonRpcResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse)5 JsonRpcResponseType (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponseType)5 Logger (org.slf4j.Logger)5 LoggerFactory (org.slf4j.LoggerFactory)5 Vertx (io.vertx.core.Vertx)4 DecodeException (io.vertx.core.json.DecodeException)4 Json (io.vertx.core.json.Json)4 User (io.vertx.ext.auth.User)4 Feature (com.fasterxml.jackson.core.JsonGenerator.Feature)3