Search in sources :

Example 1 with SignedBeaconBlock

use of tech.pegasys.teku.api.schema.SignedBeaconBlock in project teku by ConsenSys.

the class TekuNode method waitForAttestationBeingGossiped.

public void waitForAttestationBeingGossiped(int validatorSeparationIndex, int totalValidatorCount) {
    List<UInt64> node1Validators = IntStream.range(0, validatorSeparationIndex).mapToObj(UInt64::valueOf).collect(toList());
    List<UInt64> node2Validators = IntStream.range(validatorSeparationIndex, totalValidatorCount).mapToObj(UInt64::valueOf).collect(toList());
    waitFor(() -> {
        final Optional<SignedBlock> maybeBlock = fetchHeadBlock();
        final Optional<BeaconState> maybeState = fetchHeadState();
        assertThat(maybeBlock).isPresent();
        assertThat(maybeState).isPresent();
        SignedBeaconBlock block = (SignedBeaconBlock) maybeBlock.get();
        BeaconState state = maybeState.get();
        // Check that the fetched block and state are in sync
        assertThat(state.latest_block_header.parent_root).isEqualTo(block.getMessage().parent_root);
        tech.pegasys.teku.spec.datastructures.state.beaconstate.BeaconState internalBeaconState = state.asInternalBeaconState(spec);
        UInt64 proposerIndex = block.getMessage().proposer_index;
        Set<UInt64> attesterIndicesInAttestations = block.getMessage().getBody().attestations.stream().map(a -> spec.getAttestingIndices(internalBeaconState, a.asInternalAttestation(spec).getData(), a.asInternalAttestation(spec).getAggregationBits())).flatMap(Collection::stream).map(UInt64::valueOf).collect(toSet());
        if (node1Validators.contains(proposerIndex)) {
            assertThat(attesterIndicesInAttestations.stream().anyMatch(node2Validators::contains)).isTrue();
        } else if (node2Validators.contains(proposerIndex)) {
            assertThat(attesterIndicesInAttestations.stream().anyMatch(node1Validators::contains)).isTrue();
        } else {
            throw new IllegalStateException("Proposer index greater than total validator count");
        }
    }, 2, MINUTES);
}
Also used : SignedBeaconBlockAltair(tech.pegasys.teku.api.schema.altair.SignedBeaconBlockAltair) Arrays(java.util.Arrays) SszBitvectorSchema(tech.pegasys.teku.infrastructure.ssz.schema.collections.SszBitvectorSchema) ValidatorKeystores(tech.pegasys.teku.test.acceptance.dsl.tools.deposits.ValidatorKeystores) Assertions.assertThat(org.assertj.core.api.Assertions.assertThat) TimeoutException(java.util.concurrent.TimeoutException) PostValidatorLivenessResponse(tech.pegasys.teku.api.response.v1.validator.PostValidatorLivenessResponse) Network(org.testcontainers.containers.Network) SszBitvector(tech.pegasys.teku.infrastructure.ssz.collections.SszBitvector) GetStateResponseV2(tech.pegasys.teku.api.response.v2.debug.GetStateResponseV2) SpecFactory(tech.pegasys.teku.spec.SpecFactory) Duration(java.time.Duration) Map(java.util.Map) FinalityCheckpointsResponse(tech.pegasys.teku.api.response.v1.beacon.FinalityCheckpointsResponse) KEY_TYPE(io.libp2p.core.crypto.KEY_TYPE) URI(java.net.URI) SignedBlock(tech.pegasys.teku.api.schema.interfaces.SignedBlock) Bytes32(org.apache.tuweni.bytes.Bytes32) Collectors.toSet(java.util.stream.Collectors.toSet) HttpWaitStrategy(org.testcontainers.containers.wait.strategy.HttpWaitStrategy) PrivKey(io.libp2p.core.crypto.PrivKey) EventType(tech.pegasys.teku.api.response.v1.EventType) Predicate(java.util.function.Predicate) Collection(java.util.Collection) Set(java.util.Set) Collectors(java.util.stream.Collectors) List(java.util.List) ValidatorLivenessRequest(tech.pegasys.teku.api.request.v1.validator.ValidatorLivenessRequest) Logger(org.apache.logging.log4j.Logger) SignedBeaconBlock(tech.pegasys.teku.api.schema.SignedBeaconBlock) MountableFile(org.testcontainers.utility.MountableFile) Optional(java.util.Optional) IntStream(java.util.stream.IntStream) IOUtils(org.testcontainers.shaded.org.apache.commons.io.IOUtils) GenesisStateConfig(tech.pegasys.teku.test.acceptance.dsl.tools.GenesisStateConfig) GetGenesisResponse(tech.pegasys.teku.api.response.v1.beacon.GetGenesisResponse) MINUTES(java.util.concurrent.TimeUnit.MINUTES) HashMap(java.util.HashMap) Bytes(org.apache.tuweni.bytes.Bytes) AtomicReference(java.util.concurrent.atomic.AtomicReference) ArrayList(java.util.ArrayList) GetBlockResponseV2(tech.pegasys.teku.api.response.v2.beacon.GetBlockResponseV2) SignedContributionAndProof(tech.pegasys.teku.api.schema.altair.SignedContributionAndProof) PeerId(io.libp2p.core.PeerId) ValidatorLivenessAtEpoch(tech.pegasys.teku.api.response.v1.validator.ValidatorLivenessAtEpoch) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64) KeyKt(io.libp2p.core.crypto.KeyKt) Spec(tech.pegasys.teku.spec.Spec) GetStateFinalityCheckpointsResponse(tech.pegasys.teku.api.response.v1.beacon.GetStateFinalityCheckpointsResponse) GenesisStateGenerator(tech.pegasys.teku.test.acceptance.dsl.tools.GenesisStateGenerator) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) HeadEvent(tech.pegasys.teku.api.response.v1.HeadEvent) FileOutputStream(java.io.FileOutputStream) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) IOException(java.io.IOException) File(java.io.File) BeaconState(tech.pegasys.teku.api.schema.BeaconState) Consumer(java.util.function.Consumer) Collectors.toList(java.util.stream.Collectors.toList) GetBlockRootResponse(tech.pegasys.teku.api.response.v1.beacon.GetBlockRootResponse) Collections(java.util.Collections) LogManager(org.apache.logging.log4j.LogManager) InputStream(java.io.InputStream) SignedBeaconBlock(tech.pegasys.teku.api.schema.SignedBeaconBlock) SignedBlock(tech.pegasys.teku.api.schema.interfaces.SignedBlock) BeaconState(tech.pegasys.teku.api.schema.BeaconState) Collection(java.util.Collection) UInt64(tech.pegasys.teku.infrastructure.unsigned.UInt64)

