Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add POST state validators endpoint #7706

Merged
merged 19 commits into from
Nov 20, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,5 +15,6 @@ the [releases page](https://github.com/Consensys/teku/releases).
### Additions and Improvements
- Support to new Beacon APIs `publishBlindedBlockV2` and `publishBlockV2` which introduce broadcast validation parameter.
- Added configuration attributes in support of honest validator late block reorg, which adds `REORG_HEAD_WEIGHT_THRESHOLD`, `REORG_PARENT_WEIGHT_THRESHOLD`, and `REORG_MAX_EPOCHS_SINCE_FINALIZATION` to phase 0 configurations. Mainnet values have been added as defaults for configurations that have not explicitly listed them.
- Added POST `/eth/v1/beacon/states/{state_id}/validators` beacon API.

### Bug Fixes
Original file line number Diff line number Diff line change
Expand Up @@ -80,5 +80,72 @@
}
}
}
},
"post" : {
"tags" : [ "Beacon" ],
"operationId" : "postStateValidators",
"summary" : "Get validators from state",
"description" : "Returns filterable list of validators with their balance, status and index.",
"parameters" : [ {
"name" : "state_id",
"required" : true,
"in" : "path",
"schema" : {
"type" : "string",
"description" : "State identifier. Can be one of: \"head\" (canonical head in node's view), \"genesis\", \"finalized\", \"justified\", <slot>, <hex encoded stateRoot with 0x prefix>.",
"example" : "head"
}
} ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"$ref" : "#/components/schemas/PostStateValidatorsRequestBody"
}
}
}
},
"responses" : {
"200" : {
"description" : "Request successful",
"content" : {
"application/json" : {
"schema" : {
"$ref" : "#/components/schemas/GetStateValidatorsResponse"
}
}
}
},
"404" : {
"description" : "Not found",
"content" : {
"application/json" : {
"schema" : {
"$ref" : "#/components/schemas/HttpErrorResponse"
}
}
}
},
"400" : {
"description" : "The request could not be processed, check the response for more information.",
"content" : {
"application/json" : {
"schema" : {
"$ref" : "#/components/schemas/HttpErrorResponse"
}
}
}
},
"500" : {
"description" : "Internal server error",
"content" : {
"application/json" : {
"schema" : {
"$ref" : "#/components/schemas/HttpErrorResponse"
}
}
}
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"title" : "PostStateValidatorsRequestBody",
"type" : "object",
"required" : [ ],
"properties" : {
"ids" : {
"type" : "array",
"items" : {
"type" : "string"
}
},
"statuses" : {
"type" : "array",
"items" : {
"type" : "string"
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@
import java.util.Locale;
import java.util.function.Function;
import org.apache.tuweni.bytes.Bytes32;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStateValidators.StatusParameter;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.StatusParameter;
import tech.pegasys.teku.bls.BLSSignature;
import tech.pegasys.teku.infrastructure.http.RestApiConstants;
import tech.pegasys.teku.infrastructure.json.types.CoreTypes;
Expand All @@ -76,8 +76,8 @@
public class BeaconRestApiTypes {
private static final StringValueTypeDefinition<StatusParameter> STATUS_VALUE =
DeserializableTypeDefinition.string(StatusParameter.class)
.formatter(StatusParameter::toString)
.parser(StatusParameter::valueOf)
.formatter(StatusParameter::getValue)
.parser(StatusParameter::parse)
.example("active_ongoing")
.description("ValidatorStatus string")
.format("string")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.PostBlindedBlock;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.PostBlock;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.PostProposerSlashing;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.PostStateValidators;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.PostSyncCommittees;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.PostVoluntaryExit;
import tech.pegasys.teku.beaconrestapi.handlers.v1.config.GetDepositContract;
Expand Down Expand Up @@ -217,6 +218,7 @@ private static RestApi create(
.endpoint(new GetStateFork(dataProvider))
.endpoint(new GetStateFinalityCheckpoints(dataProvider))
.endpoint(new GetStateValidators(dataProvider))
.endpoint(new PostStateValidators(dataProvider))
.endpoint(new GetStateValidator(dataProvider))
.endpoint(new GetStateValidatorBalances(dataProvider))
.endpoint(new GetStateCommittees(dataProvider))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import static tech.pegasys.teku.beaconrestapi.BeaconRestApiTypes.PARAMETER_STATE_ID;
import static tech.pegasys.teku.beaconrestapi.BeaconRestApiTypes.STATUS_PARAMETER;
import static tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStateValidator.STATE_VALIDATOR_DATA_TYPE;
import static tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.StatusParameter.getApplicableValidatorStatuses;
import static tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_OK;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.EXECUTION_OPTIMISTIC;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.FINALIZED;
Expand All @@ -25,11 +26,9 @@
import static tech.pegasys.teku.infrastructure.json.types.SerializableTypeDefinition.listOf;

import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import tech.pegasys.teku.api.ChainDataProvider;
import tech.pegasys.teku.api.DataProvider;
import tech.pegasys.teku.api.migrated.StateValidatorData;
Expand All @@ -45,7 +44,7 @@
public class GetStateValidators extends RestApiEndpoint {
public static final String ROUTE = "/eth/v1/beacon/states/{state_id}/validators";

private static final SerializableTypeDefinition<ObjectAndMetaData<List<StateValidatorData>>>
static final SerializableTypeDefinition<ObjectAndMetaData<List<StateValidatorData>>>
RESPONSE_TYPE =
SerializableTypeDefinition.<ObjectAndMetaData<List<StateValidatorData>>>object()
.name("GetStateValidatorsResponse")
Expand Down Expand Up @@ -96,32 +95,4 @@ public void handleRequest(RestApiRequest request) throws JsonProcessingException
.map(AsyncApiResponse::respondOk)
.orElseGet(AsyncApiResponse::respondNotFound)));
}

private Set<ValidatorStatus> getApplicableValidatorStatuses(
final List<StatusParameter> statusParameters) {
return statusParameters.stream()
.flatMap(
statusParameter ->
Arrays.stream(ValidatorStatus.values())
.filter(
validatorStatus -> validatorStatus.name().contains(statusParameter.name())))
.collect(Collectors.toSet());
}

@SuppressWarnings("JavaCase")
public enum StatusParameter {
pending_initialized,
pending_queued,
active_ongoing,
active_exiting,
active_slashed,
exited_unslashed,
exited_slashed,
withdrawal_possible,
withdrawal_done,
active,
pending,
exited,
withdrawal;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
/*
* Copyright Consensys Software Inc., 2022
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/

package tech.pegasys.teku.beaconrestapi.handlers.v1.beacon;

import static tech.pegasys.teku.beaconrestapi.BeaconRestApiTypes.PARAMETER_STATE_ID;
import static tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.StatusParameter.getApplicableValidatorStatuses;
import static tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_OK;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.TAG_BEACON;
import static tech.pegasys.teku.infrastructure.json.types.CoreTypes.STRING_TYPE;

import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import tech.pegasys.teku.api.ChainDataProvider;
import tech.pegasys.teku.api.DataProvider;
import tech.pegasys.teku.api.migrated.StateValidatorData;
import tech.pegasys.teku.api.response.v1.beacon.ValidatorStatus;
import tech.pegasys.teku.infrastructure.async.SafeFuture;
import tech.pegasys.teku.infrastructure.json.types.DeserializableTypeDefinition;
import tech.pegasys.teku.infrastructure.restapi.endpoints.AsyncApiResponse;
import tech.pegasys.teku.infrastructure.restapi.endpoints.EndpointMetadata;
import tech.pegasys.teku.infrastructure.restapi.endpoints.RestApiEndpoint;
import tech.pegasys.teku.infrastructure.restapi.endpoints.RestApiRequest;
import tech.pegasys.teku.spec.datastructures.metadata.ObjectAndMetaData;

public class PostStateValidators extends RestApiEndpoint {
private static final DeserializableTypeDefinition<RequestBody> REQUEST_TYPE =
DeserializableTypeDefinition.object(RequestBody.class)
.name("PostStateValidatorsRequestBody")
.initializer(RequestBody::new)
.withOptionalField(
"ids",
DeserializableTypeDefinition.listOf(STRING_TYPE),
RequestBody::getMaybeIds,
RequestBody::setIds)
.withOptionalField(
"statuses",
DeserializableTypeDefinition.listOf(STRING_TYPE),
RequestBody::getMaybeStringStatuses,
RequestBody::setStatuses)
.build();

private final ChainDataProvider chainDataProvider;

public PostStateValidators(final DataProvider dataProvider) {
this(dataProvider.getChainDataProvider());
}

PostStateValidators(final ChainDataProvider provider) {
super(
EndpointMetadata.post(GetStateValidators.ROUTE)
.operationId("postStateValidators")
.summary("Get validators from state")
.description(
"Returns filterable list of validators with their balance, status and index.")
.pathParam(PARAMETER_STATE_ID)
.requestBodyType(REQUEST_TYPE)
.tags(TAG_BEACON)
.response(SC_OK, "Request successful", GetStateValidators.RESPONSE_TYPE)
.withNotFoundResponse()
.build());
this.chainDataProvider = provider;
}

@Override
public void handleRequest(RestApiRequest request) throws JsonProcessingException {
final Optional<RequestBody> requestBody = request.getOptionalRequestBody();
final List<String> validators = requestBody.map(RequestBody::getIds).orElse(List.of());
final List<StatusParameter> statusParameters =
requestBody.map(RequestBody::getStatuses).orElse(List.of());

final Set<ValidatorStatus> statusFilter = getApplicableValidatorStatuses(statusParameters);

SafeFuture<Optional<ObjectAndMetaData<List<StateValidatorData>>>> future =
chainDataProvider.getStateValidators(
request.getPathParameter(PARAMETER_STATE_ID), validators, statusFilter);

request.respondAsync(
future.thenApply(
maybeData ->
maybeData
.map(AsyncApiResponse::respondOk)
.orElseGet(AsyncApiResponse::respondNotFound)));
}

static class RequestBody {
private List<String> ids = List.of();
private List<StatusParameter> statuses = List.of();

RequestBody() {}

public RequestBody(final List<String> ids, final List<StatusParameter> statuses) {
this.ids = ids;
this.statuses = statuses;
}

public List<String> getIds() {
return ids;
}

public Optional<List<String>> getMaybeIds() {
return ids.isEmpty() ? Optional.empty() : Optional.of(ids);
}

public void setIds(final Optional<List<String>> ids) {
ids.ifPresent(i -> this.ids = i);
}

public List<StatusParameter> getStatuses() {
return statuses;
}

public Optional<List<String>> getMaybeStringStatuses() {
return statuses.isEmpty()
? Optional.empty()
: Optional.of(statuses.stream().map(Enum::name).toList());
}

public void setStatuses(final Optional<List<String>> statuses) {
statuses.ifPresent(s -> this.statuses = s.stream().map(StatusParameter::parse).toList());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright Consensys Software Inc., 2023
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*/

package tech.pegasys.teku.beaconrestapi.handlers.v1.beacon;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;
import tech.pegasys.teku.api.response.v1.beacon.ValidatorStatus;

public enum StatusParameter {
PENDING_INITIALIZED("pending_initialized"),
PENDING_QUEUED("pending_queued"),
ACTIVE_ONGOING("active_ongoing"),
ACTIVE_EXITING("active_exiting"),
ACTIVE_SLASHED("active_slashed"),
EXITED_UNSLASHED("exited_unslashed"),
EXITED_SLASHED("exited_slashed"),
WITHDRAWAL_POSSIBLE("withdrawal_possible"),
WITHDRAWAL_DONE("withdrawal_done"),
ACTIVE("active"),
PENDING("pending"),
EXITED("exited"),
WITHDRAWAL("withdrawal");

private final String value;

StatusParameter(final String value) {
this.value = value;
}

public String getValue() {
return value;
}

public static StatusParameter parse(final String value) {
return StatusParameter.valueOf(value.toUpperCase(Locale.ROOT));
}

public static Set<ValidatorStatus> getApplicableValidatorStatuses(
final List<StatusParameter> statusParameters) {
return statusParameters.stream()
.flatMap(
statusParameter ->
Arrays.stream(ValidatorStatus.values())
.filter(
validatorStatus ->
validatorStatus.name().contains(statusParameter.getValue())))
.collect(Collectors.toSet());
}
}
Loading
Loading