Search in sources :

Example 1 with MainnetBesuControllerBuilder

use of org.hyperledger.besu.controller.MainnetBesuControllerBuilder in project besu by hyperledger.

the class RunnerTest method syncFromGenesis.

private void syncFromGenesis(final SyncMode mode, final GenesisConfigFile genesisConfig) throws Exception {
    final Path dataDirAhead = temp.newFolder().toPath();
    final Path dbAhead = dataDirAhead.resolve("database");
    final int blockCount = 500;
    final NodeKey aheadDbNodeKey = NodeKeyUtils.createFrom(KeyPairUtil.loadKeyPair(dbAhead));
    final SynchronizerConfiguration syncConfigAhead = SynchronizerConfiguration.builder().syncMode(SyncMode.FULL).build();
    final ObservableMetricsSystem noOpMetricsSystem = new NoOpMetricsSystem();
    final BigInteger networkId = BigInteger.valueOf(2929);
    // Setup state with block data
    try (final BesuController controller = new MainnetBesuControllerBuilder().genesisConfigFile(genesisConfig).synchronizerConfiguration(syncConfigAhead).ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()).dataDirectory(dataDirAhead).networkId(networkId).miningParameters(new MiningParameters.Builder().miningEnabled(false).build()).nodeKey(aheadDbNodeKey).metricsSystem(noOpMetricsSystem).privacyParameters(PrivacyParameters.DEFAULT).clock(TestClock.fixed()).transactionPoolConfiguration(TransactionPoolConfiguration.DEFAULT).storageProvider(createKeyValueStorageProvider(dataDirAhead, dbAhead)).gasLimitCalculator(GasLimitCalculator.constant()).evmConfiguration(EvmConfiguration.DEFAULT).build()) {
        setupState(blockCount, controller.getProtocolSchedule(), controller.getProtocolContext());
    }
    // Setup Runner with blocks
    final BesuController controllerAhead = new MainnetBesuControllerBuilder().genesisConfigFile(genesisConfig).synchronizerConfiguration(syncConfigAhead).ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()).dataDirectory(dataDirAhead).networkId(networkId).miningParameters(new MiningParameters.Builder().miningEnabled(false).build()).nodeKey(aheadDbNodeKey).metricsSystem(noOpMetricsSystem).privacyParameters(PrivacyParameters.DEFAULT).clock(TestClock.fixed()).transactionPoolConfiguration(TransactionPoolConfiguration.DEFAULT).storageProvider(createKeyValueStorageProvider(dataDirAhead, dbAhead)).gasLimitCalculator(GasLimitCalculator.constant()).evmConfiguration(EvmConfiguration.DEFAULT).build();
    final String listenHost = InetAddress.getLoopbackAddress().getHostAddress();
    final JsonRpcConfiguration aheadJsonRpcConfiguration = jsonRpcConfiguration();
    final GraphQLConfiguration aheadGraphQLConfiguration = graphQLConfiguration();
    final WebSocketConfiguration aheadWebSocketConfiguration = wsRpcConfiguration();
    final JsonRpcIpcConfiguration aheadJsonRpcIpcConfiguration = new JsonRpcIpcConfiguration();
    final MetricsConfiguration aheadMetricsConfiguration = metricsConfiguration();
    final Path pidPath = temp.getRoot().toPath().resolve("pid");
    final RunnerBuilder runnerBuilder = new RunnerBuilder().vertx(vertx).discovery(true).p2pAdvertisedHost(listenHost).p2pListenPort(0).maxPeers(3).metricsSystem(noOpMetricsSystem).permissioningService(new PermissioningServiceImpl()).staticNodes(emptySet()).storageProvider(new InMemoryKeyValueStorageProvider()).forkIdSupplier(() -> Collections.singletonList(Bytes.EMPTY)).rpcEndpointService(new RpcEndpointServiceImpl());
    Runner runnerBehind = null;
    final Runner runnerAhead = runnerBuilder.besuController(controllerAhead).ethNetworkConfig(EthNetworkConfig.getNetworkConfig(DEV)).jsonRpcConfiguration(aheadJsonRpcConfiguration).graphQLConfiguration(aheadGraphQLConfiguration).webSocketConfiguration(aheadWebSocketConfiguration).jsonRpcIpcConfiguration(aheadJsonRpcIpcConfiguration).metricsConfiguration(aheadMetricsConfiguration).dataDir(dbAhead).pidPath(pidPath).besuPluginContext(new BesuPluginContextImpl()).forkIdSupplier(() -> controllerAhead.getProtocolManager().getForkIdAsBytesList()).rpcEndpointService(new RpcEndpointServiceImpl()).build();
    try {
        runnerAhead.startExternalServices();
        runnerAhead.startEthereumMainLoop();
        assertThat(pidPath.toFile()).exists();
        final SynchronizerConfiguration syncConfigBehind = SynchronizerConfiguration.builder().syncMode(mode).fastSyncPivotDistance(5).fastSyncMinimumPeerCount(1).build();
        final Path dataDirBehind = temp.newFolder().toPath();
        final JsonRpcConfiguration behindJsonRpcConfiguration = jsonRpcConfiguration();
        final GraphQLConfiguration behindGraphQLConfiguration = graphQLConfiguration();
        final WebSocketConfiguration behindWebSocketConfiguration = wsRpcConfiguration();
        final MetricsConfiguration behindMetricsConfiguration = metricsConfiguration();
        // Setup runner with no block data
        final BesuController controllerBehind = new MainnetBesuControllerBuilder().genesisConfigFile(genesisConfig).synchronizerConfiguration(syncConfigBehind).ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()).dataDirectory(dataDirBehind).networkId(networkId).miningParameters(new MiningParameters.Builder().miningEnabled(false).build()).nodeKey(NodeKeyUtils.generate()).storageProvider(new InMemoryKeyValueStorageProvider()).metricsSystem(noOpMetricsSystem).privacyParameters(PrivacyParameters.DEFAULT).clock(TestClock.fixed()).transactionPoolConfiguration(TransactionPoolConfiguration.DEFAULT).gasLimitCalculator(GasLimitCalculator.constant()).evmConfiguration(EvmConfiguration.DEFAULT).build();
        final EnodeURL enode = runnerAhead.getLocalEnode().get();
        final EthNetworkConfig behindEthNetworkConfiguration = new EthNetworkConfig(EthNetworkConfig.jsonConfig(DEV), DEV.getNetworkId(), Collections.singletonList(enode), null);
        runnerBehind = runnerBuilder.besuController(controllerBehind).ethNetworkConfig(behindEthNetworkConfiguration).jsonRpcConfiguration(behindJsonRpcConfiguration).graphQLConfiguration(behindGraphQLConfiguration).webSocketConfiguration(behindWebSocketConfiguration).metricsConfiguration(behindMetricsConfiguration).dataDir(temp.newFolder().toPath()).metricsSystem(noOpMetricsSystem).forkIdSupplier(() -> controllerBehind.getProtocolManager().getForkIdAsBytesList()).build();
        runnerBehind.startExternalServices();
        runnerBehind.startEthereumMainLoop();
        final int behindJsonRpcPort = runnerBehind.getJsonRpcPort().get();
        final OkHttpClient client = new OkHttpClient();
        Awaitility.await().ignoreExceptions().atMost(5L, TimeUnit.MINUTES).untilAsserted(() -> {
            final String baseUrl = String.format("http://%s:%s", listenHost, behindJsonRpcPort);
            try (final Response resp = client.newCall(new Request.Builder().post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(7) + ",\"method\":\"eth_blockNumber\"}")).url(baseUrl).build()).execute()) {
                assertThat(resp.code()).isEqualTo(200);
                final Response syncingResp = client.newCall(new Request.Builder().post(RequestBody.create(MediaType.parse("application/json; charset=utf-8"), "{\"jsonrpc\":\"2.0\",\"id\":" + Json.encode(7) + ",\"method\":\"eth_syncing\"}")).url(baseUrl).build()).execute();
                assertThat(syncingResp.code()).isEqualTo(200);
                final int currentBlock = UInt256.fromHexString(new JsonObject(resp.body().string()).getString("result")).intValue();
                final JsonObject responseJson = new JsonObject(syncingResp.body().string());
                if (currentBlock < blockCount) {
                    // if not yet at blockCount, we should get a sync result from eth_syncing
                    assertThat(responseJson.getValue("result")).isInstanceOf(JsonObject.class);
                    final int syncResultCurrentBlock = UInt256.fromHexString(responseJson.getJsonObject("result").getString("currentBlock")).intValue();
                    assertThat(syncResultCurrentBlock).isLessThan(blockCount);
                }
                assertThat(currentBlock).isEqualTo(blockCount);
                resp.close();
                // when we have synced to blockCount, eth_syncing should return false
                final boolean syncResult = responseJson.getBoolean("result");
                assertThat(syncResult).isFalse();
                syncingResp.close();
            }
        });
        final Promise<String> promise = Promise.promise();
        final HttpClient httpClient = vertx.createHttpClient();
        httpClient.webSocket(runnerBehind.getWebSocketPort().get(), WebSocketConfiguration.DEFAULT_WEBSOCKET_HOST, "/", ws -> {
            ws.result().writeTextMessage("{\"id\": 1, \"method\": \"eth_subscribe\", \"params\": [\"syncing\"]}");
            ws.result().textMessageHandler(payload -> {
                final boolean matches = payload.equals("{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":\"0x0\"}");
                if (matches) {
                    promise.complete(payload);
                } else {
                    promise.fail("Unexpected result: " + payload);
                }
            });
        });
        final Future<String> future = promise.future();
        Awaitility.await().catchUncaughtExceptions().atMost(5L, TimeUnit.MINUTES).until(future::isComplete);
    } finally {
        if (runnerBehind != null) {
            runnerBehind.close();
            runnerBehind.awaitStop();
        }
    }
}
Also used : BesuPluginContextImpl(org.hyperledger.besu.services.BesuPluginContextImpl) MockitoJUnitRunner(org.mockito.junit.MockitoJUnitRunner) BesuController(org.hyperledger.besu.controller.BesuController) OkHttpClient(okhttp3.OkHttpClient) MainnetBesuControllerBuilder(org.hyperledger.besu.controller.MainnetBesuControllerBuilder) KeyValueStorageProviderBuilder(org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProviderBuilder) JsonObject(io.vertx.core.json.JsonObject) EnodeURL(org.hyperledger.besu.plugin.data.EnodeURL) MetricsConfiguration(org.hyperledger.besu.metrics.prometheus.MetricsConfiguration) MainnetBesuControllerBuilder(org.hyperledger.besu.controller.MainnetBesuControllerBuilder) InMemoryKeyValueStorageProvider(org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider) SynchronizerConfiguration(org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration) JsonRpcIpcConfiguration(org.hyperledger.besu.ethereum.api.jsonrpc.ipc.JsonRpcIpcConfiguration) NodeKey(org.hyperledger.besu.crypto.NodeKey) GraphQLConfiguration(org.hyperledger.besu.ethereum.api.graphql.GraphQLConfiguration) Path(java.nio.file.Path) RpcEndpointServiceImpl(org.hyperledger.besu.services.RpcEndpointServiceImpl) JsonRpcConfiguration(org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration) WebSocketConfiguration(org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration) Request(okhttp3.Request) Response(okhttp3.Response) PermissioningServiceImpl(org.hyperledger.besu.services.PermissioningServiceImpl) ObservableMetricsSystem(org.hyperledger.besu.metrics.ObservableMetricsSystem) NoOpMetricsSystem(org.hyperledger.besu.metrics.noop.NoOpMetricsSystem) HttpClient(io.vertx.core.http.HttpClient) OkHttpClient(okhttp3.OkHttpClient) BigInteger(java.math.BigInteger) EthNetworkConfig(org.hyperledger.besu.cli.config.EthNetworkConfig)

