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

Added GetPendingDeposits #9110

Merged
merged 7 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
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 @@ -17,5 +17,6 @@
- Deprecated beacon-api `/eth/v1/config/deposit_contract` - will be removed after electra, in the fulu timeframe.
- Deprecated beacon-api `/teku/v1/beacon/pool/deposits` - will be removed after electra, in the fulu timeframe.
- Deprecated beacon-api `/eth/v1/builder/states/{state_id}/expected_withdrawals` - will be removed after electra, in the fulu timeframe.
- Added beacon-api `/eth/v1/beacon/states/{state_id}/pending_deposits` endpoint for use post-electra.

### Bug Fixes
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
/*
* Copyright Consensys Software Inc., 2025
*
* 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.v1.beacon;

import static org.assertj.core.api.Assertions.assertThat;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.HEADER_CONSENSUS_VERSION;

import com.fasterxml.jackson.databind.JsonNode;
import java.io.IOException;
import java.util.List;
import okhttp3.Response;
import org.junit.jupiter.api.Test;
import tech.pegasys.teku.api.schema.Version;
import tech.pegasys.teku.beaconrestapi.AbstractDataBackedRestAPIIntegrationTest;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStatePendingDeposits;
import tech.pegasys.teku.infrastructure.json.JsonTestUtil;
import tech.pegasys.teku.spec.SpecMilestone;
import tech.pegasys.teku.spec.datastructures.blocks.SignedBlockAndState;

public class GetPendingDepositsIntegrationTest extends AbstractDataBackedRestAPIIntegrationTest {
@Test
public void shouldGetElectraDepositsJson() throws Exception {
startRestAPIAtGenesis(SpecMilestone.ELECTRA);
final List<SignedBlockAndState> created = createBlocksAtSlots(10);
final Response response = get("head");

final String responseText = response.body().string();
final JsonNode node = JsonTestUtil.parseAsJsonNode(responseText);
assertThat(node.get("version").asText()).isEqualTo("electra");
assertThat(node.get("execution_optimistic").asBoolean()).isFalse();
assertThat(node.get("finalized").asBoolean()).isFalse();
assertThat(node.get("data").size()).isEqualTo(2);
assertThat(node.get("data").get(0).get("slot").asInt()).isEqualTo(10);
assertThat(node.get("data").get(0).get("pubkey").asText())
.isEqualTo(
"0x903e979f8c9074fcfb34eb5c7c2574fe6a87c76e528ebc6019bc063e0640ae6dc66581d08c48ff8fe22e2cc1ca2075cd");
assertThat(node.get("data").get(1).get("slot").asInt()).isEqualTo(10);
assertThat(node.get("data").get(0).get("pubkey").asText())
.isEqualTo(
"0xb8313bd8b0064c24bbb6a9db2462a2a13b7c0dafa0aaf940adad9ad81eda2b094bec0e05cab6ddafe0490b4b14a53a8a");
assertThat(response.header(HEADER_CONSENSUS_VERSION)).isEqualTo(Version.electra.name());
}

public Response get(final String stateId) throws IOException {
return getResponse(GetStatePendingDeposits.ROUTE.replace("{state_id}", stateId));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStateCommittees;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStateFinalityCheckpoints;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStateFork;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStatePendingDeposits;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStateRandao;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStateRoot;
import tech.pegasys.teku.beaconrestapi.handlers.v1.beacon.GetStateSyncCommittees;
Expand Down Expand Up @@ -251,6 +252,7 @@ private static RestApi create(
.endpoint(new PostVoluntaryExit(dataProvider))
.endpoint(new PostSyncCommittees(dataProvider))
.endpoint(new PostValidatorLiveness(dataProvider))
.endpoint(new GetStatePendingDeposits(dataProvider, schemaCache))
.endpoint(new GetDepositSnapshot(eth1DataProvider))
// Event Handler
.endpoint(
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
/*
* Copyright Consensys Software Inc., 2025
*
* 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.ethereum.json.types.EthereumTypes.MILESTONE_TYPE;
import static tech.pegasys.teku.ethereum.json.types.EthereumTypes.sszResponseType;
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;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.HEADER_CONSENSUS_VERSION;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.TAG_BEACON;
import static tech.pegasys.teku.infrastructure.http.RestApiConstants.TAG_EXPERIMENTAL;
import static tech.pegasys.teku.infrastructure.json.types.CoreTypes.BOOLEAN_TYPE;
import static tech.pegasys.teku.infrastructure.json.types.SerializableTypeDefinition.listOf;

import com.fasterxml.jackson.core.JsonProcessingException;
import java.util.List;
import java.util.Optional;
import tech.pegasys.teku.api.ChainDataProvider;
import tech.pegasys.teku.api.DataProvider;
import tech.pegasys.teku.api.schema.Version;
import tech.pegasys.teku.infrastructure.async.SafeFuture;
import tech.pegasys.teku.infrastructure.json.types.SerializableTypeDefinition;
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.SpecMilestone;
import tech.pegasys.teku.spec.datastructures.metadata.ObjectAndMetaData;
import tech.pegasys.teku.spec.datastructures.state.versions.electra.PendingDeposit;
import tech.pegasys.teku.spec.schemas.SchemaDefinitionCache;

public class GetStatePendingDeposits extends RestApiEndpoint {
public static final String ROUTE = "/eth/v1/beacon/states/{state_id}/pending_deposits";

private final ChainDataProvider chainDataProvider;

public GetStatePendingDeposits(
final DataProvider dataProvider, final SchemaDefinitionCache schemaDefinitionCache) {
this(dataProvider.getChainDataProvider(), schemaDefinitionCache);
}

GetStatePendingDeposits(
final ChainDataProvider provider, final SchemaDefinitionCache schemaDefinitionCache) {
super(
EndpointMetadata.get(ROUTE)
.operationId("getPendingDeposits")
.summary("Get pending deposits from state")
.description(
"Returns pending deposits for state with given 'stateId'. Should return 400 if requested before electra.")
.pathParam(PARAMETER_STATE_ID)
.tags(TAG_BEACON, TAG_EXPERIMENTAL)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Experimental?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

i can remove it but its not currently approved is all

.response(
SC_OK,
"Request successful",
getResponseType(schemaDefinitionCache),
sszResponseType())
.withNotFoundResponse()
.withUnsupportedMediaTypeResponse()
.withChainDataResponses()
.build());
this.chainDataProvider = provider;
}

@Override
public void handleRequest(final RestApiRequest request) throws JsonProcessingException {

SafeFuture<Optional<ObjectAndMetaData<List<PendingDeposit>>>> future =
chainDataProvider.getStatePendingDeposits(request.getPathParameter(PARAMETER_STATE_ID));

request.respondAsync(
future.thenApply(
maybeData ->
maybeData
.map(
objectAndMetadata -> {
request.header(
HEADER_CONSENSUS_VERSION,
Version.fromMilestone(objectAndMetadata.getMilestone()).name());
return AsyncApiResponse.respondOk(objectAndMetadata);
})
.orElseGet(AsyncApiResponse::respondNotFound)));
}

private static SerializableTypeDefinition<ObjectAndMetaData<List<PendingDeposit>>>
getResponseType(final SchemaDefinitionCache schemaDefinitionCache) {

final SerializableTypeDefinition<PendingDeposit> pendingDepositType =
schemaDefinitionCache
.getSchemaDefinition(SpecMilestone.ELECTRA)
.toVersionElectra()
.orElseThrow()
.getPendingDepositSchema()
.getJsonTypeDefinition();

return SerializableTypeDefinition.<ObjectAndMetaData<List<PendingDeposit>>>object()
.name("GetPendingDepositsResponse")
.withField("version", MILESTONE_TYPE, ObjectAndMetaData::getMilestone)
.withField(EXECUTION_OPTIMISTIC, BOOLEAN_TYPE, ObjectAndMetaData::isExecutionOptimistic)
.withField(FINALIZED, BOOLEAN_TYPE, ObjectAndMetaData::isFinalized)
.withField("data", listOf(pendingDepositType), ObjectAndMetaData::getData)
.build();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
/*
* Copyright Consensys Software Inc., 2025
*
* 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 org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_BAD_REQUEST;
import static tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_INTERNAL_SERVER_ERROR;
import static tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_NOT_FOUND;
import static tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_OK;
import static tech.pegasys.teku.infrastructure.http.HttpStatusCodes.SC_UNSUPPORTED_MEDIA_TYPE;
import static tech.pegasys.teku.infrastructure.restapi.MetadataTestUtil.getResponseStringFromMetadata;
import static tech.pegasys.teku.infrastructure.restapi.MetadataTestUtil.verifyMetadataErrorResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import java.io.IOException;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import tech.pegasys.teku.beaconrestapi.AbstractMigratedBeaconHandlerWithChainDataProviderTest;
import tech.pegasys.teku.spec.SpecMilestone;
import tech.pegasys.teku.spec.datastructures.metadata.ObjectAndMetaData;
import tech.pegasys.teku.spec.datastructures.state.versions.electra.PendingDeposit;

public class GetStatePendingDepositsTest
extends AbstractMigratedBeaconHandlerWithChainDataProviderTest {

@BeforeEach
public void setup() {

final GetStatePendingDeposits pendingDepositsHandler =
new GetStatePendingDeposits(chainDataProvider, schemaDefinitionCache);
initialise(SpecMilestone.ELECTRA);
genesis();
setHandler(pendingDepositsHandler);
request.setPathParameter("state_id", "head");
}

@Test
void metadata_shouldHandle400() throws JsonProcessingException {
verifyMetadataErrorResponse(handler, SC_BAD_REQUEST);
}

@Test
void metadata_shouldHandle404() throws JsonProcessingException {
verifyMetadataErrorResponse(handler, SC_NOT_FOUND);
}

@Test
void metadata_shouldHandle415() throws JsonProcessingException {
verifyMetadataErrorResponse(handler, SC_UNSUPPORTED_MEDIA_TYPE);
}

@Test
void metadata_shouldHandle500() throws JsonProcessingException {
verifyMetadataErrorResponse(handler, SC_INTERNAL_SERVER_ERROR);
}

@Test
void metadata_shouldHandle200() throws IOException {
final PendingDeposit deposit = dataStructureUtil.randomPendingDeposit();
final ObjectAndMetaData<List<PendingDeposit>> responseData =
new ObjectAndMetaData<>(List.of(deposit), SpecMilestone.ELECTRA, false, true, false);
final String data = getResponseStringFromMetadata(handler, SC_OK, responseData);
String expected =
String.format(
"{\"version\":\"electra\",\"execution_optimistic\":false,\"finalized\":false,"
+ "\"data\":[{\"pubkey\":\"%s\",\"withdrawal_credentials\":\"%s\",\"amount\":\"%s\",\"signature\":\"%s\",\"slot\":\"%s\"}]}",
deposit.getPublicKey(),
deposit.getWithdrawalCredentials(),
deposit.getAmount(),
deposit.getSignature(),
deposit.getSlot());
assertThat(data).isEqualTo(expected);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,7 @@
import tech.pegasys.teku.spec.datastructures.state.CommitteeAssignment;
import tech.pegasys.teku.spec.datastructures.state.SyncCommittee;
import tech.pegasys.teku.spec.datastructures.state.beaconstate.BeaconState;
import tech.pegasys.teku.spec.datastructures.state.versions.electra.PendingDeposit;
import tech.pegasys.teku.spec.logic.common.statetransition.epoch.status.ValidatorStatuses;
import tech.pegasys.teku.spec.logic.common.statetransition.exceptions.EpochProcessingException;
import tech.pegasys.teku.spec.logic.common.statetransition.exceptions.SlotProcessingException;
Expand Down Expand Up @@ -746,4 +747,42 @@ public SafeFuture<Optional<UInt64>> getFinalizedStateSlot(final UInt64 beforeSlo
.getLatestAvailableFinalizedState(beforeSlot)
.thenApply(maybeState -> maybeState.map(BeaconState::getSlot));
}

public SafeFuture<Optional<ObjectAndMetaData<List<PendingDeposit>>>> getStatePendingDeposits(
final String stateIdParam) {
return stateSelectorFactory
.createSelectorForStateId(stateIdParam)
.getState()
.thenApply(this::getPendingDeposits);
}

private Optional<ObjectAndMetaData<List<PendingDeposit>>> getPendingDeposits(
final Optional<StateAndMetaData> maybeStateAndMetadata) {
if (maybeStateAndMetadata.isPresent()) {
if (!maybeStateAndMetadata
.get()
.getMilestone()
.isGreaterThanOrEqualTo(SpecMilestone.ELECTRA)) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NIT: I think we need a isLessThan() method for our Milestone check... This would read much better as isLessThan(SpecMilestone.ELECTRA) (and without negating the whole expression).

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thats what i looked for first, i guess i could change it

throw new BadRequestException(
"The state was successfully retrieved, but was prior to electra and does not contain pending deposits.");
}
return maybeStateAndMetadata.map(
stateAndMetaData -> {
final List<PendingDeposit> deposits =
stateAndMetaData
.getData()
.toVersionElectra()
.orElseThrow()
.getPendingDeposits()
.asList();
return new ObjectAndMetaData<>(
deposits,
stateAndMetaData.getMilestone(),
stateAndMetaData.isExecutionOptimistic(),
stateAndMetaData.isCanonical(),
stateAndMetaData.isFinalized());
});
}
return Optional.empty();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -776,6 +776,11 @@ public EndpointMetaDataBuilder withInternalErrorResponse() {
return this;
}

public EndpointMetaDataBuilder withUnsupportedMediaTypeResponse() {
response(SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported media type", HTTP_ERROR_RESPONSE_TYPE);
return this;
}

public EndpointMetaDataBuilder withNotImplementedResponse() {
response(SC_NOT_IMPLEMENTED, "Not implemented", HTTP_ERROR_RESPONSE_TYPE);
return this;
Expand Down