Search in sources :

Example 26 with RuntimeContext

use of com.quorum.tessera.context.RuntimeContext in project tessera by ConsenSys.

the class Main method main.

public static void main(final String... args) throws Exception {
    Security.addProvider(new BouncyCastleProvider());
    LOGGER.debug("args [{}]", String.join(",", args));
    try {
        PicoCliDelegate picoCliDelegate = new PicoCliDelegate();
        LOGGER.debug("Execute PicoCliDelegate with args [{}]", String.join(",", args));
        final CliResult cliResult = picoCliDelegate.execute(args);
        LOGGER.debug("Executed PicoCliDelegate with args [{}].", String.join(",", args));
        if (cliResult.isSuppressStartup()) {
            System.exit(0);
        }
        if (cliResult.getStatus() != 0) {
            System.exit(cliResult.getStatus());
        }
        final Config config = cliResult.getConfig().orElseThrow(() -> new NoSuchElementException("No config found. Tessera will not run."));
        // Start legacy spring profile stuff
        final String springProfileWarning = "Warn: Spring profiles will not be supported in future. To start in recover mode use 'tessera recover'";
        if (System.getProperties().containsKey("spring.profiles.active")) {
            System.out.println(springProfileWarning);
            config.setRecoveryMode(System.getProperty("spring.profiles.active").contains("enable-sync-poller"));
        } else if (System.getenv().containsKey("SPRING_PROFILES_ACTIVE")) {
            System.out.println(springProfileWarning);
            config.setRecoveryMode(System.getenv("SPRING_PROFILES_ACTIVE").contains("enable-sync-poller"));
        }
        // end spring profile stuff
        LOGGER.debug("Storing config {}", config);
        ConfigFactory.create().store(config);
        LOGGER.debug("Stored config {}", config);
        LOGGER.debug("Creating enclave");
        final Enclave enclave = Enclave.create();
        LOGGER.debug("Created enclave {}", enclave);
        LOGGER.debug("Creating RuntimeContext");
        final RuntimeContext runtimeContext = RuntimeContext.getInstance();
        LOGGER.debug("Created RuntimeContext {}", runtimeContext);
        LOGGER.debug("Creating Discovery");
        Discovery discovery = Discovery.create();
        discovery.onCreate();
        LOGGER.debug("Created Discovery {}", discovery);
        if (runtimeContext.isMultiplePrivateStates()) {
            LOGGER.debug("Creating ResidentGroupHandler");
            ResidentGroupHandler residentGroupHandler = ResidentGroupHandler.create();
            residentGroupHandler.onCreate(config);
            LOGGER.debug("Created ResidentGroupHandler {}", residentGroupHandler);
        }
        LOGGER.debug("Creating EncodedPayloadManager");
        EncodedPayloadManager.create();
        LOGGER.debug("Created EncodedPayloadManager");
        LOGGER.debug("Creating BatchResendManager");
        BatchResendManager.create();
        LOGGER.debug("Created BatchResendManager");
        LOGGER.debug("Creating txn manager");
        TransactionManager transactionManager = TransactionManager.create();
        LOGGER.debug("Created txn manager");
        LOGGER.debug("Validating if transaction table exists");
        if (!transactionManager.upcheck()) {
            throw new RuntimeException("The database has not been setup correctly. Please ensure transaction tables " + "are present and correct");
        }
        LOGGER.debug("Creating ScheduledServiceFactory");
        ScheduledServiceFactory scheduledServiceFactory = ScheduledServiceFactory.fromConfig(config);
        scheduledServiceFactory.build();
        LOGGER.debug("Created ScheduledServiceFactory");
        LOGGER.debug("Creating Launcher");
        final List<TesseraServer> tesseraServers = Launcher.create(runtimeContext.isRecoveryMode()).launchServer(config);
        LOGGER.debug("Created Launcher");
        if (config.getOutputServerURIPath() != null) {
            ServerURIFileWriter.writeURIFile(config.getOutputServerURIPath(), tesseraServers);
        }
    } catch (final ConstraintViolationException ex) {
        for (final ConstraintViolation<?> violation : ex.getConstraintViolations()) {
            System.err.println("ERROR: Config validation issue: " + violation.getPropertyPath() + " " + violation.getMessage());
        }
        System.exit(1);
    } catch (final ConfigException ex) {
        LOGGER.debug("", ex);
        final Throwable cause = ExceptionUtils.getRootCause(ex);
        if (JsonException.class.isInstance(cause)) {
            System.err.println("ERROR: Invalid json, cause is " + cause.getMessage());
        } else {
            System.err.println("ERROR: Configuration exception, cause is " + Objects.toString(cause));
        }
        System.exit(3);
    } catch (final CliException ex) {
        LOGGER.debug("", ex);
        System.err.println("ERROR: CLI exception, cause is " + ex.getMessage());
        System.exit(4);
    } catch (final ServiceConfigurationError ex) {
        LOGGER.debug("", ex);
        Optional<Throwable> e = Optional.of(ex);
        e.map(Throwable::getMessage).ifPresent(System.err::println);
        // get root cause
        while (e.map(Throwable::getCause).isPresent()) {
            e = e.map(Throwable::getCause);
        }
        e.map(Throwable::toString).ifPresent(System.err::println);
        System.exit(5);
    } catch (final Throwable ex) {
        LOGGER.debug(null, ex);
        if (Arrays.asList(args).contains("--debug")) {
            ex.printStackTrace();
        } else {
            if (Optional.ofNullable(ex.getMessage()).isPresent()) {
                System.err.println("ERROR: Cause is " + ex.getMessage());
            } else {
                System.err.println("ERROR: In class " + ex.getClass().getSimpleName());
            }
        }
        System.exit(2);
    }
}
Also used : JsonException(jakarta.json.JsonException) Config(com.quorum.tessera.config.Config) ResidentGroupHandler(com.quorum.tessera.privacygroup.ResidentGroupHandler) Discovery(com.quorum.tessera.discovery.Discovery) ConfigException(com.quorum.tessera.config.ConfigException) TesseraServer(com.quorum.tessera.server.TesseraServer) PicoCliDelegate(com.quorum.tessera.config.cli.PicoCliDelegate) CliException(com.quorum.tessera.cli.CliException) CliResult(com.quorum.tessera.cli.CliResult) Enclave(com.quorum.tessera.enclave.Enclave) TransactionManager(com.quorum.tessera.transaction.TransactionManager) ConstraintViolation(jakarta.validation.ConstraintViolation) ConstraintViolationException(jakarta.validation.ConstraintViolationException) RuntimeContext(com.quorum.tessera.context.RuntimeContext) BouncyCastleProvider(org.bouncycastle.jce.provider.BouncyCastleProvider)