Example 2 with SignedBeaconBlock

use of tech.pegasys.teku.api.schema.SignedBeaconBlock in project teku by ConsenSys.

the class PostBlock method handle.

@OpenApi(path = ROUTE, method = HttpMethod.POST, summary = "Publish a signed block", tags = { TAG_BEACON, TAG_VALIDATOR_REQUIRED }, requestBody = @OpenApiRequestBody(content = { @OpenApiContent(from = SignedBlock.class) }), description = "Submit a signed beacon block to the beacon node to be imported." + " The beacon node performs the required validation.", responses = { @OpenApiResponse(status = RES_OK, description = "Block has been successfully broadcast, validated and imported."), @OpenApiResponse(status = RES_ACCEPTED, description = "Block has been successfully broadcast, but failed validation and has not been imported."), @OpenApiResponse(status = RES_BAD_REQUEST, description = "Unable to parse request body."), @OpenApiResponse(status = RES_INTERNAL_ERROR, description = "Beacon node experienced an internal error."), @OpenApiResponse(status = RES_SERVICE_UNAVAILABLE, description = "Beacon node is currently syncing.") })
@Override
public void handle(final Context ctx) throws Exception {
    try {
        if (syncDataProvider.isSyncing()) {
            ctx.status(SC_SERVICE_UNAVAILABLE);
            ctx.json(BadRequest.serviceUnavailable(jsonProvider));
            return;
        }
        final SignedBeaconBlock signedBeaconBlock = validatorDataProvider.parseBlock(jsonProvider, ctx.body());
        ctx.future(validatorDataProvider.submitSignedBlock(signedBeaconBlock).thenApplyChecked(validatorBlockResult -> handleResponseContext(ctx, validatorBlockResult)));
    } catch (final JsonProcessingException ex) {
        ctx.status(SC_BAD_REQUEST);
        ctx.json(BadRequest.badRequest(jsonProvider, ex.getMessage()));
    } catch (final Exception ex) {
        LOG.error("Failed to post block due to internal error", ex);
        ctx.status(SC_INTERNAL_SERVER_ERROR);
        ctx.json(BadRequest.internalError(jsonProvider, ex.getMessage()));
    }
}
Also used : SC_INTERNAL_SERVER_ERROR(javax.servlet.http.HttpServletResponse.SC_INTERNAL_SERVER_ERROR) RES_SERVICE_UNAVAILABLE(tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_SERVICE_UNAVAILABLE) TAG_BEACON(tech.pegasys.teku.infrastructure.http.RestApiConstants.TAG_BEACON) OpenApiContent(io.javalin.plugin.openapi.annotations.OpenApiContent) SC_SERVICE_UNAVAILABLE(javax.servlet.http.HttpServletResponse.SC_SERVICE_UNAVAILABLE) ValidatorDataProvider(tech.pegasys.teku.api.ValidatorDataProvider) RES_INTERNAL_ERROR(tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_INTERNAL_ERROR) RES_BAD_REQUEST(tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_BAD_REQUEST) Context(io.javalin.http.Context) OpenApiResponse(io.javalin.plugin.openapi.annotations.OpenApiResponse) JsonProvider(tech.pegasys.teku.provider.JsonProvider) RES_ACCEPTED(tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_ACCEPTED) SignedBlock(tech.pegasys.teku.api.schema.interfaces.SignedBlock) HttpMethod(io.javalin.plugin.openapi.annotations.HttpMethod) SyncDataProvider(tech.pegasys.teku.api.SyncDataProvider) BadRequest(tech.pegasys.teku.beaconrestapi.schema.BadRequest) TAG_VALIDATOR_REQUIRED(tech.pegasys.teku.infrastructure.http.RestApiConstants.TAG_VALIDATOR_REQUIRED) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Handler(io.javalin.http.Handler) Logger(org.apache.logging.log4j.Logger) SignedBeaconBlock(tech.pegasys.teku.api.schema.SignedBeaconBlock) SC_OK(javax.servlet.http.HttpServletResponse.SC_OK) RES_OK(tech.pegasys.teku.infrastructure.http.RestApiConstants.RES_OK) SC_BAD_REQUEST(javax.servlet.http.HttpServletResponse.SC_BAD_REQUEST) OpenApi(io.javalin.plugin.openapi.annotations.OpenApi) OpenApiRequestBody(io.javalin.plugin.openapi.annotations.OpenApiRequestBody) ValidatorBlockResult(tech.pegasys.teku.api.schema.ValidatorBlockResult) SC_ACCEPTED(javax.servlet.http.HttpServletResponse.SC_ACCEPTED) LogManager(org.apache.logging.log4j.LogManager) DataProvider(tech.pegasys.teku.api.DataProvider) SignedBeaconBlock(tech.pegasys.teku.api.schema.SignedBeaconBlock) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) OpenApi(io.javalin.plugin.openapi.annotations.OpenApi)

