use of org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule in project besu by hyperledger.
the class RunnerBuilder method build.
public Runner build() {
Preconditions.checkNotNull(besuController);
final DiscoveryConfiguration discoveryConfiguration = DiscoveryConfiguration.create().setBindHost(p2pListenInterface).setBindPort(p2pListenPort).setAdvertisedHost(p2pAdvertisedHost);
if (discovery) {
final List<EnodeURL> bootstrap;
if (ethNetworkConfig.getBootNodes() == null) {
bootstrap = EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET).getBootNodes();
} else {
bootstrap = ethNetworkConfig.getBootNodes();
}
discoveryConfiguration.setBootnodes(bootstrap);
discoveryConfiguration.setDnsDiscoveryURL(ethNetworkConfig.getDnsDiscoveryUrl());
} else {
discoveryConfiguration.setActive(false);
}
final NodeKey nodeKey = besuController.getNodeKey();
final SubProtocolConfiguration subProtocolConfiguration = besuController.getSubProtocolConfiguration();
final ProtocolSchedule protocolSchedule = besuController.getProtocolSchedule();
final ProtocolContext context = besuController.getProtocolContext();
final List<SubProtocol> subProtocols = subProtocolConfiguration.getSubProtocols();
final List<ProtocolManager> protocolManagers = subProtocolConfiguration.getProtocolManagers();
final Set<Capability> supportedCapabilities = protocolManagers.stream().flatMap(protocolManager -> protocolManager.getSupportedCapabilities().stream()).collect(Collectors.toSet());
final RlpxConfiguration rlpxConfiguration = RlpxConfiguration.create().setBindHost(p2pListenInterface).setBindPort(p2pListenPort).setMaxPeers(maxPeers).setSupportedProtocols(subProtocols).setClientId(BesuInfo.nodeName(identityString)).setLimitRemoteWireConnectionsEnabled(limitRemoteWireConnectionsEnabled).setFractionRemoteWireConnectionsAllowed(fractionRemoteConnectionsAllowed);
networkingConfiguration.setRlpx(rlpxConfiguration).setDiscovery(discoveryConfiguration);
final PeerPermissionsDenylist bannedNodes = PeerPermissionsDenylist.create();
bannedNodeIds.forEach(bannedNodes::add);
final List<EnodeURL> bootnodes = discoveryConfiguration.getBootnodes();
final Synchronizer synchronizer = besuController.getSynchronizer();
final TransactionSimulator transactionSimulator = new TransactionSimulator(context.getBlockchain(), context.getWorldStateArchive(), protocolSchedule);
final Bytes localNodeId = nodeKey.getPublicKey().getEncodedBytes();
final Optional<NodePermissioningController> nodePermissioningController = buildNodePermissioningController(bootnodes, synchronizer, transactionSimulator, localNodeId, context.getBlockchain());
final PeerPermissions peerPermissions = nodePermissioningController.map(nodePC -> new PeerPermissionsAdapter(nodePC, bootnodes, context.getBlockchain())).map(nodePerms -> PeerPermissions.combine(nodePerms, bannedNodes)).orElse(bannedNodes);
LOG.info("Detecting NAT service.");
final boolean fallbackEnabled = natMethod == NatMethod.AUTO || natMethodFallbackEnabled;
final NatService natService = new NatService(buildNatManager(natMethod), fallbackEnabled);
final NetworkBuilder inactiveNetwork = caps -> new NoopP2PNetwork();
final NetworkBuilder activeNetwork = caps -> DefaultP2PNetwork.builder().vertx(vertx).nodeKey(nodeKey).config(networkingConfiguration).peerPermissions(peerPermissions).metricsSystem(metricsSystem).supportedCapabilities(caps).natService(natService).randomPeerPriority(randomPeerPriority).storageProvider(storageProvider).forkIdSupplier(forkIdSupplier).p2pTLSConfiguration(p2pTLSConfiguration).build();
final NetworkRunner networkRunner = NetworkRunner.builder().protocolManagers(protocolManagers).subProtocols(subProtocols).network(p2pEnabled ? activeNetwork : inactiveNetwork).metricsSystem(metricsSystem).build();
final P2PNetwork network = networkRunner.getNetwork();
// ForkId in Ethereum Node Record needs updating when we transition to a new protocol spec
context.getBlockchain().observeBlockAdded(blockAddedEvent -> {
if (protocolSchedule.streamMilestoneBlocks().anyMatch(blockNumber -> blockNumber == blockAddedEvent.getBlock().getHeader().getNumber())) {
network.updateNodeRecord();
}
});
nodePermissioningController.ifPresent(n -> n.setInsufficientPeersPermissioningProvider(new InsufficientPeersPermissioningProvider(network, bootnodes)));
final TransactionPool transactionPool = besuController.getTransactionPool();
final MiningCoordinator miningCoordinator = besuController.getMiningCoordinator();
final BlockchainQueries blockchainQueries = new BlockchainQueries(context.getBlockchain(), context.getWorldStateArchive(), Optional.of(dataDir.resolve(CACHE_PATH)), Optional.of(besuController.getProtocolManager().ethContext().getScheduler()), apiConfiguration);
final PrivacyParameters privacyParameters = besuController.getPrivacyParameters();
final FilterManager filterManager = new FilterManagerBuilder().blockchainQueries(blockchainQueries).transactionPool(transactionPool).privacyParameters(privacyParameters).build();
vertx.deployVerticle(filterManager);
createPrivateTransactionObserver(filterManager, privacyParameters);
final P2PNetwork peerNetwork = networkRunner.getNetwork();
final MiningParameters miningParameters = besuController.getMiningParameters();
Optional<StratumServer> stratumServer = Optional.empty();
if (miningParameters.isStratumMiningEnabled()) {
var powMiningCoordinator = miningCoordinator;
if (miningCoordinator instanceof TransitionCoordinator) {
LOG.debug("fetching powMiningCoordinator from TransitionCoordinator");
powMiningCoordinator = ((TransitionCoordinator) miningCoordinator).getPreMergeObject();
}
stratumServer = Optional.of(new StratumServer(vertx, powMiningCoordinator, miningParameters.getStratumPort(), miningParameters.getStratumNetworkInterface(), miningParameters.getStratumExtranonce(), metricsSystem));
miningCoordinator.addEthHashObserver(stratumServer.get());
LOG.debug("added ethash observer: {}", stratumServer.get());
}
sanitizePeers(network, staticNodes).map(DefaultPeer::fromEnodeURL).forEach(peerNetwork::addMaintainedConnectionPeer);
final Optional<NodeLocalConfigPermissioningController> nodeLocalConfigPermissioningController = nodePermissioningController.flatMap(NodePermissioningController::localConfigController);
final Optional<AccountPermissioningController> accountPermissioningController = buildAccountPermissioningController(permissioningConfiguration, besuController, transactionSimulator, context.getBlockchain());
final Optional<AccountLocalConfigPermissioningController> accountLocalConfigPermissioningController = accountPermissioningController.flatMap(AccountPermissioningController::getAccountLocalConfigPermissioningController);
Optional<JsonRpcHttpService> jsonRpcHttpService = Optional.empty();
if (jsonRpcConfiguration.isEnabled()) {
final Map<String, JsonRpcMethod> nonEngineMethods = jsonRpcMethods(protocolSchedule, context, besuController, peerNetwork, blockchainQueries, synchronizer, transactionPool, miningCoordinator, metricsSystem, supportedCapabilities, jsonRpcConfiguration.getRpcApis().stream().filter(apiGroup -> !apiGroup.toLowerCase().startsWith("engine")).collect(Collectors.toList()), filterManager, accountLocalConfigPermissioningController, nodeLocalConfigPermissioningController, privacyParameters, jsonRpcConfiguration, webSocketConfiguration, metricsConfiguration, natService, besuPluginContext.getNamedPlugins(), dataDir, rpcEndpointServiceImpl);
jsonRpcHttpService = Optional.of(new JsonRpcHttpService(vertx, dataDir, jsonRpcConfiguration, metricsSystem, natService, nonEngineMethods, new HealthService(new LivenessCheck()), new HealthService(new ReadinessCheck(peerNetwork, synchronizer))));
}
Optional<JsonRpcService> engineJsonRpcService = Optional.empty();
if (engineJsonRpcConfiguration.isPresent() && engineJsonRpcConfiguration.get().isEnabled()) {
final Map<String, JsonRpcMethod> engineMethods = jsonRpcMethods(protocolSchedule, context, besuController, peerNetwork, blockchainQueries, synchronizer, transactionPool, miningCoordinator, metricsSystem, supportedCapabilities, engineJsonRpcConfiguration.get().getRpcApis(), filterManager, accountLocalConfigPermissioningController, nodeLocalConfigPermissioningController, privacyParameters, engineJsonRpcConfiguration.get(), webSocketConfiguration, metricsConfiguration, natService, besuPluginContext.getNamedPlugins(), dataDir, rpcEndpointServiceImpl);
Optional<AuthenticationService> authToUse = engineJsonRpcConfiguration.get().isAuthenticationEnabled() ? Optional.of(new EngineAuthService(vertx, Optional.ofNullable(engineJsonRpcConfiguration.get().getAuthenticationPublicKeyFile()), dataDir)) : Optional.empty();
WebSocketConfiguration engineSocketConfig = webSocketConfiguration.isEnabled() ? webSocketConfiguration : WebSocketConfiguration.createEngineDefault();
engineJsonRpcService = Optional.of(new JsonRpcService(vertx, dataDir, engineJsonRpcConfiguration.orElse(JsonRpcConfiguration.createEngineDefault()), metricsSystem, natService, engineMethods, Optional.ofNullable(engineSocketConfig), besuController.getProtocolManager().ethContext().getScheduler(), authToUse, new HealthService(new LivenessCheck()), new HealthService(new ReadinessCheck(peerNetwork, synchronizer))));
}
Optional<GraphQLHttpService> graphQLHttpService = Optional.empty();
if (graphQLConfiguration.isEnabled()) {
final GraphQLDataFetchers fetchers = new GraphQLDataFetchers(supportedCapabilities, privacyParameters.getGoQuorumPrivacyParameters());
final Map<GraphQLContextType, Object> graphQlContextMap = new ConcurrentHashMap<>();
graphQlContextMap.putIfAbsent(GraphQLContextType.BLOCKCHAIN_QUERIES, blockchainQueries);
graphQlContextMap.putIfAbsent(GraphQLContextType.PROTOCOL_SCHEDULE, protocolSchedule);
graphQlContextMap.putIfAbsent(GraphQLContextType.TRANSACTION_POOL, transactionPool);
graphQlContextMap.putIfAbsent(GraphQLContextType.MINING_COORDINATOR, miningCoordinator);
graphQlContextMap.putIfAbsent(GraphQLContextType.SYNCHRONIZER, synchronizer);
final GraphQL graphQL;
try {
graphQL = GraphQLProvider.buildGraphQL(fetchers);
} catch (final IOException ioe) {
throw new RuntimeException(ioe);
}
graphQLHttpService = Optional.of(new GraphQLHttpService(vertx, dataDir, graphQLConfiguration, graphQL, graphQlContextMap, besuController.getProtocolManager().ethContext().getScheduler()));
}
Optional<WebSocketService> webSocketService = Optional.empty();
if (webSocketConfiguration.isEnabled()) {
final Map<String, JsonRpcMethod> nonEngineMethods = jsonRpcMethods(protocolSchedule, context, besuController, peerNetwork, blockchainQueries, synchronizer, transactionPool, miningCoordinator, metricsSystem, supportedCapabilities, webSocketConfiguration.getRpcApis().stream().filter(apiGroup -> !apiGroup.toLowerCase().startsWith("engine")).collect(Collectors.toList()), filterManager, accountLocalConfigPermissioningController, nodeLocalConfigPermissioningController, privacyParameters, jsonRpcConfiguration, webSocketConfiguration, metricsConfiguration, natService, besuPluginContext.getNamedPlugins(), dataDir, rpcEndpointServiceImpl);
final SubscriptionManager subscriptionManager = createSubscriptionManager(vertx, transactionPool, blockchainQueries);
createLogsSubscriptionService(context.getBlockchain(), context.getWorldStateArchive(), subscriptionManager, privacyParameters);
createNewBlockHeadersSubscriptionService(context.getBlockchain(), blockchainQueries, subscriptionManager);
createSyncingSubscriptionService(synchronizer, subscriptionManager);
webSocketService = Optional.of(createWebsocketService(vertx, webSocketConfiguration, subscriptionManager, nonEngineMethods, privacyParameters, protocolSchedule, blockchainQueries, DefaultAuthenticationService.create(vertx, webSocketConfiguration), metricsSystem));
createPrivateTransactionObserver(subscriptionManager, privacyParameters);
}
Optional<MetricsService> metricsService = createMetricsService(vertx, metricsConfiguration);
final Optional<EthStatsService> ethStatsService;
if (!Strings.isNullOrEmpty(ethstatsUrl)) {
ethStatsService = Optional.of(new EthStatsService(NetstatsUrl.fromParams(ethstatsUrl, ethstatsContact), blockchainQueries, besuController.getProtocolManager(), transactionPool, miningCoordinator, besuController.getSyncState(), vertx, BesuInfo.nodeName(identityString), besuController.getGenesisConfigOptions(), network));
} else {
ethStatsService = Optional.empty();
}
final Optional<JsonRpcIpcService> jsonRpcIpcService;
if (jsonRpcIpcConfiguration.isEnabled()) {
Map<String, JsonRpcMethod> ipcMethods = jsonRpcMethods(protocolSchedule, context, besuController, peerNetwork, blockchainQueries, synchronizer, transactionPool, miningCoordinator, metricsSystem, supportedCapabilities, jsonRpcIpcConfiguration.getEnabledApis().stream().filter(apiGroup -> !apiGroup.toLowerCase().startsWith("engine")).collect(Collectors.toList()), filterManager, accountLocalConfigPermissioningController, nodeLocalConfigPermissioningController, privacyParameters, jsonRpcConfiguration, webSocketConfiguration, metricsConfiguration, natService, besuPluginContext.getNamedPlugins(), dataDir, rpcEndpointServiceImpl);
jsonRpcIpcService = Optional.of(new JsonRpcIpcService(vertx, jsonRpcIpcConfiguration.getPath(), new JsonRpcExecutor(new BaseJsonRpcProcessor(), ipcMethods)));
} else {
jsonRpcIpcService = Optional.empty();
}
return new Runner(vertx, networkRunner, natService, jsonRpcHttpService, engineJsonRpcService, graphQLHttpService, webSocketService, jsonRpcIpcService, stratumServer, metricsService, ethStatsService, besuController, dataDir, pidPath, autoLogBloomCaching ? blockchainQueries.getTransactionLogBloomCacher() : Optional.empty(), context.getBlockchain());
}
use of org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule in project besu by hyperledger.
the class QbftProtocolScheduleTest method blockModeTransitionsCreatesBlockModeHeaderValidators.
@Test
public void blockModeTransitionsCreatesBlockModeHeaderValidators() {
final MutableQbftConfigOptions arbitraryTransition = new MutableQbftConfigOptions(JsonQbftConfigOptions.DEFAULT);
arbitraryTransition.setBlockRewardWei(BigInteger.ONE);
final BlockHeader parentHeader = QbftBlockHeaderUtils.createPresetHeaderBuilder(1, proposerNodeKey, validators, null, Optional.empty()).buildHeader();
final BlockHeader blockHeader = QbftBlockHeaderUtils.createPresetHeaderBuilder(2, proposerNodeKey, validators, parentHeader, Optional.empty()).buildHeader();
final ProtocolSchedule schedule = createProtocolSchedule(JsonGenesisConfigOptions.fromJsonObject(JsonUtil.createEmptyObjectNode()), List.of(new ForkSpec<>(0, JsonQbftConfigOptions.DEFAULT), new ForkSpec<>(1, arbitraryTransition), new ForkSpec<>(2, JsonQbftConfigOptions.DEFAULT)));
assertThat(schedule.streamMilestoneBlocks().count()).isEqualTo(3);
assertThat(validateHeader(schedule, validators, parentHeader, blockHeader, 0)).isTrue();
assertThat(validateHeader(schedule, validators, parentHeader, blockHeader, 1)).isTrue();
assertThat(validateHeader(schedule, validators, parentHeader, blockHeader, 2)).isTrue();
}
use of org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule in project besu by hyperledger.
the class TransactionSmartContractPermissioningControllerTest method setupController.
private TransactionSmartContractPermissioningController setupController(final String resourceName, final String contractAddressString) throws IOException {
final ProtocolSchedule protocolSchedule = ProtocolScheduleFixture.MAINNET;
final String emptyContractFile = Resources.toString(this.getClass().getResource(resourceName), UTF_8);
final GenesisState genesisState = GenesisState.fromConfig(GenesisConfigFile.fromConfig(emptyContractFile), protocolSchedule);
final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock());
final WorldStateArchive worldArchive = createInMemoryWorldStateArchive();
genesisState.writeStateTo(worldArchive.getMutable());
final TransactionSimulator ts = new TransactionSimulator(blockchain, worldArchive, protocolSchedule);
final Address contractAddress = Address.fromHexString(contractAddressString);
when(metricsSystem.createCounter(BesuMetricCategory.PERMISSIONING, "transaction_smart_contract_check_count", "Number of times the transaction smart contract permissioning provider has been checked")).thenReturn(checkCounter);
when(metricsSystem.createCounter(BesuMetricCategory.PERMISSIONING, "transaction_smart_contract_check_count_permitted", "Number of times the transaction smart contract permissioning provider has been checked and returned permitted")).thenReturn(checkPermittedCounter);
when(metricsSystem.createCounter(BesuMetricCategory.PERMISSIONING, "transaction_smart_contract_check_count_unpermitted", "Number of times the transaction smart contract permissioning provider has been checked and returned unpermitted")).thenReturn(checkUnpermittedCounter);
return new TransactionSmartContractPermissioningController(contractAddress, ts, metricsSystem);
}
use of org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule in project besu by hyperledger.
the class ReferenceTestProtocolSchedules method create.
public static ReferenceTestProtocolSchedules create() {
final ImmutableMap.Builder<String, ProtocolSchedule> builder = ImmutableMap.builder();
builder.put("Frontier", createSchedule(new StubGenesisConfigOptions()));
builder.put("FrontierToHomesteadAt5", createSchedule(new StubGenesisConfigOptions().homesteadBlock(5)));
builder.put("Homestead", createSchedule(new StubGenesisConfigOptions().homesteadBlock(0)));
builder.put("HomesteadToEIP150At5", createSchedule(new StubGenesisConfigOptions().homesteadBlock(0).eip150Block(5)));
builder.put("HomesteadToDaoAt5", createSchedule(new StubGenesisConfigOptions().homesteadBlock(0).daoForkBlock(5)));
builder.put("EIP150", createSchedule(new StubGenesisConfigOptions().eip150Block(0)));
builder.put("EIP158", createSchedule(new StubGenesisConfigOptions().eip158Block(0)));
builder.put("EIP158ToByzantiumAt5", createSchedule(new StubGenesisConfigOptions().eip158Block(0).byzantiumBlock(5)));
builder.put("Byzantium", createSchedule(new StubGenesisConfigOptions().byzantiumBlock(0)));
builder.put("Constantinople", createSchedule(new StubGenesisConfigOptions().constantinopleBlock(0)));
builder.put("ConstantinopleFix", createSchedule(new StubGenesisConfigOptions().petersburgBlock(0)));
builder.put("Petersburg", createSchedule(new StubGenesisConfigOptions().petersburgBlock(0)));
builder.put("Istanbul", createSchedule(new StubGenesisConfigOptions().istanbulBlock(0)));
builder.put("MuirGlacier", createSchedule(new StubGenesisConfigOptions().muirGlacierBlock(0)));
builder.put("Berlin", createSchedule(new StubGenesisConfigOptions().berlinBlock(0)));
builder.put("London", createSchedule(new StubGenesisConfigOptions().londonBlock(0)));
builder.put("ArrowGlacier", createSchedule(new StubGenesisConfigOptions().arrowGlacierBlock(0)));
return new ReferenceTestProtocolSchedules(builder.build());
}
use of org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule in project besu by hyperledger.
the class BlockchainReferenceTestTools method executeTest.
public static void executeTest(final BlockchainReferenceTestCaseSpec spec) {
final BlockHeader genesisBlockHeader = spec.getGenesisBlockHeader();
final MutableWorldState worldState = spec.getWorldStateArchive().getMutable(genesisBlockHeader.getStateRoot(), genesisBlockHeader.getHash()).get();
assertThat(worldState.rootHash()).isEqualTo(genesisBlockHeader.getStateRoot());
final ProtocolSchedule schedule = REFERENCE_TEST_PROTOCOL_SCHEDULES.getByName(spec.getNetwork());
final MutableBlockchain blockchain = spec.getBlockchain();
final ProtocolContext context = spec.getProtocolContext();
for (final BlockchainReferenceTestCaseSpec.CandidateBlock candidateBlock : spec.getCandidateBlocks()) {
if (!candidateBlock.isExecutable()) {
return;
}
try {
final Block block = candidateBlock.getBlock();
final ProtocolSpec protocolSpec = schedule.getByBlockNumber(block.getHeader().getNumber());
final BlockImporter blockImporter = protocolSpec.getBlockImporter();
final HeaderValidationMode validationMode = "NoProof".equalsIgnoreCase(spec.getSealEngine()) ? HeaderValidationMode.LIGHT : HeaderValidationMode.FULL;
final boolean imported = blockImporter.importBlock(context, block, validationMode, validationMode);
assertThat(imported).isEqualTo(candidateBlock.isValid());
} catch (final RLPException e) {
assertThat(candidateBlock.isValid()).isFalse();
}
}
Assertions.assertThat(blockchain.getChainHeadHash()).isEqualTo(spec.getLastBlockHash());
}
Aggregations