Example 27 with RuntimeContext

use of com.quorum.tessera.context.RuntimeContext in project tessera by ConsenSys.

the class PrivacyGroupResourceTest method testGetNoGroupsFound.

@Test
public void testGetNoGroupsFound() {
    RuntimeContext runtimeContext = mock(RuntimeContext.class);
    try (var runtimeContextMockedStatic = mockStatic(RuntimeContext.class)) {
        runtimeContextMockedStatic.when(RuntimeContext::getInstance).thenReturn(runtimeContext);
        final Response response = privacyGroupResource.getPrivacyGroups("legacy");
        assertThat(response).isNotNull();
        assertThat(response.getStatus()).isEqualTo(200);
        PrivacyGroupResponse[] responses = (PrivacyGroupResponse[]) response.getEntity();
        assertThat(responses.length).isEqualTo(0);
        runtimeContextMockedStatic.verify(RuntimeContext::getInstance);
        runtimeContextMockedStatic.verifyNoMoreInteractions();
    }
    verify(privacyGroupManager).findPrivacyGroupByType(eq(PrivacyGroup.Type.LEGACY));
    verifyNoMoreInteractions(runtimeContext);
}
Also used : Response(jakarta.ws.rs.core.Response) RuntimeContext(com.quorum.tessera.context.RuntimeContext) Test(org.junit.Test)

Example 28 with RuntimeContext

use of com.quorum.tessera.context.RuntimeContext in project tessera by ConsenSys.

the class PrivacyGroupResource method getPrivacyGroups.

@GET
@Path("groups/{type}")
@Produces(APPLICATION_JSON)
public Response getPrivacyGroups(@PathParam("type") String type) {
    final PrivacyGroup.Type queryType = PrivacyGroup.Type.valueOf(type.toUpperCase());
    final RuntimeContext runtimeContext = RuntimeContext.getInstance();
    if (queryType == PrivacyGroup.Type.RESIDENT && !runtimeContext.isMultiplePrivateStates()) {
        return Response.status(Response.Status.SERVICE_UNAVAILABLE).entity("Multiple private state feature is not available on this privacy manager").build();
    }
    final List<PrivacyGroup> privacyGroups = privacyGroupManager.findPrivacyGroupByType(queryType);
    final PrivacyGroupResponse[] results = privacyGroups.stream().map(this::toResponseObject).toArray(PrivacyGroupResponse[]::new);
    return Response.status(Response.Status.OK).type(APPLICATION_JSON).entity(results).build();
}
Also used : RuntimeContext(com.quorum.tessera.context.RuntimeContext) PrivacyGroup(com.quorum.tessera.enclave.PrivacyGroup)

