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

[Merge] implements /eth/v1/validator/prepare_beacon_proposer Validator api #4642

Merged
merged 7 commits into from
Nov 16, 2021
Merged
Show file tree
Hide file tree
Changes from 4 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
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@
import tech.pegasys.teku.sync.events.SyncStateProvider;
import tech.pegasys.teku.validator.api.AttesterDuties;
import tech.pegasys.teku.validator.api.AttesterDuty;
import tech.pegasys.teku.validator.api.BeaconPreparableProposer;
import tech.pegasys.teku.validator.api.CommitteeSubscriptionRequest;
import tech.pegasys.teku.validator.api.NodeSyncingException;
import tech.pegasys.teku.validator.api.ProposerDuties;
Expand Down Expand Up @@ -590,6 +591,10 @@ public SafeFuture<Void> sendSignedContributionAndProofs(
});
}

@Override
public void prepareBeaconProposer(
Collection<BeaconPreparableProposer> beaconPreparableProposers) {}

private Optional<SubmitDataError> fromInternalValidationResult(
final InternalValidationResult internalValidationResult, final int resultIndex) {
if (!internalValidationResult.isReject()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"post" : {
"tags" : [ "Validator", "Validator Required Api" ],
"summary" : "Provide beacon node with proposals for the given validators.",
"description" : "Prepares the beacon node for potential proposers by supplying information required when proposing blocks for the given validators. The information supplied for each validator index is considered persistent until overwritten by new information for the given validator index, or until the beacon node restarts.\n\nNote that because the information is not persistent across beacon node restarts it is recommended that either the beacon node is monitored for restarts or this information is refreshed by resending this request periodically (for example, each epoch).\n\nAlso note that requests containing currently inactive or unknown validator indices will be accepted, as they may become active at a later epoch.",
"operationId" : "postEthV1ValidatorPrepare_beacon_proposer",
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"type" : "array",
"items" : {
"$ref" : "#/components/schemas/BeaconPreparableProposer"
}
}
}
}
},
"responses" : {
"200" : {
"description" : "Preparation information has been received."
},
"400" : {
"description" : "Invalid parameter supplied."
},
"500" : {
"description" : "Beacon node internal error."
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"type" : "object",
"properties" : {
"validator_index" : {
"type" : "string",
"format" : "uint64",
"example" : "1"
},
"fee_recipient" : {
"pattern" : "^0x[a-fA-F0-9]{40}$",
"type" : "string",
"description" : "Bytes20 hexadecimal",
"format" : "byte"
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@
import tech.pegasys.teku.beaconrestapi.handlers.v1.validator.PostAggregateAndProofs;
import tech.pegasys.teku.beaconrestapi.handlers.v1.validator.PostAttesterDuties;
import tech.pegasys.teku.beaconrestapi.handlers.v1.validator.PostContributionAndProofs;
import tech.pegasys.teku.beaconrestapi.handlers.v1.validator.PostPrepareBeaconProposer;
import tech.pegasys.teku.beaconrestapi.handlers.v1.validator.PostSubscribeToBeaconCommitteeSubnet;
import tech.pegasys.teku.beaconrestapi.handlers.v1.validator.PostSyncCommitteeSubscriptions;
import tech.pegasys.teku.beaconrestapi.handlers.v1.validator.PostSyncDuties;
Expand Down Expand Up @@ -346,6 +347,8 @@ private void addValidatorHandlers(final DataProvider dataProvider) {
new PostSyncCommitteeSubscriptions(dataProvider, jsonProvider));
app.post(
PostContributionAndProofs.ROUTE, new PostContributionAndProofs(dataProvider, jsonProvider));
app.post(
PostPrepareBeaconProposer.ROUTE, new PostPrepareBeaconProposer(dataProvider, jsonProvider));
}

private void addBeaconHandlers(final DataProvider dataProvider) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
/*
* Copyright 2021 ConsenSys AG.
*
* 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.validator;

import static javax.servlet.http.HttpServletResponse.SC_OK;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_BAD_REQUEST;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_INTERNAL_ERROR;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_OK;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.TAG_VALIDATOR;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.TAG_VALIDATOR_REQUIRED;

import io.javalin.http.Context;
import io.javalin.http.Handler;
import io.javalin.plugin.openapi.annotations.HttpMethod;
import io.javalin.plugin.openapi.annotations.OpenApi;
import io.javalin.plugin.openapi.annotations.OpenApiContent;
import io.javalin.plugin.openapi.annotations.OpenApiRequestBody;
import io.javalin.plugin.openapi.annotations.OpenApiResponse;
import java.util.Arrays;
import java.util.stream.Collectors;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jetbrains.annotations.NotNull;
import tech.pegasys.teku.api.DataProvider;
import tech.pegasys.teku.api.ValidatorDataProvider;
import tech.pegasys.teku.api.schema.merge.BeaconPreparableProposer;
import tech.pegasys.teku.beaconrestapi.handlers.AbstractHandler;
import tech.pegasys.teku.beaconrestapi.schema.BadRequest;
import tech.pegasys.teku.infrastructure.http.HttpStatusCodes;
import tech.pegasys.teku.provider.JsonProvider;

public class PostPrepareBeaconProposer extends AbstractHandler implements Handler {
public static final String ROUTE = "/eth/v1/validator/prepare_beacon_proposer";
private static final Logger LOG = LogManager.getLogger();

public PostPrepareBeaconProposer(final DataProvider provider, final JsonProvider jsonProvider) {
this(provider.getValidatorDataProvider(), jsonProvider);
}

public PostPrepareBeaconProposer(
final ValidatorDataProvider provider, final JsonProvider jsonProvider) {
super(jsonProvider);
}

@OpenApi(
path = ROUTE,
method = HttpMethod.POST,
summary = "Provide beacon node with proposals for the given validators.",
tags = {TAG_VALIDATOR, TAG_VALIDATOR_REQUIRED},
requestBody =
@OpenApiRequestBody(content = {@OpenApiContent(from = BeaconPreparableProposer[].class)}),
description =
"Prepares the beacon node for potential proposers by supplying information required when proposing blocks for the given validators. The information supplied for each validator index is considered persistent until overwritten by new information for the given validator index, or until the beacon node restarts.\n\n"
+ "Note that because the information is not persistent across beacon node restarts it is recommended that either the beacon node is monitored for restarts or this information is refreshed by resending this request periodically (for example, each epoch).\n\n"
+ "Also note that requests containing currently inactive or unknown validator indices will be accepted, as they may become active at a later epoch.",
responses = {
@OpenApiResponse(
status = RES_OK,
description = "Preparation information has been received."),
@OpenApiResponse(status = RES_BAD_REQUEST, description = "Invalid parameter supplied."),
@OpenApiResponse(status = RES_INTERNAL_ERROR, description = "Beacon node internal error.")
})
@Override
public void handle(@NotNull final Context ctx) throws Exception {
try {
final BeaconPreparableProposer[] request =
parseRequestBody(ctx.body(), BeaconPreparableProposer[].class);

LOG.trace(
"received: {}",
Arrays.stream(request)
.map(BeaconPreparableProposer::toString)
.collect(Collectors.joining(",")));
tbenr marked this conversation as resolved.
Show resolved Hide resolved

ctx.status(SC_OK);
} catch (final IllegalArgumentException e) {
ctx.json(BadRequest.badRequest(jsonProvider, e.getMessage()));
ctx.status(HttpStatusCodes.SC_BAD_REQUEST);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
/*
* Copyright 2020 ConsenSys AG.
*
* 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.validator;

import static javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST;
import static javax.servlet.http.HttpServletResponse.SC_OK;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import io.javalin.http.Context;
import java.util.List;
import org.junit.jupiter.api.Test;
import tech.pegasys.teku.api.ValidatorDataProvider;
import tech.pegasys.teku.api.schema.merge.BeaconPreparableProposer;
import tech.pegasys.teku.infrastructure.unsigned.UInt64;
import tech.pegasys.teku.provider.JsonProvider;
import tech.pegasys.teku.ssz.type.Bytes20;

class PostPrepareBeaconProposerTest {

private final Context context = mock(Context.class);
private final ValidatorDataProvider provider = mock(ValidatorDataProvider.class);
private final JsonProvider jsonProvider = new JsonProvider();

private final PostPrepareBeaconProposer handler =
new PostPrepareBeaconProposer(provider, jsonProvider);

@Test
public void shouldReturnBadRequestWhenRequestBodyIsInvalid() throws Exception {
when(context.body()).thenReturn("{\"foo\": \"bar\"}");

handler.handle(context);
verify(context).status(SC_BAD_REQUEST);
}

@SuppressWarnings("unchecked")
@Test
public void shouldReturnSuccessWhenPostingValidData() throws Exception {
final BeaconPreparableProposer proposer1 =
new BeaconPreparableProposer(UInt64.valueOf(1), Bytes20.ZERO);
final BeaconPreparableProposer proposer2 =
new BeaconPreparableProposer(
UInt64.valueOf(10),
Bytes20.fromHexString("0x1aD91ee08f21bE3dE0BA2ba6918E714dA6B45836"));

final String requestJson = jsonProvider.objectToJSON(List.of(proposer1, proposer2));
when(context.body()).thenReturn(requestJson);

handler.handle(context);

verify(context).status(SC_OK);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
/*
* Copyright 2021 ConsenSys AG.
*
* 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.api.schema.merge;

import static tech.pegasys.teku.api.schema.SchemaConstants.DESCRIPTION_BYTES20;
import static tech.pegasys.teku.api.schema.SchemaConstants.EXAMPLE_UINT64;
import static tech.pegasys.teku.api.schema.SchemaConstants.PATTERN_BYTES20;

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.base.MoreObjects;
import io.swagger.v3.oas.annotations.media.Schema;
import tech.pegasys.teku.infrastructure.unsigned.UInt64;
import tech.pegasys.teku.ssz.type.Bytes20;

public class BeaconPreparableProposer {
@JsonProperty("validator_index")
@Schema(type = "string", format = "uint64", example = EXAMPLE_UINT64)
public final UInt64 validator_index;

@JsonProperty("fee_recipient")
@Schema(
type = "string",
format = "byte",
pattern = PATTERN_BYTES20,
description = DESCRIPTION_BYTES20)
public final Bytes20 fee_recipient;

@JsonCreator
public BeaconPreparableProposer(
@JsonProperty("validator_index") UInt64 validator_index,
@JsonProperty("fee_recipient") Bytes20 fee_recipient) {
this.validator_index = validator_index;
this.fee_recipient = fee_recipient;
}

@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("validator_index", validator_index)
.add("fee_recipient", fee_recipient)
.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright 2021 ConsenSys AG.
*
* 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.validator.api;

import com.google.common.base.MoreObjects;
import java.util.Objects;
import tech.pegasys.teku.infrastructure.unsigned.UInt64;
import tech.pegasys.teku.ssz.type.Bytes20;

public class BeaconPreparableProposer {
private final UInt64 validatorIndex;
private final Bytes20 feeRecipient;

public BeaconPreparableProposer(UInt64 validatorIndex, Bytes20 feeRecipient) {
this.validatorIndex = validatorIndex;
this.feeRecipient = feeRecipient;
}

public UInt64 getValidatorIndex() {
return validatorIndex;
}

public Bytes20 getFeeRecipient() {
return feeRecipient;
}

@Override
public boolean equals(final Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final BeaconPreparableProposer that = (BeaconPreparableProposer) o;
return Objects.equals(validatorIndex, that.validatorIndex)
&& Objects.equals(feeRecipient, that.feeRecipient);
}

@Override
public int hashCode() {
return Objects.hash(validatorIndex, feeRecipient);
}

@Override
public String toString() {
return MoreObjects.toStringHelper(this)
.add("validatorIndex", validatorIndex)
.add("feeRecipient", feeRecipient)
.toString();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,6 @@ SafeFuture<List<SubmitDataError>> sendSyncCommitteeMessages(

SafeFuture<Void> sendSignedContributionAndProofs(
Collection<SignedContributionAndProof> signedContributionAndProofs);

void prepareBeaconProposer(Collection<BeaconPreparableProposer> beaconPreparableProposers);
}
Loading