Skip to content

Commit

Permalink
Merge remote-tracking branch 'upstream/master' into post-state-valida…
Browse files Browse the repository at this point in the history
…tor-balances

# Conflicts:
#	CHANGELOG.md
#	data/beaconrestapi/src/main/java/tech/pegasys/teku/beaconrestapi/JsonTypeDefinitionBeaconRestApi.java
  • Loading branch information
courtneyeh committed Nov 20, 2023
2 parents 42462f7 + d695ed4 commit b7cf60c
Show file tree
Hide file tree
Showing 10 changed files with 533 additions and 36 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ 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.
- Added POST `/eth/v1/beacon/states/{state_id}/validator_balances` 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 @@ -67,6 +67,7 @@
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.PostStateValidatorBalances;
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 @@ -218,6 +219,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 PostStateValidatorBalances(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());
}
}
}
Loading

0 comments on commit b7cf60c

Please sign in to comment.