Example 29 with RuntimeContext

use of com.quorum.tessera.context.RuntimeContext in project tessera by ConsenSys.

the class PartyStoreTest method loadFromConfigIfEmptyExistingParties.

@Test
public void loadFromConfigIfEmptyExistingParties() {
    URI peerUri = URI.create("somepeer");
    URI existingPeerUri = URI.create("anexistingpeer");
    try (var runtimeContextMockedStatic = mockStatic(RuntimeContext.class)) {
        RuntimeContext runtimeContext = mock(RuntimeContext.class);
        when(runtimeContext.getPeers()).thenReturn(List.of(peerUri));
        runtimeContextMockedStatic.when(RuntimeContext::getInstance).thenReturn(runtimeContext);
        PartyStore partyStore = PartyStore.getInstance();
        partyStore.store(existingPeerUri);
        partyStore.loadFromConfigIfEmpty();
        assertThat(partyStore.getParties()).containsExactlyInAnyOrder(peerUri, existingPeerUri);
    }
}
Also used : RuntimeContext(com.quorum.tessera.context.RuntimeContext) URI(java.net.URI) Test(org.junit.Test)

Example 30 with RuntimeContext

use of com.quorum.tessera.context.RuntimeContext in project tessera by ConsenSys.

the class EnclaveKeySynchroniserImpl method syncKeys.

@Override
public void syncKeys() {
    NodeUri nodeUri = Optional.of(RuntimeContext.getInstance()).map(RuntimeContext::getP2pServerUri).map(NodeUri::create).get();
    List<ActiveNode> activeNodes = networkStore.getActiveNodes().filter(a -> a.getUri().equals(nodeUri)).collect(Collectors.toList());
    if (activeNodes.isEmpty()) {
        return;
    }
    final Set<PublicKey> storedKeys = activeNodes.stream().flatMap(a -> a.getKeys().stream()).collect(Collectors.toSet());
    final Set<PublicKey> keys = enclave.getPublicKeys();
    if (!storedKeys.equals(keys)) {
        final Set<PublicKey> allKeys = Stream.concat(storedKeys.stream(), keys.stream()).collect(Collectors.toUnmodifiableSet());
        activeNodes.forEach(activeNode -> {
            ActiveNode modified = ActiveNode.Builder.from(activeNode).withKeys(allKeys).build();
            networkStore.store(modified);
        });
    }
}
Also used : EnclaveKeySynchroniser(com.quorum.tessera.discovery.EnclaveKeySynchroniser) PublicKey(com.quorum.tessera.encryption.PublicKey) Set(java.util.Set) NodeUri(com.quorum.tessera.discovery.NodeUri) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) ActiveNode(com.quorum.tessera.discovery.ActiveNode) NetworkStore(com.quorum.tessera.discovery.NetworkStore) List(java.util.List) Stream(java.util.stream.Stream) RuntimeContext(com.quorum.tessera.context.RuntimeContext) Enclave(com.quorum.tessera.enclave.Enclave) Optional(java.util.Optional) PublicKey(com.quorum.tessera.encryption.PublicKey) NodeUri(com.quorum.tessera.discovery.NodeUri) ActiveNode(com.quorum.tessera.discovery.ActiveNode) RuntimeContext(com.quorum.tessera.context.RuntimeContext)

Aggregations

RuntimeContext (com.quorum.tessera.context.RuntimeContext)33 Test (org.junit.Test)20 URI (java.net.URI)14 PublicKey (com.quorum.tessera.encryption.PublicKey)11 ActiveNode (com.quorum.tessera.discovery.ActiveNode)9 NodeUri (com.quorum.tessera.discovery.NodeUri)9 Enclave (com.quorum.tessera.enclave.Enclave)9 Discovery (com.quorum.tessera.discovery.Discovery)6 Set (java.util.Set)6 Stream (java.util.stream.Stream)6 NetworkStore (com.quorum.tessera.discovery.NetworkStore)5 NodeInfo (com.quorum.tessera.partyinfo.node.NodeInfo)5 List (java.util.List)5 Collectors (java.util.stream.Collectors)5 Before (org.junit.Before)5 Response (jakarta.ws.rs.core.Response)4 TransactionManager (com.quorum.tessera.transaction.TransactionManager)3 Client (jakarta.ws.rs.client.Client)3 ConfigKeyPair (com.quorum.tessera.config.keypairs.ConfigKeyPair)2 KeyEncryptor (com.quorum.tessera.config.keys.KeyEncryptor)2