Search in sources :

Example 81 with EncodedPayload

use of com.quorum.tessera.enclave.EncodedPayload in project tessera by ConsenSys.

the class EncryptedTransactionMigrator method migrate.

public void migrate() {
    final long secondaryTxCount = secondaryEntityManager.createQuery("select count(e) from EncryptedTransaction e", Long.class).getSingleResult();
    final int batchCount = calculateBatchCount(maxBatchSize, secondaryTxCount);
    IntStream.range(0, batchCount).map(i -> i * maxBatchSize).mapToObj(offset -> secondaryEntityManager.createNamedQuery("EncryptedTransaction.FindAll", EncryptedTransaction.class).setFirstResult(offset).setMaxResults(maxBatchSize)).flatMap(TypedQuery::getResultStream).forEach(et -> {
        final Optional<EncryptedTransaction> existing = primaryEntityManager.createNamedQuery("EncryptedTransaction.FindByHash", EncryptedTransaction.class).setParameter("hash", et.getHash().getHashBytes()).getResultStream().findAny();
        if (existing.isEmpty()) {
            primaryEntityManager.getTransaction().begin();
            primaryEntityManager.persist(et);
            primaryEntityManager.getTransaction().commit();
            return;
        }
        final EncryptedTransaction outerTx = existing.get();
        final EncodedPayload primaryTx = outerTx.getPayload();
        final EncodedPayload secondaryTx = et.getPayload();
        final EncodedPayload updatedPayload = this.handleSingleTransaction(primaryTx, secondaryTx);
        outerTx.setPayload(updatedPayload);
        primaryEntityManager.getTransaction().begin();
        primaryEntityManager.merge(outerTx);
        primaryEntityManager.getTransaction().commit();
    });
}
Also used : IntStream(java.util.stream.IntStream) SecurityHash(com.quorum.tessera.enclave.SecurityHash) PublicKey(com.quorum.tessera.encryption.PublicKey) java.util(java.util) EncodedPayload(com.quorum.tessera.enclave.EncodedPayload) PrivacyMode(com.quorum.tessera.enclave.PrivacyMode) TypedQuery(jakarta.persistence.TypedQuery) EntityManager(jakarta.persistence.EntityManager) TxHash(com.quorum.tessera.enclave.TxHash) EncryptedTransaction(com.quorum.tessera.data.EncryptedTransaction) Collectors(java.util.stream.Collectors) RecipientBox(com.quorum.tessera.enclave.RecipientBox) EncodedPayload(com.quorum.tessera.enclave.EncodedPayload) EncryptedTransaction(com.quorum.tessera.data.EncryptedTransaction)

Example 82 with EncodedPayload

use of com.quorum.tessera.enclave.EncodedPayload in project tessera by ConsenSys.

the class RecoveryResource method push.