Aggregations

HttpClient (io.vertx.core.http.HttpClient)1 JsonObject (io.vertx.core.json.JsonObject)1 BigInteger (java.math.BigInteger)1 Path (java.nio.file.Path)1 OkHttpClient (okhttp3.OkHttpClient)1 Request (okhttp3.Request)1 Response (okhttp3.Response)1 EthNetworkConfig (org.hyperledger.besu.cli.config.EthNetworkConfig)1 BesuController (org.hyperledger.besu.controller.BesuController)1 MainnetBesuControllerBuilder (org.hyperledger.besu.controller.MainnetBesuControllerBuilder)1 NodeKey (org.hyperledger.besu.crypto.NodeKey)1 GraphQLConfiguration (org.hyperledger.besu.ethereum.api.graphql.GraphQLConfiguration)1 JsonRpcConfiguration (org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration)1 JsonRpcIpcConfiguration (org.hyperledger.besu.ethereum.api.jsonrpc.ipc.JsonRpcIpcConfiguration)1 WebSocketConfiguration (org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration)1 InMemoryKeyValueStorageProvider (org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider)1 SynchronizerConfiguration (org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration)1 KeyValueStorageProviderBuilder (org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProviderBuilder)1 ObservableMetricsSystem (org.hyperledger.besu.metrics.ObservableMetricsSystem)1 NoOpMetricsSystem (org.hyperledger.besu.metrics.noop.NoOpMetricsSystem)1