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();
}
}
}
Aggregations