// path /push with application/octet-stream is overloaded (RecoveryResource &
// TransactionResource); swagger annotations cannot handle situations like this so hide this
// operation and use TransactionResource::push to document both
@Hidden
@POST
@Path("push")
@Consumes(APPLICATION_OCTET_STREAM)
public Response push(final byte[] payload, @HeaderParam(Constants.API_VERSION_HEADER) final List<String> headers) {
    LOGGER.debug("Received push request during recovery mode");
    final Set<String> versions = Optional.ofNullable(headers).orElse(emptyList()).stream().filter(Objects::nonNull).flatMap(v -> Arrays.stream(v.split(","))).collect(Collectors.toSet());
    final EncodedPayloadCodec codec = EncodedPayloadCodec.getPreferredCodec(versions);
    final PayloadEncoder payloadEncoder = PayloadEncoder.create(codec);
    final EncodedPayload encodedPayload = payloadEncoder.decode(payload);
    if (encodedPayload.getPrivacyMode() != PrivacyMode.STANDARD_PRIVATE) {
        return Response.status(Response.Status.FORBIDDEN).entity("Transactions with enhanced privacy are not accepted during recovery mode").build();
    }
    final MessageHash messageHash = transactionManager.storePayload(encodedPayload);
    LOGGER.debug("Push request generated hash {}", messageHash);
    return Response.status(Response.Status.CREATED).entity(Objects.toString(messageHash)).build();
}
Also used : java.util(java.util) PrivacyMode(com.quorum.tessera.enclave.PrivacyMode) HeaderParam(jakarta.ws.rs.HeaderParam) LoggerFactory(org.slf4j.LoggerFactory) BatchResendManager(com.quorum.tessera.recovery.workflow.BatchResendManager) PayloadEncoder(com.quorum.tessera.enclave.PayloadEncoder) PushBatchRequest(com.quorum.tessera.p2p.recovery.PushBatchRequest) Valid(jakarta.validation.Valid) NotNull(jakarta.validation.constraints.NotNull) Path(jakarta.ws.rs.Path) Operation(io.swagger.v3.oas.annotations.Operation) Response(jakarta.ws.rs.core.Response) APPLICATION_OCTET_STREAM(jakarta.ws.rs.core.MediaType.APPLICATION_OCTET_STREAM) ApiResponse(io.swagger.v3.oas.annotations.responses.ApiResponse) MessageHash(com.quorum.tessera.data.MessageHash) Constants(com.quorum.tessera.shared.Constants) Consumes(jakarta.ws.rs.Consumes) EncodedPayload(com.quorum.tessera.enclave.EncodedPayload) Logger(org.slf4j.Logger) Hidden(io.swagger.v3.oas.annotations.Hidden) POST(jakarta.ws.rs.POST) Collections.emptyList(java.util.Collections.emptyList) TransactionManager(com.quorum.tessera.transaction.TransactionManager) Collectors(java.util.stream.Collectors) Tag(io.swagger.v3.oas.annotations.tags.Tag) APPLICATION_JSON(jakarta.ws.rs.core.MediaType.APPLICATION_JSON) EncodedPayloadCodec(com.quorum.tessera.enclave.EncodedPayloadCodec) PayloadEncoder(com.quorum.tessera.enclave.PayloadEncoder) EncodedPayload(com.quorum.tessera.enclave.EncodedPayload) MessageHash(com.quorum.tessera.data.MessageHash) EncodedPayloadCodec(com.quorum.tessera.enclave.EncodedPayloadCodec) Path(jakarta.ws.rs.Path) POST(jakarta.ws.rs.POST) Consumes(jakarta.ws.rs.Consumes) Hidden(io.swagger.v3.oas.annotations.Hidden)

Example 83 with EncodedPayload

use of com.quorum.tessera.enclave.EncodedPayload in project tessera by ConsenSys.

the class PartyInfoResourceTest method partyInfoExceptionIfValidationFailsWith400.

@Test
public void partyInfoExceptionIfValidationFailsWith400() {
    final int validateResponseCode = 400;
    final String validateResponseMsg = null;
    String url = "http://www.bogus.com";
    PublicKey myKey = PublicKey.from("myKey".getBytes());
    PublicKey recipientKey = PublicKey.from("recipientKey".getBytes());
    String message = "I love sparrows";
    byte[] payload = message.getBytes();
    Recipient recipient = Recipient.of(recipientKey, url);
    Set<Recipient> recipientList = Collections.singleton(recipient);
    PartyInfo partyInfo = new PartyInfo(url, recipientList, Collections.emptySet());
    when(partyInfoParser.from(payload)).thenReturn(partyInfo);
    when(enclave.defaultPublicKey()).thenReturn(myKey);
    when(partyInfoParser.to(partyInfo)).thenReturn(payload);
    EncodedPayload encodedPayload = mock(EncodedPayload.class);
    when(enclave.encryptPayload(any(byte[].class), any(PublicKey.class), anyList(), any(PrivacyMetadata.class))).thenReturn(encodedPayload);
    when(payloadEncoder.encode(encodedPayload)).thenReturn(payload);
    WebTarget webTarget = mock(WebTarget.class);
    when(restClient.target(url)).thenReturn(webTarget);
    when(webTarget.path(anyString())).thenReturn(webTarget);
    Invocation.Builder invocationBuilder = mock(Invocation.Builder.class);
    when(webTarget.request()).thenReturn(invocationBuilder);
    Response response = mock(Response.class);
    when(response.getStatus()).thenReturn(validateResponseCode);
    doAnswer((invocation) -> validateResponseMsg).when(response).readEntity(String.class);
    when(invocationBuilder.post(any(Entity.class))).thenReturn(response);
    try {
        partyInfoResource.partyInfo(payload, List.of("v1", "v2"));
        failBecauseExceptionWasNotThrown(SecurityException.class);
    } catch (SecurityException ex) {
        verify(partyInfoParser).from(payload);
        verify(enclave).defaultPublicKey();
        verify(enclave).encryptPayload(any(byte[].class), any(PublicKey.class), anyList(), any(PrivacyMetadata.class));
        verify(payloadEncoder).encode(encodedPayload);
        verify(restClient).target(url);
    }
}
Also used : Entity(jakarta.ws.rs.client.Entity) Invocation(jakarta.ws.rs.client.Invocation) PublicKey(com.quorum.tessera.encryption.PublicKey) Recipient(com.quorum.tessera.partyinfo.model.Recipient) EncodedPayload(com.quorum.tessera.enclave.EncodedPayload) PartyInfo(com.quorum.tessera.partyinfo.model.PartyInfo) Response(jakarta.ws.rs.core.Response) PrivacyMetadata(com.quorum.tessera.enclave.PrivacyMetadata) WebTarget(jakarta.ws.rs.client.WebTarget) Test(org.junit.Test)