Example 3 with SignedBeaconBlock

use of tech.pegasys.teku.api.schema.SignedBeaconBlock in project teku by ConsenSys.

the class GetBlockIntegrationTest method shouldGetBlock.

@Test
public void shouldGetBlock() throws IOException {
    startRestAPIAtGenesis();
    final List<SignedBlockAndState> created = createBlocksAtSlots(10);
    final Response response = get("head");
    final GetBlockResponse body = jsonProvider.jsonToObject(response.body().string(), GetBlockResponse.class);
    final SignedBeaconBlock data = body.data;
    final SignedBlockAndState block = created.get(0);
    assertThat(data).isEqualTo(SignedBeaconBlock.create(block.getBlock()));
}
Also used : Response(okhttp3.Response) GetBlockResponse(tech.pegasys.teku.api.response.v1.beacon.GetBlockResponse) GetBlockResponse(tech.pegasys.teku.api.response.v1.beacon.GetBlockResponse) SignedBlockAndState(tech.pegasys.teku.spec.datastructures.blocks.SignedBlockAndState) SignedBeaconBlock(tech.pegasys.teku.api.schema.SignedBeaconBlock) Test(org.junit.jupiter.api.Test) AbstractDataBackedRestAPIIntegrationTest(tech.pegasys.teku.beaconrestapi.AbstractDataBackedRestAPIIntegrationTest)

