Search in sources :

Example 1 with JsonRpcResponse

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

the class PrivGetEeaTransactionCountTest method validRequestProducesExpectedNonce.

@Test
public void validRequestProducesExpectedNonce() {
    final long reportedNonce = 8L;
    final PrivGetEeaTransactionCount method = new PrivGetEeaTransactionCount(privacyController, privacyIdProvider);
    when(privacyController.determineNonce(any(), any(), eq(ENCLAVE_PUBLIC_KEY))).thenReturn(reportedNonce);
    final JsonRpcResponse response = method.response(request);
    assertThat(response).isInstanceOf(JsonRpcSuccessResponse.class);
    final JsonRpcSuccessResponse successResponse = (JsonRpcSuccessResponse) response;
    final int returnedValue = Integer.decode((String) successResponse.getResult());
    assertThat(returnedValue).isEqualTo(reportedNonce);
}
Also used : JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) JsonRpcSuccessResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse) Test(org.junit.Test)

Example 2 with JsonRpcResponse

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

the class JsonRpcHttpService method handleJsonSingleRequest.

private void handleJsonSingleRequest(final RoutingContext routingContext, final JsonObject request, final Optional<User> user) {
    final HttpServerResponse response = routingContext.response();
    vertx.executeBlocking(future -> {
        final JsonRpcResponse jsonRpcResponse = process(routingContext, request, user);
        future.complete(jsonRpcResponse);
    }, false, (res) -> {
        if (!response.closed() && !response.headWritten()) {
            if (res.failed()) {
                response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code()).end();
                return;
            }
            final JsonRpcResponse jsonRpcResponse = (JsonRpcResponse) res.result();
            response.setStatusCode(status(jsonRpcResponse).code()).putHeader("Content-Type", APPLICATION_JSON);
            if (jsonRpcResponse.getType() == JsonRpcResponseType.NONE) {
                response.end(EMPTY_RESPONSE);
            } else {
                try {
                    // underlying output stream lifecycle is managed by the json object writer
                    JSON_OBJECT_WRITER.writeValue(new JsonResponseStreamer(response, routingContext.request().remoteAddress()), jsonRpcResponse);
                } catch (IOException ex) {
                    LOG.error("Error streaming JSON-RPC response", ex);
                }
            }
        }
    });
}
Also used : JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) HttpServerResponse(io.vertx.core.http.HttpServerResponse) IOException(java.io.IOException)

Example 3 with JsonRpcResponse

use of org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse 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 4 with JsonRpcResponse

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

the class QbftDiscardValidatorVoteTest method methodNotEnabledWhenNoVoteProvider.

@Test
public void methodNotEnabledWhenNoVoteProvider() {
    final JsonRpcRequestContext request = requestWithParams(Address.fromHexString("1"));
    final JsonRpcResponse expectedResponse = new JsonRpcErrorResponse(request.getRequest().getId(), JsonRpcError.METHOD_NOT_ENABLED);
    when(validatorProvider.getVoteProviderAtHead()).thenReturn(Optional.empty());
    final JsonRpcResponse response = method.response(request);
    assertThat(response).usingRecursiveComparison().isEqualTo(expectedResponse);
}
Also used : JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) JsonRpcRequestContext(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext) JsonRpcErrorResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse) Test(org.junit.Test)

Example 5 with JsonRpcResponse

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

the class QbftDiscardValidatorVoteTest method discardValidator.

@Test
public void discardValidator() {
    final Address parameterAddress = Address.fromHexString("1");
    final JsonRpcRequestContext request = requestWithParams(parameterAddress);
    final JsonRpcResponse expectedResponse = new JsonRpcSuccessResponse(request.getRequest().getId(), true);
    final JsonRpcResponse response = method.response(request);
    assertThat(response).usingRecursiveComparison().isEqualTo(expectedResponse);
    verify(voteProvider).discardVote(parameterAddress);
}
Also used : JsonRpcResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse) Address(org.hyperledger.besu.datatypes.Address) JsonRpcRequestContext(org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext) JsonRpcSuccessResponse(org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse) Test(org.junit.Test)

Aggregations

JsonRpcResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse)358 JsonRpcRequestContext (org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext)276 Test (org.junit.Test)263 JsonRpcSuccessResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse)185 JsonRpcErrorResponse (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse)164 JsonRpcRequest (org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest)75 Test (org.junit.jupiter.api.Test)67 JsonCallParameter (org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonCallParameter)30 ArrayList (java.util.ArrayList)27 Address (org.hyperledger.besu.datatypes.Address)24 NodesAllowlistResult (org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController.NodesAllowlistResult)22 Optional (java.util.Optional)15 JsonRpcError (org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError)15 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)13 Logger (org.slf4j.Logger)13 List (java.util.List)12 RpcMethod (org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod)12 Hash (org.hyperledger.besu.datatypes.Hash)11 HashMap (java.util.HashMap)10 LogsResult (org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.LogsResult)10