Example 84 with EncodedPayload

use of com.quorum.tessera.enclave.EncodedPayload in project tessera by ConsenSys.

the class PartyInfoResourceTest method partyInfo.

@Test
public void partyInfo() {
    String url = "http://www.bogus.com";
    PublicKey myKey = PublicKey.from("myKey".getBytes());
    PublicKey recipientKey = PublicKey.from("recipientKey".getBytes());
    String message = "I love sparrows";
    byte[] payload = message.getBytes();
    Recipient recipient = Recipient.of(recipientKey, url);
    Set<Recipient> recipientList = Collections.singleton(recipient);
    PartyInfo partyInfo = new PartyInfo(url, recipientList, Collections.emptySet());
    when(partyInfoParser.from(payload)).thenReturn(partyInfo);
    when(enclave.defaultPublicKey()).thenReturn(myKey);
    when(partyInfoParser.to(partyInfo)).thenReturn(payload);
    EncodedPayload encodedPayload = mock(EncodedPayload.class);
    List<String> uuidList = new ArrayList<>();
    doAnswer((invocation) -> {
        byte[] d = invocation.getArgument(0);
        uuidList.add(new String(d));
        return encodedPayload;
    }).when(enclave).encryptPayload(any(byte[].class), any(PublicKey.class), anyList(), any(PrivacyMetadata.class));
    when(payloadEncoder.encode(encodedPayload)).thenReturn(payload);
    WebTarget webTarget = mock(WebTarget.class);
    when(restClient.target(url)).thenReturn(webTarget);
    when(webTarget.path(anyString())).thenReturn(webTarget);
    Invocation.Builder invocationBuilder = mock(Invocation.Builder.class);
    when(webTarget.request()).thenReturn(invocationBuilder);
    Response response = mock(Response.class);
    when(response.getStatus()).thenReturn(200);
    doAnswer((invocation) -> uuidList.get(0)).when(response).readEntity(String.class);
    when(invocationBuilder.post(any(Entity.class))).thenReturn(response);
    Response result = partyInfoResource.partyInfo(payload, List.of("v1,v2"));
    assertThat(result.getStatus()).isEqualTo(200);
    verify(partyInfoParser).from(payload);
    verify(enclave).defaultPublicKey();
    verify(enclave).encryptPayload(any(byte[].class), any(PublicKey.class), anyList(), any(PrivacyMetadata.class));
    verify(payloadEncoder).encode(encodedPayload);
    verify(restClient).target(url);
    ArgumentCaptor<NodeInfo> argCaptor = ArgumentCaptor.forClass(NodeInfo.class);
    verify(discovery).onUpdate(argCaptor.capture());
    final NodeInfo nodeInfo = argCaptor.getValue();
    assertThat(nodeInfo).isNotNull();
    assertThat(nodeInfo.getUrl()).isEqualTo(url);
    assertThat(nodeInfo.supportedApiVersions()).containsExactlyInAnyOrder("v1", "v2");
}
Also used : Entity(jakarta.ws.rs.client.Entity) Invocation(jakarta.ws.rs.client.Invocation) PublicKey(com.quorum.tessera.encryption.PublicKey) Recipient(com.quorum.tessera.partyinfo.model.Recipient) EncodedPayload(com.quorum.tessera.enclave.EncodedPayload) PartyInfo(com.quorum.tessera.partyinfo.model.PartyInfo) Response(jakarta.ws.rs.core.Response) PrivacyMetadata(com.quorum.tessera.enclave.PrivacyMetadata) NodeInfo(com.quorum.tessera.partyinfo.node.NodeInfo) WebTarget(jakarta.ws.rs.client.WebTarget) Test(org.junit.Test)

Example 85 with EncodedPayload

use of com.quorum.tessera.enclave.EncodedPayload in project tessera by ConsenSys.