Example 4 with SignedBeaconBlock

use of tech.pegasys.teku.api.schema.SignedBeaconBlock in project teku by ConsenSys.

the class OkHttpValidatorRestApiClientTest method sendSignedBlock_MakesExpectedRequest.

@Test
public void sendSignedBlock_MakesExpectedRequest() throws Exception {
    final Bytes32 blockRoot = Bytes32.fromHexStringLenient("0x1234");
    final SignedBeaconBlock signedBeaconBlock = schemaObjects.signedBeaconBlock();
    // Block has been successfully broadcast, validated and imported
    mockWebServer.enqueue(new MockResponse().setResponseCode(SC_OK).setBody(asJson(blockRoot)));
    apiClient.sendSignedBlock(signedBeaconBlock);
    RecordedRequest request = mockWebServer.takeRequest();
    assertThat(request.getMethod()).isEqualTo("POST");
    assertThat(request.getPath()).contains(ValidatorApiMethod.SEND_SIGNED_BLOCK.getPath(emptyMap()));
    assertThat(request.getBody().readString(StandardCharsets.UTF_8)).isEqualTo(asJson(signedBeaconBlock));
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) SignedBeaconBlock(tech.pegasys.teku.api.schema.SignedBeaconBlock) Bytes32(org.apache.tuweni.bytes.Bytes32) Test(org.junit.jupiter.api.Test)

Example 5 with SignedBeaconBlock

use of tech.pegasys.teku.api.schema.SignedBeaconBlock in project teku by ConsenSys.

the class OkHttpValidatorRestApiClientTest method sendSignedBlock_WhenServerError_ThrowsRuntimeException.

@Test
public void sendSignedBlock_WhenServerError_ThrowsRuntimeException() {
    final SignedBeaconBlock signedBeaconBlock = schemaObjects.signedBeaconBlock();
    mockWebServer.enqueue(new MockResponse().setResponseCode(SC_INTERNAL_SERVER_ERROR));
    assertThatThrownBy(() -> apiClient.sendSignedBlock(signedBeaconBlock)).isInstanceOf(RuntimeException.class).hasMessageContaining("Unexpected response from Beacon Node API");
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) SignedBeaconBlock(tech.pegasys.teku.api.schema.SignedBeaconBlock) Test(org.junit.jupiter.api.Test)

Aggregations

SignedBeaconBlock (tech.pegasys.teku.api.schema.SignedBeaconBlock)9 Test (org.junit.jupiter.api.Test)6 MockResponse (okhttp3.mockwebserver.MockResponse)5 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)2 LogManager (org.apache.logging.log4j.LogManager)2 Logger (org.apache.logging.log4j.Logger)2 Bytes32 (org.apache.tuweni.bytes.Bytes32)2 SignedBlock (tech.pegasys.teku.api.schema.interfaces.SignedBlock)2 JsonNode (com.fasterxml.jackson.databind.JsonNode)1 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 Context (io.javalin.http.Context)1 Handler (io.javalin.http.Handler)1 HttpMethod (io.javalin.plugin.openapi.annotations.HttpMethod)1 OpenApi (io.javalin.plugin.openapi.annotations.OpenApi)1 OpenApiContent (io.javalin.plugin.openapi.annotations.OpenApiContent)1 OpenApiRequestBody (io.javalin.plugin.openapi.annotations.OpenApiRequestBody)1 OpenApiResponse (io.javalin.plugin.openapi.annotations.OpenApiResponse)1 PeerId (io.libp2p.core.PeerId)1 KEY_TYPE (io.libp2p.core.crypto.KEY_TYPE)1 KeyKt (io.libp2p.core.crypto.KeyKt)1