the class PartyInfoResourceTest method partyInfoExceptionIfValidationFailsWith200.

@Test
public void partyInfoExceptionIfValidationFailsWith200() {
    final int validateResponseCode = 200;
    final String validateResponseMsg = "BADRESPONSE";
    String url = "http://www.bogus.com";
    PublicKey myKey = PublicKey.from("myKey".getBytes());
    PublicKey recipientKey = PublicKey.from("recipientKey".getBytes());
    String message = "I love sparrows";
    byte[] payload = message.getBytes();
    Recipient recipient = Recipient.of(recipientKey, url);
    Set<Recipient> recipientList = Collections.singleton(recipient);
    PartyInfo partyInfo = new PartyInfo(url, recipientList, Collections.emptySet());
    when(partyInfoParser.from(payload)).thenReturn(partyInfo);
    when(enclave.defaultPublicKey()).thenReturn(myKey);
    when(partyInfoParser.to(partyInfo)).thenReturn(payload);
    EncodedPayload encodedPayload = mock(EncodedPayload.class);
    when(enclave.encryptPayload(any(byte[].class), any(PublicKey.class), anyList(), any(PrivacyMetadata.class))).thenReturn(encodedPayload);
    when(payloadEncoder.encode(encodedPayload)).thenReturn(payload);
    WebTarget webTarget = mock(WebTarget.class);
    when(restClient.target(url)).thenReturn(webTarget);
    when(webTarget.path(anyString())).thenReturn(webTarget);
    Invocation.Builder invocationBuilder = mock(Invocation.Builder.class);
    when(webTarget.request()).thenReturn(invocationBuilder);
    Response response = mock(Response.class);
    when(response.getStatus()).thenReturn(validateResponseCode);
    doAnswer((invocation) -> validateResponseMsg).when(response).readEntity(String.class);
    when(invocationBuilder.post(any(Entity.class))).thenReturn(response);
    try {
        partyInfoResource.partyInfo(payload, Collections.emptyList());
        failBecauseExceptionWasNotThrown(SecurityException.class);
    } catch (SecurityException ex) {
        verify(partyInfoParser).from(payload);
        verify(enclave).defaultPublicKey();
        verify(enclave).encryptPayload(any(byte[].class), any(PublicKey.class), anyList(), any(PrivacyMetadata.class));
        verify(payloadEncoder).encode(encodedPayload);
        verify(restClient).target(url);
    }
}
Also used : Entity(jakarta.ws.rs.client.Entity) Invocation(jakarta.ws.rs.client.Invocation) PublicKey(com.quorum.tessera.encryption.PublicKey) Recipient(com.quorum.tessera.partyinfo.model.Recipient) EncodedPayload(com.quorum.tessera.enclave.EncodedPayload) PartyInfo(com.quorum.tessera.partyinfo.model.PartyInfo) Response(jakarta.ws.rs.core.Response) PrivacyMetadata(com.quorum.tessera.enclave.PrivacyMetadata) WebTarget(jakarta.ws.rs.client.WebTarget) Test(org.junit.Test)

Aggregations

EncodedPayload (com.quorum.tessera.enclave.EncodedPayload)91 Test (org.junit.Test)60 PublicKey (com.quorum.tessera.encryption.PublicKey)50 PayloadEncoder (com.quorum.tessera.enclave.PayloadEncoder)23 Response (jakarta.ws.rs.core.Response)20 MessageHash (com.quorum.tessera.data.MessageHash)13 Collectors (java.util.stream.Collectors)12 EncryptedTransaction (com.quorum.tessera.data.EncryptedTransaction)11 PrivacyMode (com.quorum.tessera.enclave.PrivacyMode)11 EncodedPayloadCodec (com.quorum.tessera.enclave.EncodedPayloadCodec)9 NodeInfo (com.quorum.tessera.partyinfo.node.NodeInfo)8 Recipient (com.quorum.tessera.partyinfo.node.Recipient)8 java.util (java.util)8 Invocation (jakarta.ws.rs.client.Invocation)6 WebTarget (jakarta.ws.rs.client.WebTarget)6 StagingTransaction (com.quorum.tessera.data.staging.StagingTransaction)5 PrivacyMetadata (com.quorum.tessera.enclave.PrivacyMetadata)5 RecipientBox (com.quorum.tessera.enclave.RecipientBox)5 TxHash (com.quorum.tessera.enclave.TxHash)5 ResendRequest (com.quorum.tessera.p2p.resend.ResendRequest)5