From 690a2ea81e2bf62508ff16675cd7dbaeb006fa83 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Thu, 2 May 2024 15:47:59 +0200 Subject: [PATCH] Refactor genesis config file and options (#7012) Signed-off-by: Fabio Di Fabio --- .../dsl/node/ThreadBesuNodeRunner.java | 9 +- .../org/hyperledger/besu/RunnerBuilder.java | 10 +- .../org/hyperledger/besu/cli/BesuCommand.java | 150 ++++++++-------- .../besu/cli/config/EthNetworkConfig.java | 153 +++++------------ .../besu/controller/BesuController.java | 51 ++---- .../controller/BesuControllerBuilder.java | 64 +++---- .../CliqueBesuControllerBuilder.java | 6 +- ...onsensusScheduleBesuControllerBuilder.java | 11 +- .../controller/IbftBesuControllerBuilder.java | 12 +- .../MainnetBesuControllerBuilder.java | 5 +- .../MergeBesuControllerBuilder.java | 16 +- .../controller/QbftBesuControllerBuilder.java | 10 +- .../TransitionBesuControllerBuilder.java | 11 +- .../hyperledger/besu/PrivacyReorgTest.java | 5 +- .../org/hyperledger/besu/PrivacyTest.java | 5 +- .../hyperledger/besu/RunnerBuilderTest.java | 8 +- .../java/org/hyperledger/besu/RunnerTest.java | 11 +- .../chainexport/RlpBlockExporterTest.java | 5 +- .../chainimport/JsonBlockImporterTest.java | 2 +- .../chainimport/RlpBlockImporterTest.java | 12 +- .../hyperledger/besu/cli/BesuCommandTest.java | 161 +++++++++--------- .../cli/CascadingDefaultProviderTest.java | 26 +-- .../besu/cli/CommandTestAbstract.java | 7 +- .../besu/cli/config/EthNetworkConfigTest.java | 51 +++--- .../besu/cli/options/MiningOptionsTest.java | 2 +- .../blocks/BlocksSubCommandTest.java | 2 +- .../AbstractBftBesuControllerBuilderTest.java | 4 +- .../besu/controller/BesuControllerTest.java | 53 +++--- ...nsusScheduleBesuControllerBuilderTest.java | 3 +- .../IbftBesuControllerBuilderTest.java | 2 +- .../QbftBesuControllerBuilderTest.java | 2 +- ...rmissioningConfigurationValidatorTest.java | 4 +- .../besu/config/GenesisConfigFile.java | 98 ++++++----- .../besu/config/JsonGenesisConfigOptions.java | 15 ++ .../org/hyperledger/besu/config/JsonUtil.java | 28 ++- .../besu/config/GenesisConfigFileTest.java | 22 +-- .../hyperledger/besu/config/JsonUtilTest.java | 22 +++ .../MergeGenesisConfigHelper.java | 8 +- .../qbft/support/TestContextBuilder.java | 7 +- .../AbstractBlockTransactionSelectorTest.java | 2 +- ...FeeMarketBlockTransactionSelectorTest.java | 3 +- ...FeeMarketBlockTransactionSelectorTest.java | 3 +- .../ethereum/core/BlockchainSetupUtil.java | 12 +- .../fixed/FixedProtocolScheduleTest.java | 2 +- .../mainnet/MainnetProtocolScheduleTest.java | 10 +- .../bonsai/AbstractIsolationTests.java | 6 +- .../eth/messages/BlockBodiesMessageTest.java | 2 +- .../eth/messages/BlockHeadersMessageTest.java | 2 +- .../eth/sync/ChainHeadTrackerTest.java | 2 +- .../ethereum/eth/transactions/TestNode.java | 4 +- ...rtContractPermissioningControllerTest.java | 10 +- 51 files changed, 513 insertions(+), 618 deletions(-) diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java index 1493df6f0f..073e0bd1d1 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java @@ -74,7 +74,6 @@ import org.hyperledger.besu.services.TransactionSimulationServiceImpl; import java.io.File; import java.nio.file.Path; import java.time.Clock; -import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; @@ -213,14 +212,16 @@ public class ThreadBesuNodeRunner implements BesuNodeRunner { final EthNetworkConfig.Builder networkConfigBuilder = new EthNetworkConfig.Builder(EthNetworkConfig.getNetworkConfig(network)) .setBootNodes(bootnodes); - node.getConfiguration().getGenesisConfig().ifPresent(networkConfigBuilder::setGenesisConfig); + node.getConfiguration() + .getGenesisConfig() + .map(GenesisConfigFile::fromConfig) + .ifPresent(networkConfigBuilder::setGenesisConfigFile); final EthNetworkConfig ethNetworkConfig = networkConfigBuilder.build(); final SynchronizerConfiguration synchronizerConfiguration = new SynchronizerConfiguration.Builder().build(); final BesuControllerBuilder builder = new BesuController.Builder() - .fromEthNetworkConfig( - ethNetworkConfig, Collections.emptyMap(), synchronizerConfiguration.getSyncMode()); + .fromEthNetworkConfig(ethNetworkConfig, synchronizerConfiguration.getSyncMode()); final KeyValueStorageProvider storageProvider = new KeyValueStorageProviderBuilder() diff --git a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java index 6379e2c1a6..f38d362fde 100644 --- a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java @@ -603,15 +603,15 @@ public class RunnerBuilder { .setAdvertisedHost(p2pAdvertisedHost); if (discovery) { final List bootstrap; - if (ethNetworkConfig.getBootNodes() == null) { - bootstrap = EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET).getBootNodes(); + if (ethNetworkConfig.bootNodes() == null) { + bootstrap = EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET).bootNodes(); } else { - bootstrap = ethNetworkConfig.getBootNodes(); + bootstrap = ethNetworkConfig.bootNodes(); } discoveryConfiguration.setBootnodes(bootstrap); LOG.info("Resolved {} bootnodes.", bootstrap.size()); LOG.debug("Bootnodes = {}", bootstrap); - discoveryConfiguration.setDnsDiscoveryURL(ethNetworkConfig.getDnsDiscoveryUrl()); + discoveryConfiguration.setDnsDiscoveryURL(ethNetworkConfig.dnsDiscoveryUrl()); discoveryConfiguration.setDiscoveryV5Enabled( networkingConfiguration.getDiscovery().isDiscoveryV5Enabled()); discoveryConfiguration.setFilterOnEnrForkId( @@ -1209,7 +1209,7 @@ public class RunnerBuilder { new JsonRpcMethodsFactory() .methods( BesuInfo.nodeName(identityString), - ethNetworkConfig.getNetworkId(), + ethNetworkConfig.networkId(), besuController.getGenesisConfigOptions(), network, blockchainQueries, diff --git a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java index 2d147be517..e3419f594c 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -16,7 +16,6 @@ package org.hyperledger.besu.cli; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; -import static java.nio.charset.StandardCharsets.UTF_8; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static org.hyperledger.besu.cli.DefaultCommandValues.getDefaultBesuDataPath; @@ -207,6 +206,7 @@ import java.math.BigInteger; import java.net.InetAddress; import java.net.SocketException; import java.net.URI; +import java.net.URL; import java.net.UnknownHostException; import java.nio.file.Path; import java.time.Clock; @@ -231,7 +231,6 @@ import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Strings; import com.google.common.base.Suppliers; import com.google.common.collect.ImmutableMap; -import com.google.common.io.Resources; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; import io.vertx.core.json.DecodeException; @@ -324,7 +323,10 @@ public class BesuCommand implements DefaultCommandValues, Runnable { private final Set allocatedPorts = new HashSet<>(); private final PkiBlockCreationConfigurationProvider pkiBlockCreationConfigProvider; - private GenesisConfigOptions genesisConfigOptions; + private final Supplier genesisConfigFileSupplier = + Suppliers.memoize(this::readGenesisConfigFile); + private final Supplier genesisConfigOptionsSupplier = + Suppliers.memoize(this::readGenesisConfigOptions); private RocksDBPlugin rocksDBPlugin; @@ -1130,10 +1132,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable { try { configureLogging(true); - if (genesisFile != null) { - genesisConfigOptions = readGenesisConfigOptions(); - } - // set merge config on the basis of genesis config setMergeConfigOptions(); @@ -1292,8 +1290,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable { return new KeyPairSecurityModule(loadKeyPair(nodePrivateKeyFileOption.getNodePrivateKeyFile())); } - // loadKeyPair() is public because it is accessed by subcommands - /** * Load key pair from private key. Visible to be accessed by subcommands. * @@ -1473,8 +1469,8 @@ public class BesuCommand implements DefaultCommandValues, Runnable { logger.info("Using the Java implementation of the blake2bf algorithm"); } - if (getActualGenesisConfigOptions().getCancunTime().isPresent() - || getActualGenesisConfigOptions().getPragueTime().isPresent()) { + if (genesisConfigOptionsSupplier.get().getCancunTime().isPresent() + || genesisConfigOptionsSupplier.get().getPragueTime().isPresent()) { if (kzgTrustedSetupFile != null) { KZGPointEvalPrecompiledContract.init(kzgTrustedSetupFile); } else { @@ -1504,16 +1500,33 @@ public class BesuCommand implements DefaultCommandValues, Runnable { validateDataStorageOptions(); validateGraphQlOptions(); validateApiOptions(); + validateConsensusSyncCompatibilityOptions(); p2pTLSConfigOptions.checkP2PTLSOptionsDependencies(logger, commandLine); pkiBlockCreationOptions.checkPkiBlockCreationOptionsDependencies(logger, commandLine); } + private void validateConsensusSyncCompatibilityOptions() { + // snap and checkpoint can't be used with BFT but can for clique + if (genesisConfigOptionsSupplier.get().isIbftLegacy() + || genesisConfigOptionsSupplier.get().isIbft2() + || genesisConfigOptionsSupplier.get().isQbft()) { + final String errorSuffix = "can't be used with BFT networks"; + if (SyncMode.CHECKPOINT.equals(syncMode) || SyncMode.X_CHECKPOINT.equals(syncMode)) { + throw new ParameterException( + commandLine, String.format("%s %s", "Checkpoint sync", errorSuffix)); + } + if (syncMode == SyncMode.SNAP || syncMode == SyncMode.X_SNAP) { + throw new ParameterException(commandLine, String.format("%s %s", "Snap sync", errorSuffix)); + } + } + } + private void validateApiOptions() { apiConfigurationOptions.validate(commandLine, logger); } private void validateTransactionPoolOptions() { - transactionPoolOptions.validate(commandLine, getActualGenesisConfigOptions()); + transactionPoolOptions.validate(commandLine, genesisConfigOptionsSupplier.get()); } private void validateDataStorageOptions() { @@ -1534,7 +1547,8 @@ public class BesuCommand implements DefaultCommandValues, Runnable { } private void validateMiningParams() { - miningOptions.validate(commandLine, getActualGenesisConfigOptions(), isMergeEnabled(), logger); + miningOptions.validate( + commandLine, genesisConfigOptionsSupplier.get(), isMergeEnabled(), logger); } /** @@ -1644,29 +1658,20 @@ public class BesuCommand implements DefaultCommandValues, Runnable { } } - private GenesisConfigOptions readGenesisConfigOptions() { + private GenesisConfigFile readGenesisConfigFile() { + return genesisFile != null + ? GenesisConfigFile.fromSource(genesisConfigSource(genesisFile)) + : GenesisConfigFile.fromResource( + Optional.ofNullable(network).orElse(MAINNET).getGenesisFile()); + } + private GenesisConfigOptions readGenesisConfigOptions() { try { - final GenesisConfigFile genesisConfigFile = GenesisConfigFile.fromConfig(genesisConfig()); - genesisConfigOptions = genesisConfigFile.getConfigOptions(genesisConfigOverrides); + return genesisConfigFileSupplier.get().getConfigOptions(genesisConfigOverrides); } catch (final Exception e) { throw new ParameterException( this.commandLine, "Unable to load genesis file. " + e.getCause()); } - // snap and checkpoint can't be used with BFT but can for clique - if (genesisConfigOptions.isIbftLegacy() - || genesisConfigOptions.isIbft2() - || genesisConfigOptions.isQbft()) { - final String errorSuffix = "can't be used with BFT networks"; - if (SyncMode.CHECKPOINT.equals(syncMode) || SyncMode.X_CHECKPOINT.equals(syncMode)) { - throw new ParameterException( - commandLine, String.format("%s %s", "Checkpoint sync", errorSuffix)); - } - if (syncMode == SyncMode.SNAP || syncMode == SyncMode.X_SNAP) { - throw new ParameterException(commandLine, String.format("%s %s", "Snap sync", errorSuffix)); - } - } - return genesisConfigOptions; } private void issueOptionWarnings() { @@ -1765,7 +1770,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable { permissioningConfiguration = permissioningConfiguration(); staticNodes = loadStaticNodes(); - final List enodeURIs = ethNetworkConfig.getBootNodes(); + final List enodeURIs = ethNetworkConfig.bootNodes(); permissioningConfiguration .flatMap(PermissioningConfiguration::getLocalConfig) .ifPresent(p -> ensureAllNodesAreInAllowlist(enodeURIs, p)); @@ -1842,8 +1847,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable { getMiningParameters()); final KeyValueStorageProvider storageProvider = keyValueStorageProvider(keyValueStorageName); return controllerBuilderFactory - .fromEthNetworkConfig( - updateNetworkConfig(network), genesisConfigOverrides, getDefaultSyncModeIfNotSet()) + .fromEthNetworkConfig(updateNetworkConfig(network), getDefaultSyncModeIfNotSet()) .synchronizerConfiguration(buildSyncConfig()) .ethProtocolConfiguration(unstableEthProtocolOptions.toDomainObject()) .networkConfiguration(unstableNetworkingOptions.toDomainObject()) @@ -1859,7 +1863,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable { .clock(Clock.systemUTC()) .isRevertReasonEnabled(isRevertReasonEnabled) .storageProvider(storageProvider) - .genesisConfigOverrides(genesisConfigOverrides) .gasLimitCalculator( getMiningParameters().getTargetGasLimit().isPresent() ? new FrontierTargetingGasLimitCalculator() @@ -2148,7 +2151,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable { .from(txPoolConf) .saveFile((dataPath.resolve(txPoolConf.getSaveFile().getPath()).toFile())); - if (getActualGenesisConfigOptions().isZeroBaseFee()) { + if (genesisConfigOptionsSupplier.get().isZeroBaseFee()) { logger.info( "Forcing price bump for transaction replacement to 0, since we are on a zero basefee network"); txPoolConfBuilder.priceBump(Percentage.ZERO); @@ -2185,7 +2188,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable { if (miningParameters == null) { miningOptions.setTransactionSelectionService(transactionSelectionServiceImpl); miningParameters = miningOptions.toDomainObject(); - getGenesisBlockPeriodSeconds(getActualGenesisConfigOptions()) + getGenesisBlockPeriodSeconds(genesisConfigOptionsSupplier.get()) .ifPresent(miningParameters::setBlockPeriodSeconds); initMiningParametersMetrics(miningParameters); } @@ -2337,16 +2340,14 @@ public class BesuCommand implements DefaultCommandValues, Runnable { + "refer to CLI reference for more details about this constraint."); } - builder.setGenesisConfig(genesisConfig()); - if (networkId == null) { // If no chain id is found in the genesis, use mainnet network id try { builder.setNetworkId( - getGenesisConfigFile() - .getConfigOptions(genesisConfigOverrides) + genesisConfigOptionsSupplier + .get() .getChainId() - .orElse(EthNetworkConfig.getNetworkConfig(MAINNET).getNetworkId())); + .orElse(EthNetworkConfig.getNetworkConfig(MAINNET).networkId())); } catch (final DecodeException e) { throw new ParameterException( this.commandLine, String.format("Unable to parse genesis file %s.", genesisFile), e); @@ -2364,18 +2365,20 @@ public class BesuCommand implements DefaultCommandValues, Runnable { builder.setDnsDiscoveryUrl(null); } + builder.setGenesisConfigFile(genesisConfigFileSupplier.get()); + + if (networkId != null) { + builder.setNetworkId(networkId); + } + if (p2PDiscoveryOptionGroup.discoveryDnsUrl != null) { builder.setDnsDiscoveryUrl(p2PDiscoveryOptionGroup.discoveryDnsUrl); - } else if (genesisConfigOptions != null) { + } else { final Optional discoveryDnsUrlFromGenesis = - genesisConfigOptions.getDiscoveryOptions().getDiscoveryDnsUrl(); + genesisConfigOptionsSupplier.get().getDiscoveryOptions().getDiscoveryDnsUrl(); discoveryDnsUrlFromGenesis.ifPresent(builder::setDnsDiscoveryUrl); } - if (networkId != null) { - builder.setNetworkId(networkId); - } - List listBootNodes = null; if (p2PDiscoveryOptionGroup.bootNodes != null) { try { @@ -2383,9 +2386,9 @@ public class BesuCommand implements DefaultCommandValues, Runnable { } catch (final IllegalArgumentException e) { throw new ParameterException(commandLine, e.getMessage()); } - } else if (genesisConfigOptions != null) { + } else { final Optional> bootNodesFromGenesis = - genesisConfigOptions.getDiscoveryOptions().getBootNodes(); + genesisConfigOptionsSupplier.get().getDiscoveryOptions().getBootNodes(); if (bootNodesFromGenesis.isPresent()) { listBootNodes = buildEnodes(bootNodesFromGenesis.get(), getEnodeDnsConfiguration()); } @@ -2400,28 +2403,15 @@ public class BesuCommand implements DefaultCommandValues, Runnable { return builder.build(); } - private GenesisConfigFile getGenesisConfigFile() { - return GenesisConfigFile.fromConfig(genesisConfig()); - } - - private String genesisConfig() { + private URL genesisConfigSource(final File genesisFile) { try { - return Resources.toString(genesisFile.toURI().toURL(), UTF_8); + return genesisFile.toURI().toURL(); } catch (final IOException e) { throw new ParameterException( this.commandLine, String.format("Unable to load genesis URL %s.", genesisFile), e); } } - private static String genesisConfig(final NetworkName networkName) { - try (final InputStream genesisFileInputStream = - EthNetworkConfig.class.getResourceAsStream(networkName.getGenesisFile())) { - return new String(genesisFileInputStream.readAllBytes(), UTF_8); - } catch (final IOException | NullPointerException e) { - throw new IllegalStateException(e); - } - } - /** * Returns data directory used by Besu. Visible as it is accessed by other subcommands. * @@ -2635,26 +2625,21 @@ public class BesuCommand implements DefaultCommandValues, Runnable { if (genesisFile == null) { return Optional.empty(); } - return genesisConfigOptions.getEcCurve(); + return genesisConfigOptionsSupplier.get().getEcCurve(); } /** - * Return the genesis config options after applying any specified config overrides + * Return the genesis config options * - * @return the genesis config options after applying any specified config overrides + * @return the genesis config options */ - protected GenesisConfigOptions getActualGenesisConfigOptions() { - return Optional.ofNullable(genesisConfigOptions) - .orElseGet( - () -> - GenesisConfigFile.fromConfig( - genesisConfig(Optional.ofNullable(network).orElse(MAINNET))) - .getConfigOptions(genesisConfigOverrides)); + protected GenesisConfigOptions getGenesisConfigOptions() { + return genesisConfigOptionsSupplier.get(); } private void setMergeConfigOptions() { MergeConfigOptions.setMergeEnabled( - getActualGenesisConfigOptions().getTerminalTotalDifficulty().isPresent()); + genesisConfigOptionsSupplier.get().getTerminalTotalDifficulty().isPresent()); } /** Set ignorable segments in RocksDB Storage Provider plugin. */ @@ -2665,11 +2650,12 @@ public class BesuCommand implements DefaultCommandValues, Runnable { } private void validatePostMergeCheckpointBlockRequirements() { - final GenesisConfigOptions genesisOptions = getActualGenesisConfigOptions(); final SynchronizerConfiguration synchronizerConfiguration = unstableSynchronizerOptions.toDomainObject().build(); - final Optional terminalTotalDifficulty = genesisOptions.getTerminalTotalDifficulty(); - final CheckpointConfigOptions checkpointConfigOptions = genesisOptions.getCheckpointOptions(); + final Optional terminalTotalDifficulty = + genesisConfigOptionsSupplier.get().getTerminalTotalDifficulty(); + final CheckpointConfigOptions checkpointConfigOptions = + genesisConfigOptionsSupplier.get().getCheckpointOptions(); if (synchronizerConfiguration.isCheckpointPostMergeEnabled()) { if (!checkpointConfigOptions.isValid()) { throw new InvalidConfigurationException( @@ -2677,15 +2663,13 @@ public class BesuCommand implements DefaultCommandValues, Runnable { } terminalTotalDifficulty.ifPresentOrElse( ttd -> { - if (UInt256.fromHexString( - genesisOptions.getCheckpointOptions().getTotalDifficulty().get()) + if (UInt256.fromHexString(checkpointConfigOptions.getTotalDifficulty().get()) .equals(UInt256.ZERO) && ttd.equals(UInt256.ZERO)) { throw new InvalidConfigurationException( "PoS checkpoint sync can't be used with TTD = 0 and checkpoint totalDifficulty = 0"); } - if (UInt256.fromHexString( - genesisOptions.getCheckpointOptions().getTotalDifficulty().get()) + if (UInt256.fromHexString(checkpointConfigOptions.getTotalDifficulty().get()) .lessThan(ttd)) { throw new InvalidConfigurationException( "PoS checkpoint sync requires a block with total difficulty greater or equal than the TTD"); @@ -2742,7 +2726,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable { if (genesisFile != null) { builder.setCustomGenesis(genesisFile.getAbsolutePath()); } - builder.setNetworkId(ethNetworkConfig.getNetworkId()); + builder.setNetworkId(ethNetworkConfig.networkId()); builder .setDataStorage(dataStorageOptions.normalizeDataStorageFormat()) diff --git a/besu/src/main/java/org/hyperledger/besu/cli/config/EthNetworkConfig.java b/besu/src/main/java/org/hyperledger/besu/cli/config/EthNetworkConfig.java index 3af85016c8..d591637e33 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/config/EthNetworkConfig.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/config/EthNetworkConfig.java @@ -14,8 +14,6 @@ */ package org.hyperledger.besu.cli.config; -import static java.nio.charset.StandardCharsets.UTF_8; - import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.ethereum.p2p.peers.EnodeURLImpl; @@ -24,6 +22,8 @@ import org.hyperledger.besu.plugin.data.EnodeURL; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; +import java.net.URL; +import java.nio.charset.StandardCharsets; import java.util.Collections; import java.util.List; import java.util.Objects; @@ -31,102 +31,25 @@ import java.util.Optional; import java.util.stream.Collectors; /** The Eth network config. */ -public class EthNetworkConfig { - - private final String genesisConfig; - private final BigInteger networkId; - private final List bootNodes; - private final String dnsDiscoveryUrl; +public record EthNetworkConfig( + GenesisConfigFile genesisConfigFile, + BigInteger networkId, + List bootNodes, + String dnsDiscoveryUrl) { /** - * Instantiates a new Eth network config. + * Validate parameters on new record creation * - * @param genesisConfig the genesis config + * @param genesisConfigFile the genesis config * @param networkId the network id * @param bootNodes the boot nodes * @param dnsDiscoveryUrl the dns discovery url */ - public EthNetworkConfig( - final String genesisConfig, - final BigInteger networkId, - final List bootNodes, - final String dnsDiscoveryUrl) { - Objects.requireNonNull(genesisConfig); + @SuppressWarnings( + "MethodInputParametersMustBeFinal") // needed since record constructors are not yet supported + public EthNetworkConfig { + Objects.requireNonNull(genesisConfigFile); Objects.requireNonNull(bootNodes); - this.genesisConfig = genesisConfig; - this.networkId = networkId; - this.bootNodes = bootNodes; - this.dnsDiscoveryUrl = dnsDiscoveryUrl; - } - - /** - * Gets genesis config. - * - * @return the genesis config - */ - public String getGenesisConfig() { - return genesisConfig; - } - - /** - * Gets network id. - * - * @return the network id - */ - public BigInteger getNetworkId() { - return networkId; - } - - /** - * Gets boot nodes. - * - * @return the boot nodes - */ - public List getBootNodes() { - return bootNodes; - } - - /** - * Gets dns discovery url. - * - * @return the dns discovery url - */ - public String getDnsDiscoveryUrl() { - return dnsDiscoveryUrl; - } - - @Override - public boolean equals(final Object o) { - if (this == o) { - return true; - } - if (o == null || getClass() != o.getClass()) { - return false; - } - final EthNetworkConfig that = (EthNetworkConfig) o; - return networkId.equals(that.networkId) - && Objects.equals(genesisConfig, that.genesisConfig) - && Objects.equals(bootNodes, that.bootNodes) - && Objects.equals(dnsDiscoveryUrl, that.dnsDiscoveryUrl); - } - - @Override - public int hashCode() { - return Objects.hash(genesisConfig, networkId, bootNodes, dnsDiscoveryUrl); - } - - @Override - public String toString() { - return "EthNetworkConfig{" - + "genesisConfig=" - + genesisConfig - + ", networkId=" - + networkId - + ", bootNodes=" - + bootNodes - + ", dnsDiscoveryUrl=" - + dnsDiscoveryUrl - + '}'; } /** @@ -136,9 +59,9 @@ public class EthNetworkConfig { * @return the network config */ public static EthNetworkConfig getNetworkConfig(final NetworkName networkName) { - final String genesisContent = jsonConfig(networkName.getGenesisFile()); - final GenesisConfigOptions genesisConfigOptions = - GenesisConfigFile.fromConfig(genesisContent).getConfigOptions(); + final URL genesisSource = jsonConfigSource(networkName.getGenesisFile()); + final GenesisConfigFile genesisConfigFile = GenesisConfigFile.fromSource(genesisSource); + final GenesisConfigOptions genesisConfigOptions = genesisConfigFile.getConfigOptions(); final Optional> rawBootNodes = genesisConfigOptions.getDiscoveryOptions().getBootNodes(); final List bootNodes = @@ -148,36 +71,36 @@ public class EthNetworkConfig { strings.stream().map(EnodeURLImpl::fromString).collect(Collectors.toList())) .orElse(Collections.emptyList()); return new EthNetworkConfig( - genesisContent, + genesisConfigFile, networkName.getNetworkId(), bootNodes, genesisConfigOptions.getDiscoveryOptions().getDiscoveryDnsUrl().orElse(null)); } - private static String jsonConfig(final String resourceName) { - try (final InputStream genesisFileInputStream = - EthNetworkConfig.class.getResourceAsStream(resourceName)) { - return new String(genesisFileInputStream.readAllBytes(), UTF_8); - } catch (IOException | NullPointerException e) { - throw new IllegalStateException(e); - } + private static URL jsonConfigSource(final String resourceName) { + return EthNetworkConfig.class.getResource(resourceName); } /** * Json config string. * - * @param network the network - * @return the string + * @param network the named network + * @return the json string */ public static String jsonConfig(final NetworkName network) { - return jsonConfig(network.getGenesisFile()); + try (final InputStream genesisFileInputStream = + EthNetworkConfig.class.getResourceAsStream(network.getGenesisFile())) { + return new String(genesisFileInputStream.readAllBytes(), StandardCharsets.UTF_8); + } catch (IOException | NullPointerException e) { + throw new IllegalStateException(e); + } } /** The type Builder. */ public static class Builder { private String dnsDiscoveryUrl; - private String genesisConfig; + private GenesisConfigFile genesisConfigFile; private BigInteger networkId; private List bootNodes; @@ -187,20 +110,20 @@ public class EthNetworkConfig { * @param ethNetworkConfig the eth network config */ public Builder(final EthNetworkConfig ethNetworkConfig) { - this.genesisConfig = ethNetworkConfig.genesisConfig; + this.genesisConfigFile = ethNetworkConfig.genesisConfigFile; this.networkId = ethNetworkConfig.networkId; this.bootNodes = ethNetworkConfig.bootNodes; this.dnsDiscoveryUrl = ethNetworkConfig.dnsDiscoveryUrl; } /** - * Sets genesis config. + * Sets genesis config file. * - * @param genesisConfig the genesis config - * @return the genesis config + * @param genesisConfigFile the genesis config + * @return this builder */ - public Builder setGenesisConfig(final String genesisConfig) { - this.genesisConfig = genesisConfig; + public Builder setGenesisConfigFile(final GenesisConfigFile genesisConfigFile) { + this.genesisConfigFile = genesisConfigFile; return this; } @@ -208,7 +131,7 @@ public class EthNetworkConfig { * Sets network id. * * @param networkId the network id - * @return the network id + * @return this builder */ public Builder setNetworkId(final BigInteger networkId) { this.networkId = networkId; @@ -219,7 +142,7 @@ public class EthNetworkConfig { * Sets boot nodes. * * @param bootNodes the boot nodes - * @return the boot nodes + * @return this builder */ public Builder setBootNodes(final List bootNodes) { this.bootNodes = bootNodes; @@ -230,7 +153,7 @@ public class EthNetworkConfig { * Sets dns discovery url. * * @param dnsDiscoveryUrl the dns discovery url - * @return the dns discovery url + * @return this builder */ public Builder setDnsDiscoveryUrl(final String dnsDiscoveryUrl) { this.dnsDiscoveryUrl = dnsDiscoveryUrl; @@ -243,7 +166,7 @@ public class EthNetworkConfig { * @return the eth network config */ public EthNetworkConfig build() { - return new EthNetworkConfig(genesisConfig, networkId, bootNodes, dnsDiscoveryUrl); + return new EthNetworkConfig(genesisConfigFile, networkId, bootNodes, dnsDiscoveryUrl); } } } diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java index 2849846f21..6c223674d5 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java @@ -42,7 +42,6 @@ import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; import java.io.Closeable; import java.io.IOException; import java.util.Collection; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -317,50 +316,29 @@ public class BesuController implements java.io.Closeable { * From eth network config besu controller builder. * * @param ethNetworkConfig the eth network config - * @param genesisConfigOverrides the genesis config overrides * @param syncMode The sync mode * @return the besu controller builder */ public BesuControllerBuilder fromEthNetworkConfig( - final EthNetworkConfig ethNetworkConfig, - final Map genesisConfigOverrides, - final SyncMode syncMode) { - return fromGenesisConfig( - GenesisConfigFile.fromConfig(ethNetworkConfig.getGenesisConfig()), - genesisConfigOverrides, - syncMode) - .networkId(ethNetworkConfig.getNetworkId()); + final EthNetworkConfig ethNetworkConfig, final SyncMode syncMode) { + return fromGenesisFile(ethNetworkConfig.genesisConfigFile(), syncMode) + .networkId(ethNetworkConfig.networkId()); } /** * From genesis config besu controller builder. * - * @param genesisConfig the genesis config - * @param syncMode The Sync Mode + * @param genesisConfigFile the genesis config file + * @param syncMode the sync mode * @return the besu controller builder */ - public BesuControllerBuilder fromGenesisConfig( - final GenesisConfigFile genesisConfig, final SyncMode syncMode) { - return fromGenesisConfig(genesisConfig, Collections.emptyMap(), syncMode); - } - - /** - * From genesis config besu controller builder. - * - * @param genesisConfig the genesis config - * @param genesisConfigOverrides the genesis config overrides - * @return the besu controller builder - */ - BesuControllerBuilder fromGenesisConfig( - final GenesisConfigFile genesisConfig, - final Map genesisConfigOverrides, - final SyncMode syncMode) { - final GenesisConfigOptions configOptions = - genesisConfig.getConfigOptions(genesisConfigOverrides); + public BesuControllerBuilder fromGenesisFile( + final GenesisConfigFile genesisConfigFile, final SyncMode syncMode) { final BesuControllerBuilder builder; + final var configOptions = genesisConfigFile.getConfigOptions(); if (configOptions.isConsensusMigration()) { - return createConsensusScheduleBesuControllerBuilder(genesisConfig, configOptions); + return createConsensusScheduleBesuControllerBuilder(genesisConfigFile); } if (configOptions.getPowAlgorithm() != PowAlgorithm.UNSUPPORTED) { @@ -382,21 +360,22 @@ public class BesuController implements java.io.Closeable { if (configOptions.getTerminalTotalDifficulty().isPresent()) { // Enable start with vanilla MergeBesuControllerBuilder for PoS checkpoint block if (isCheckpointSync(syncMode) && isCheckpointPoSBlock(configOptions)) { - return new MergeBesuControllerBuilder().genesisConfigFile(genesisConfig); + return new MergeBesuControllerBuilder().genesisConfigFile(genesisConfigFile); } else { // TODO this should be changed to vanilla MergeBesuControllerBuilder and the Transition* // series of classes removed after we successfully transition to PoS // https://github.com/hyperledger/besu/issues/2897 return new TransitionBesuControllerBuilder(builder, new MergeBesuControllerBuilder()) - .genesisConfigFile(genesisConfig); + .genesisConfigFile(genesisConfigFile); } - } else return builder.genesisConfigFile(genesisConfig); + } else return builder.genesisConfigFile(genesisConfigFile); } private BesuControllerBuilder createConsensusScheduleBesuControllerBuilder( - final GenesisConfigFile genesisConfig, final GenesisConfigOptions configOptions) { + final GenesisConfigFile genesisConfigFile) { final Map besuControllerBuilderSchedule = new HashMap<>(); + final var configOptions = genesisConfigFile.getConfigOptions(); final BesuControllerBuilder originalControllerBuilder; if (configOptions.isIbft2()) { @@ -415,7 +394,7 @@ public class BesuController implements java.io.Closeable { besuControllerBuilderSchedule.put(qbftBlock, new QbftBesuControllerBuilder()); return new ConsensusScheduleBesuControllerBuilder(besuControllerBuilderSchedule) - .genesisConfigFile(genesisConfig); + .genesisConfigFile(genesisConfigFile); } private Long readQbftStartBlockConfig(final QbftConfigOptions qbftConfigOptions) { diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java index 7061af4221..a3c243a656 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java @@ -117,15 +117,11 @@ import org.slf4j.LoggerFactory; public abstract class BesuControllerBuilder implements MiningParameterOverrides { private static final Logger LOG = LoggerFactory.getLogger(BesuControllerBuilder.class); - private GenesisConfigFile genesisConfig; - private Map genesisConfigOverrides = Collections.emptyMap(); + /** The genesis file */ + protected GenesisConfigFile genesisConfigFile; - /** The Config options supplier. */ - protected Supplier configOptionsSupplier = - () -> - Optional.ofNullable(genesisConfig) - .map(conf -> conf.getConfigOptions(genesisConfigOverrides)) - .orElseThrow(); + /** The genesis config options; */ + protected GenesisConfigOptions genesisConfigOptions; /** The is genesis state hash from data. */ protected boolean genesisStateHashCacheEnabled; @@ -238,7 +234,8 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides * @return the besu controller builder */ public BesuControllerBuilder genesisConfigFile(final GenesisConfigFile genesisConfig) { - this.genesisConfig = genesisConfig; + this.genesisConfigFile = genesisConfig; + this.genesisConfigOptions = genesisConfig.getConfigOptions(); return this; } @@ -402,18 +399,6 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides return this; } - /** - * Genesis config overrides besu controller builder. - * - * @param genesisConfigOverrides the genesis config overrides - * @return the besu controller builder - */ - public BesuControllerBuilder genesisConfigOverrides( - final Map genesisConfigOverrides) { - this.genesisConfigOverrides = genesisConfigOverrides; - return this; - } - /** * Gas limit calculator besu controller builder. * @@ -544,7 +529,8 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides * @return the besu controller */ public BesuController build() { - checkNotNull(genesisConfig, "Missing genesis config"); + checkNotNull(genesisConfigFile, "Missing genesis config file"); + checkNotNull(genesisConfigOptions, "Missing genesis config options"); checkNotNull(syncConfig, "Missing sync config"); checkNotNull(ethereumWireProtocolConfiguration, "Missing ethereum protocol configuration"); checkNotNull(networkId, "Missing network ID"); @@ -574,10 +560,10 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides if (genesisStateHash.isPresent()) { genesisState = - GenesisState.fromConfig(genesisStateHash.get(), genesisConfig, protocolSchedule); + GenesisState.fromConfig(genesisStateHash.get(), genesisConfigFile, protocolSchedule); } else { genesisState = - GenesisState.fromConfig(dataStorageConfiguration, genesisConfig, protocolSchedule); + GenesisState.fromConfig(dataStorageConfiguration, genesisConfigFile, protocolSchedule); if (variablesStorage != null) { VariablesStorage.Updater updater = variablesStorage.updater(); if (updater != null) { @@ -660,20 +646,18 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides syncConfig.getComputationParallelism(), metricsSystem); - final GenesisConfigOptions configOptions = - genesisConfig.getConfigOptions(genesisConfigOverrides); - Optional checkpoint = Optional.empty(); - if (configOptions.getCheckpointOptions().isValid()) { + if (genesisConfigOptions.getCheckpointOptions().isValid()) { checkpoint = Optional.of( ImmutableCheckpoint.builder() .blockHash( - Hash.fromHexString(configOptions.getCheckpointOptions().getHash().get())) - .blockNumber(configOptions.getCheckpointOptions().getNumber().getAsLong()) + Hash.fromHexString( + genesisConfigOptions.getCheckpointOptions().getHash().get())) + .blockNumber(genesisConfigOptions.getCheckpointOptions().getNumber().getAsLong()) .totalDifficulty( Difficulty.fromHexString( - configOptions.getCheckpointOptions().getTotalDifficulty().get())) + genesisConfigOptions.getCheckpointOptions().getTotalDifficulty().get())) .build()); } @@ -768,7 +752,7 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides protocolSchedule, protocolContext, ethProtocolManager, - configOptionsSupplier.get(), + genesisConfigOptions, subProtocolConfiguration, synchronizer, syncState, @@ -789,7 +773,6 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides final WorldStateKeyValueStorage worldStateStorage, final Blockchain blockchain, final EthScheduler scheduler) { - final GenesisConfigOptions genesisConfigOptions = configOptionsSupplier.get(); final boolean isProofOfStake = genesisConfigOptions.getTerminalTotalDifficulty().isPresent(); final TrieLogPruner trieLogPruner = @@ -849,8 +832,6 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides final SyncState syncState, final MetricsSystem metricsSystem) { - final GenesisConfigOptions genesisConfigOptions = configOptionsSupplier.get(); - if (genesisConfigOptions.getTerminalTotalDifficulty().isPresent()) { LOG.info("TTD difficulty is present, creating initial sync for PoS"); @@ -887,8 +868,7 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides * @return the full sync termination condition */ protected SyncTerminationCondition getFullSyncTerminationCondition(final Blockchain blockchain) { - return configOptionsSupplier - .get() + return genesisConfigOptions .getTerminalTotalDifficulty() .map(difficulty -> SyncTerminationCondition.difficulty(difficulty, blockchain)) .orElse(SyncTerminationCondition.never()); @@ -1020,8 +1000,8 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides mergePeerFilter, synchronizerConfiguration, scheduler, - genesisConfig.getForkBlockNumbers(), - genesisConfig.getForkTimestamps()); + genesisConfigOptions.getForkBlockNumbers(), + genesisConfigOptions.getForkBlockTimestamps()); } /** @@ -1109,14 +1089,14 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides protected List createPeerValidators(final ProtocolSchedule protocolSchedule) { final List validators = new ArrayList<>(); - final OptionalLong daoBlock = configOptionsSupplier.get().getDaoForkBlock(); + final OptionalLong daoBlock = genesisConfigOptions.getDaoForkBlock(); if (daoBlock.isPresent()) { // Setup dao validator validators.add( new DaoForkPeerValidator(protocolSchedule, metricsSystem, daoBlock.getAsLong())); } - final OptionalLong classicBlock = configOptionsSupplier.get().getClassicForkBlock(); + final OptionalLong classicBlock = genesisConfigOptions.getClassicForkBlock(); // setup classic validator if (classicBlock.isPresent()) { validators.add( @@ -1130,7 +1110,7 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides } final CheckpointConfigOptions checkpointConfigOptions = - genesisConfig.getConfigOptions(genesisConfigOverrides).getCheckpointOptions(); + genesisConfigOptions.getCheckpointOptions(); if (SyncMode.isCheckpointSync(syncConfig.getSyncMode()) && checkpointConfigOptions.isValid()) { validators.add( new CheckpointBlocksPeerValidator( diff --git a/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java index 7b13a211a7..e4a30c1dd2 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java @@ -60,11 +60,11 @@ public class CliqueBesuControllerBuilder extends BesuControllerBuilder { @Override protected void prepForBuild() { localAddress = Util.publicKeyToAddress(nodeKey.getPublicKey()); - final CliqueConfigOptions cliqueConfig = configOptionsSupplier.get().getCliqueConfigOptions(); + final CliqueConfigOptions cliqueConfig = genesisConfigOptions.getCliqueConfigOptions(); final long blocksPerEpoch = cliqueConfig.getEpochLength(); epochManager = new EpochManager(blocksPerEpoch); - forksSchedule = CliqueForksSchedulesFactory.create(configOptionsSupplier.get()); + forksSchedule = CliqueForksSchedulesFactory.create(genesisConfigOptions); } @Override @@ -124,7 +124,7 @@ public class CliqueBesuControllerBuilder extends BesuControllerBuilder { @Override protected ProtocolSchedule createProtocolSchedule() { return CliqueProtocolSchedule.create( - configOptionsSupplier.get(), + genesisConfigOptions, forksSchedule, nodeKey, privacyParameters, diff --git a/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java index a7c1cfe35b..e172115f8d 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java @@ -160,7 +160,7 @@ public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilde besuControllerBuilderSchedule.entrySet().stream() .map(e -> new ForkSpec<>(e.getKey(), e.getValue().createProtocolSchedule())) .collect(Collectors.toCollection(() -> new TreeSet<>(ForkSpec.COMPARATOR))); - final Optional chainId = configOptionsSupplier.get().getChainId(); + final Optional chainId = genesisConfigOptions.getChainId(); return combinedProtocolScheduleFactory.apply(protocolScheduleSpecs, chainId); } @@ -363,15 +363,6 @@ public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilde return super.isRevertReasonEnabled(isRevertReasonEnabled); } - @Override - public BesuControllerBuilder genesisConfigOverrides( - final Map genesisConfigOverrides) { - besuControllerBuilderSchedule - .values() - .forEach(b -> b.genesisConfigOverrides(genesisConfigOverrides)); - return super.genesisConfigOverrides(genesisConfigOverrides); - } - @Override public BesuControllerBuilder gasLimitCalculator(final GasLimitCalculator gasLimitCalculator) { besuControllerBuilderSchedule.values().forEach(b -> b.gasLimitCalculator(gasLimitCalculator)); diff --git a/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java index 6ab517efd6..0bd36c3b0a 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java @@ -16,7 +16,6 @@ package org.hyperledger.besu.controller; import org.hyperledger.besu.config.BftConfigOptions; import org.hyperledger.besu.config.BftFork; -import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.consensus.common.BftValidatorOverrides; import org.hyperledger.besu.consensus.common.EpochManager; import org.hyperledger.besu.consensus.common.ForksSchedule; @@ -102,9 +101,9 @@ public class IbftBesuControllerBuilder extends BftBesuControllerBuilder { @Override protected void prepForBuild() { - bftConfig = configOptionsSupplier.get().getBftConfigOptions(); + bftConfig = genesisConfigOptions.getBftConfigOptions(); bftEventQueue = new BftEventQueue(bftConfig.getMessageQueueLimit()); - forksSchedule = IbftForksSchedulesFactory.create(configOptionsSupplier.get()); + forksSchedule = IbftForksSchedulesFactory.create(genesisConfigOptions); } @Override @@ -280,7 +279,7 @@ public class IbftBesuControllerBuilder extends BftBesuControllerBuilder { @Override protected ProtocolSchedule createProtocolSchedule() { return IbftProtocolScheduleBuilder.create( - configOptionsSupplier.get(), + genesisConfigOptions, forksSchedule, privacyParameters, isRevertReasonEnabled, @@ -304,12 +303,11 @@ public class IbftBesuControllerBuilder extends BftBesuControllerBuilder { final Blockchain blockchain, final WorldStateArchive worldStateArchive, final ProtocolSchedule protocolSchedule) { - final GenesisConfigOptions configOptions = configOptionsSupplier.get(); - final BftConfigOptions ibftConfig = configOptions.getBftConfigOptions(); + final BftConfigOptions ibftConfig = genesisConfigOptions.getBftConfigOptions(); final EpochManager epochManager = new EpochManager(ibftConfig.getEpochLength()); final BftValidatorOverrides validatorOverrides = - convertIbftForks(configOptions.getTransitions().getIbftForks()); + convertIbftForks(genesisConfigOptions.getTransitions().getIbftForks()); return new BftContext( BlockValidatorProvider.forkingValidatorProvider( diff --git a/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java index 4c2e0ee47a..13b3a7111d 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java @@ -91,7 +91,7 @@ public class MainnetBesuControllerBuilder extends BesuControllerBuilder { @Override protected ProtocolSchedule createProtocolSchedule() { return MainnetProtocolSchedule.fromConfig( - configOptionsSupplier.get(), + genesisConfigOptions, privacyParameters, isRevertReasonEnabled, evmConfiguration, @@ -101,8 +101,7 @@ public class MainnetBesuControllerBuilder extends BesuControllerBuilder { @Override protected void prepForBuild() { - configOptionsSupplier - .get() + genesisConfigOptions .getThanosBlockNumber() .ifPresent( activationBlock -> epochCalculator = new EpochCalculator.Ecip1099EpochCalculator()); diff --git a/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java index 20cb108446..3c5f10e4bd 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java @@ -14,7 +14,6 @@ */ package org.hyperledger.besu.controller; -import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.consensus.merge.MergeContext; import org.hyperledger.besu.consensus.merge.MergeProtocolSchedule; import org.hyperledger.besu.consensus.merge.PostMergeContext; @@ -101,11 +100,7 @@ public class MergeBesuControllerBuilder extends BesuControllerBuilder { var mergeBestPeerComparator = new TransitionBestPeerComparator( - configOptionsSupplier - .get() - .getTerminalTotalDifficulty() - .map(Difficulty::of) - .orElseThrow()); + genesisConfigOptions.getTerminalTotalDifficulty().map(Difficulty::of).orElseThrow()); ethPeers.setBestChainComparator(mergeBestPeerComparator); mergeContext.observeNewIsPostMergeState(mergeBestPeerComparator); @@ -156,7 +151,6 @@ public class MergeBesuControllerBuilder extends BesuControllerBuilder { this.syncState.set(syncState); - final GenesisConfigOptions genesisConfigOptions = configOptionsSupplier.get(); final Optional
depositContractAddress = genesisConfigOptions.getDepositContractAddress(); @@ -173,7 +167,7 @@ public class MergeBesuControllerBuilder extends BesuControllerBuilder { @Override protected ProtocolSchedule createProtocolSchedule() { return MergeProtocolSchedule.create( - configOptionsSupplier.get(), + genesisConfigOptions, privacyParameters, isRevertReasonEnabled, miningParameters, @@ -186,7 +180,6 @@ public class MergeBesuControllerBuilder extends BesuControllerBuilder { final WorldStateArchive worldStateArchive, final ProtocolSchedule protocolSchedule) { - final GenesisConfigOptions genesisConfigOptions = configOptionsSupplier.get(); final OptionalLong terminalBlockNumber = genesisConfigOptions.getTerminalBlockNumber(); final Optional terminalBlockHash = genesisConfigOptions.getTerminalBlockHash(); final boolean isPostMergeAtGenesis = @@ -236,9 +229,8 @@ public class MergeBesuControllerBuilder extends BesuControllerBuilder { @Override protected List createPeerValidators(final ProtocolSchedule protocolSchedule) { List retval = super.createPeerValidators(protocolSchedule); - final OptionalLong powTerminalBlockNumber = - configOptionsSupplier.get().getTerminalBlockNumber(); - final Optional powTerminalBlockHash = configOptionsSupplier.get().getTerminalBlockHash(); + final OptionalLong powTerminalBlockNumber = genesisConfigOptions.getTerminalBlockNumber(); + final Optional powTerminalBlockHash = genesisConfigOptions.getTerminalBlockHash(); if (powTerminalBlockHash.isPresent() && powTerminalBlockNumber.isPresent()) { retval.add( new RequiredBlocksPeerValidator( diff --git a/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java index 747949aac1..3c5b87df59 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java @@ -120,9 +120,9 @@ public class QbftBesuControllerBuilder extends BftBesuControllerBuilder { @Override protected void prepForBuild() { - qbftConfig = configOptionsSupplier.get().getQbftConfigOptions(); + qbftConfig = genesisConfigOptions.getQbftConfigOptions(); bftEventQueue = new BftEventQueue(qbftConfig.getMessageQueueLimit()); - qbftForksSchedule = QbftForksSchedulesFactory.create(configOptionsSupplier.get()); + qbftForksSchedule = QbftForksSchedulesFactory.create(genesisConfigOptions); } @Override @@ -320,7 +320,7 @@ public class QbftBesuControllerBuilder extends BftBesuControllerBuilder { @Override protected ProtocolSchedule createProtocolSchedule() { return QbftProtocolScheduleBuilder.create( - configOptionsSupplier.get(), + genesisConfigOptions, qbftForksSchedule, privacyParameters, isRevertReasonEnabled, @@ -355,7 +355,7 @@ public class QbftBesuControllerBuilder extends BftBesuControllerBuilder { } private boolean isValidatorContractMode() { - return configOptionsSupplier.get().getQbftConfigOptions().isValidatorContractMode(); + return genesisConfigOptions.getQbftConfigOptions().isValidatorContractMode(); } private boolean signersExistIn(final BlockHeader genesisBlockHeader) { @@ -370,7 +370,7 @@ public class QbftBesuControllerBuilder extends BftBesuControllerBuilder { final EpochManager epochManager = new EpochManager(qbftConfig.getEpochLength()); final BftValidatorOverrides validatorOverrides = - convertBftForks(configOptionsSupplier.get().getTransitions().getQbftForks()); + convertBftForks(genesisConfigOptions.getTransitions().getQbftForks()); final BlockValidatorProvider blockValidatorProvider = BlockValidatorProvider.forkingValidatorProvider( blockchain, epochManager, bftBlockInterface().get(), validatorOverrides); diff --git a/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java index dab6ff5579..a2f52c90ee 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java @@ -15,7 +15,6 @@ package org.hyperledger.besu.controller; import org.hyperledger.besu.config.GenesisConfigFile; -import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.consensus.merge.MergeContext; import org.hyperledger.besu.consensus.merge.PostMergeContext; import org.hyperledger.besu.consensus.merge.TransitionBackwardSyncContext; @@ -232,9 +231,8 @@ public class TransitionBesuControllerBuilder extends BesuControllerBuilder { syncState, ethProtocolManager, pivotBlockSelector); - final GenesisConfigOptions maybeForTTD = configOptionsSupplier.get(); - if (maybeForTTD.getTerminalTotalDifficulty().isPresent()) { + if (genesisConfigOptions.getTerminalTotalDifficulty().isPresent()) { LOG.info( "TTD present, creating DefaultSynchronizer that stops propagating after finalization"); protocolContext @@ -383,13 +381,6 @@ public class TransitionBesuControllerBuilder extends BesuControllerBuilder { return propagateConfig(z -> z.isRevertReasonEnabled(isRevertReasonEnabled)); } - @Override - public BesuControllerBuilder genesisConfigOverrides( - final Map genesisConfigOverrides) { - super.genesisConfigOverrides(genesisConfigOverrides); - return propagateConfig(z -> z.genesisConfigOverrides(genesisConfigOverrides)); - } - @Override public BesuControllerBuilder gasLimitCalculator(final GasLimitCalculator gasLimitCalculator) { super.gasLimitCalculator(gasLimitCalculator); diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java index 4f1b31c76b..ceb0be40fe 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java @@ -180,9 +180,8 @@ public class PrivacyReorgTest { besuController = new BesuController.Builder() - .fromGenesisConfig( - GenesisConfigFile.genesisFileFromResources("/privacy_reorg_genesis.json"), - SyncMode.FULL) + .fromGenesisFile( + GenesisConfigFile.fromResource("/privacy_reorg_genesis.json"), SyncMode.FULL) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java index 44730b43ee..7a4f05ad7f 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java @@ -22,7 +22,8 @@ import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_IS_HIGH_SPEC; import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_MAX_OPEN_FILES; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.cli.config.EthNetworkConfig; +import org.hyperledger.besu.cli.config.NetworkName; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.datatypes.Address; @@ -111,7 +112,7 @@ public class PrivacyTest { .setFlexiblePrivacyGroupsEnabled(flexibleEnabled) .build(); return new BesuController.Builder() - .fromGenesisConfig(GenesisConfigFile.mainnet(), SyncMode.FULL) + .fromEthNetworkConfig(EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET), SyncMode.FULL) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) diff --git a/besu/src/test/java/org/hyperledger/besu/RunnerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/RunnerBuilderTest.java index cbd18961ad..c177064080 100644 --- a/besu/src/test/java/org/hyperledger/besu/RunnerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/RunnerBuilderTest.java @@ -246,7 +246,7 @@ public final class RunnerBuilderTest { final JsonRpcConfiguration engine = JsonRpcConfiguration.createEngineDefault(); engine.setEnabled(true); final EthNetworkConfig mockMainnet = mock(EthNetworkConfig.class); - when(mockMainnet.getNetworkId()).thenReturn(BigInteger.ONE); + when(mockMainnet.networkId()).thenReturn(BigInteger.ONE); MergeConfigOptions.setMergeEnabled(true); when(besuController.getMiningCoordinator()).thenReturn(mock(MergeMiningCoordinator.class)); @@ -287,7 +287,7 @@ public final class RunnerBuilderTest { final WebSocketConfiguration wsRpc = WebSocketConfiguration.createDefault(); wsRpc.setEnabled(true); final EthNetworkConfig mockMainnet = mock(EthNetworkConfig.class); - when(mockMainnet.getNetworkId()).thenReturn(BigInteger.ONE); + when(mockMainnet.networkId()).thenReturn(BigInteger.ONE); MergeConfigOptions.setMergeEnabled(true); when(besuController.getMiningCoordinator()).thenReturn(mock(MergeMiningCoordinator.class)); final JsonRpcConfiguration engineConf = JsonRpcConfiguration.createEngineDefault(); @@ -329,7 +329,7 @@ public final class RunnerBuilderTest { final WebSocketConfiguration wsRpc = WebSocketConfiguration.createDefault(); wsRpc.setEnabled(true); final EthNetworkConfig mockMainnet = mock(EthNetworkConfig.class); - when(mockMainnet.getNetworkId()).thenReturn(BigInteger.ONE); + when(mockMainnet.networkId()).thenReturn(BigInteger.ONE); MergeConfigOptions.setMergeEnabled(true); when(besuController.getMiningCoordinator()).thenReturn(mock(MergeMiningCoordinator.class)); final JsonRpcConfiguration engineConf = JsonRpcConfiguration.createEngineDefault(); @@ -376,7 +376,7 @@ public final class RunnerBuilderTest { final WebSocketConfiguration defaultWebSockConfig = WebSocketConfiguration.createDefault(); defaultWebSockConfig.setEnabled(true); final EthNetworkConfig mockMainnet = mock(EthNetworkConfig.class); - when(mockMainnet.getNetworkId()).thenReturn(BigInteger.ONE); + when(mockMainnet.networkId()).thenReturn(BigInteger.ONE); MergeConfigOptions.setMergeEnabled(true); final Runner runner = diff --git a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java index 55cdee554b..f0125174d2 100644 --- a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java +++ b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java @@ -17,6 +17,7 @@ package org.hyperledger.besu; import static java.util.Collections.emptySet; import static org.assertj.core.api.Assertions.assertThat; import static org.hyperledger.besu.cli.config.NetworkName.DEV; +import static org.hyperledger.besu.cli.config.NetworkName.MAINNET; import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_BACKGROUND_THREAD_COUNT; import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_CACHE_CAPACITY; import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_IS_HIGH_SPEC; @@ -85,6 +86,7 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.TimeUnit; +import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import io.vertx.core.Future; import io.vertx.core.Promise; @@ -242,7 +244,7 @@ public final class RunnerTest { final EnodeURL aheadEnode = runnerAhead.getLocalEnode().get(); final EthNetworkConfig behindEthNetworkConfiguration = new EthNetworkConfig( - EthNetworkConfig.jsonConfig(DEV), + GenesisConfigFile.fromResource(DEV.getGenesisFile()), DEV.getNetworkId(), Collections.singletonList(aheadEnode), null); @@ -367,8 +369,11 @@ public final class RunnerTest { .build(); } - private GenesisConfigFile getFastSyncGenesis() { - final ObjectNode jsonNode = GenesisConfigFile.mainnetJsonNode(); + private GenesisConfigFile getFastSyncGenesis() throws IOException { + final ObjectNode jsonNode = + (ObjectNode) + new ObjectMapper() + .readTree(GenesisConfigFile.class.getResource(MAINNET.getGenesisFile())); final Optional configNode = JsonUtil.getObjectNode(jsonNode, "config"); configNode.ifPresent( (node) -> { diff --git a/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java b/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java index faa6bd34b9..05057f15c8 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java @@ -18,7 +18,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import org.hyperledger.besu.chainimport.RlpBlockImporter; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.cli.config.EthNetworkConfig; +import org.hyperledger.besu.cli.config.NetworkName; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.ethereum.GasLimitCalculator; @@ -86,7 +87,7 @@ public final class RlpBlockExporterTest { private static BesuController createController(final @TempDir Path dataDir) throws IOException { return new BesuController.Builder() - .fromGenesisConfig(GenesisConfigFile.mainnet(), SyncMode.FAST) + .fromEthNetworkConfig(EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET), SyncMode.FAST) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) diff --git a/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java b/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java index dff42ef654..522f268c57 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java @@ -434,7 +434,7 @@ public abstract class JsonBlockImporterTest { protected BesuController createController(final GenesisConfigFile genesisConfigFile) { return new BesuController.Builder() - .fromGenesisConfig(genesisConfigFile, SyncMode.FAST) + .fromGenesisFile(genesisConfigFile, SyncMode.FAST) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) diff --git a/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java b/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java index d65569535a..e37b8a5fd0 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java @@ -17,7 +17,8 @@ package org.hyperledger.besu.chainimport; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import org.hyperledger.besu.config.GenesisConfigFile; +import org.hyperledger.besu.cli.config.EthNetworkConfig; +import org.hyperledger.besu.cli.config.NetworkName; import org.hyperledger.besu.config.MergeConfigOptions; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; @@ -60,7 +61,8 @@ public final class RlpBlockImporterTest { BlockTestUtil.write1000Blocks(source); final BesuController targetController = new BesuController.Builder() - .fromGenesisConfig(GenesisConfigFile.mainnet(), SyncMode.FAST) + .fromEthNetworkConfig( + EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET), SyncMode.FAST) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) @@ -92,7 +94,8 @@ public final class RlpBlockImporterTest { BlockTestUtil.writeBadPowBlocks(source); final BesuController targetController = new BesuController.Builder() - .fromGenesisConfig(GenesisConfigFile.mainnet(), SyncMode.FAST) + .fromEthNetworkConfig( + EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET), SyncMode.FAST) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) @@ -121,7 +124,8 @@ public final class RlpBlockImporterTest { BlockTestUtil.writeBadPowBlocks(source); final BesuController targetController = new BesuController.Builder() - .fromGenesisConfig(GenesisConfigFile.mainnet(), SyncMode.FAST) + .fromEthNetworkConfig( + EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET), SyncMode.FAST) .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) diff --git a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java index 82a6921786..4353fd7d5f 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -205,7 +205,7 @@ public class BesuCommandTest extends CommandTestAbstract { verify(mockRunnerBuilder) .ethNetworkConfig( new EthNetworkConfig( - EthNetworkConfig.jsonConfig(MAINNET), + GenesisConfigFile.fromResource(MAINNET.getGenesisFile()), MAINNET.getNetworkId(), MAINNET_BOOTSTRAP_NODES, MAINNET_DISCOVERY_URL)); @@ -220,8 +220,7 @@ public class BesuCommandTest extends CommandTestAbstract { verify(mockRunnerBuilder).apiConfiguration(DEFAULT_API_CONFIGURATION); verify(mockRunnerBuilder).build(); - verify(mockControllerBuilderFactory) - .fromEthNetworkConfig(ethNetworkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(ethNetworkArg.capture(), any()); final ArgumentCaptor miningArg = ArgumentCaptor.forClass(MiningParameters.class); verify(mockControllerBuilder).synchronizerConfiguration(syncConfigurationCaptor.capture()); @@ -240,8 +239,8 @@ public class BesuCommandTest extends CommandTestAbstract { assertThat(miningArg.getValue().getCoinbase()).isEqualTo(Optional.empty()); assertThat(miningArg.getValue().getMinTransactionGasPrice()).isEqualTo(Wei.of(1000)); assertThat(miningArg.getValue().getExtraData()).isEqualTo(Bytes.EMPTY); - assertThat(ethNetworkArg.getValue().getNetworkId()).isEqualTo(1); - assertThat(ethNetworkArg.getValue().getBootNodes()).isEqualTo(MAINNET_BOOTSTRAP_NODES); + assertThat(ethNetworkArg.getValue().networkId()).isEqualTo(1); + assertThat(ethNetworkArg.getValue().bootNodes()).isEqualTo(MAINNET_BOOTSTRAP_NODES); } // Testing each option @@ -299,7 +298,7 @@ public class BesuCommandTest extends CommandTestAbstract { parseCommand("--config-file", toml.toAbsolutePath().toString()); verify(mockRunnerBuilder).ethNetworkConfig(ethNetworkConfigArgumentCaptor.capture()); - assertThat(ethNetworkConfigArgumentCaptor.getValue().getBootNodes()).isEmpty(); + assertThat(ethNetworkConfigArgumentCaptor.getValue().bootNodes()).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); assertThat(commandOutput.toString(UTF_8)).isEmpty(); @@ -410,11 +409,11 @@ public class BesuCommandTest extends CommandTestAbstract { parseCommand("--genesis-file", genesisFile.toString()); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); - assertThat(networkArg.getValue().getGenesisConfig()) - .isEqualTo(encodeJsonGenesis(GENESIS_VALID_JSON)); + assertThat(networkArg.getValue().genesisConfigFile()) + .isEqualTo(GenesisConfigFile.fromConfig(encodeJsonGenesis(GENESIS_VALID_JSON))); assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -429,29 +428,29 @@ public class BesuCommandTest extends CommandTestAbstract { parseCommand("--genesis-file", genesisFile.toString()); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getBootNodes()).isEmpty(); - assertThat(config.getDnsDiscoveryUrl()).isNull(); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(3141592)); + assertThat(config.bootNodes()).isEmpty(); + assertThat(config.dnsDiscoveryUrl()).isNull(); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(3141592)); } @Test - public void testGenesisPathMainnetEthConfig() throws Exception { + public void testGenesisPathMainnetEthConfig() { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); parseCommand("--network", "mainnet"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getBootNodes()).isEqualTo(MAINNET_BOOTSTRAP_NODES); - assertThat(config.getDnsDiscoveryUrl()).isEqualTo(MAINNET_DISCOVERY_URL); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(1)); + assertThat(config.bootNodes()).isEqualTo(MAINNET_BOOTSTRAP_NODES); + assertThat(config.dnsDiscoveryUrl()).isEqualTo(MAINNET_DISCOVERY_URL); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(1)); verify(mockLogger, never()).warn(contains("Mainnet is deprecated and will be shutdown")); } @@ -463,13 +462,13 @@ public class BesuCommandTest extends CommandTestAbstract { parseCommand("--network", "goerli"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getBootNodes()).isEqualTo(GOERLI_BOOTSTRAP_NODES); - assertThat(config.getDnsDiscoveryUrl()).isEqualTo(GOERLI_DISCOVERY_URL); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(5)); + assertThat(config.bootNodes()).isEqualTo(GOERLI_BOOTSTRAP_NODES); + assertThat(config.dnsDiscoveryUrl()).isEqualTo(GOERLI_DISCOVERY_URL); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(5)); } @Test @@ -479,13 +478,13 @@ public class BesuCommandTest extends CommandTestAbstract { parseCommand("--network", "future_eips"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getBootNodes()).isEmpty(); - assertThat(config.getDnsDiscoveryUrl()).isNull(); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(2022)); + assertThat(config.bootNodes()).isEmpty(); + assertThat(config.dnsDiscoveryUrl()).isNull(); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(2022)); } @Test @@ -495,13 +494,13 @@ public class BesuCommandTest extends CommandTestAbstract { parseCommand("--network", "experimental_eips"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getBootNodes()).isEmpty(); - assertThat(config.getDnsDiscoveryUrl()).isNull(); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(2023)); + assertThat(config.bootNodes()).isEmpty(); + assertThat(config.dnsDiscoveryUrl()).isNull(); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(2023)); } @Test @@ -518,7 +517,7 @@ public class BesuCommandTest extends CommandTestAbstract { } @Test - public void nonExistentGenesisGivesError() throws Exception { + public void nonExistentGenesisGivesError() { final String nonExistentGenesis = "non-existent-genesis.json"; parseCommand("--genesis-file", nonExistentGenesis); @@ -530,7 +529,7 @@ public class BesuCommandTest extends CommandTestAbstract { } @Test - public void testDnsDiscoveryUrlEthConfig() throws Exception { + public void testDnsDiscoveryUrlEthConfig() { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); @@ -538,17 +537,17 @@ public class BesuCommandTest extends CommandTestAbstract { "--discovery-dns-url", "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@nodes.example.org"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getDnsDiscoveryUrl()) + assertThat(config.dnsDiscoveryUrl()) .isEqualTo( "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@nodes.example.org"); } @Test - public void testDnsDiscoveryUrlOverridesNetworkEthConfig() throws Exception { + public void testDnsDiscoveryUrlOverridesNetworkEthConfig() { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); @@ -558,11 +557,11 @@ public class BesuCommandTest extends CommandTestAbstract { "--discovery-dns-url", "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@nodes.example.org"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getDnsDiscoveryUrl()) + assertThat(config.dnsDiscoveryUrl()) .isEqualTo( "enrtree://AM5FCQLWIZX2QFPNJAP7VUERCCRNGRHWZG3YYHIUV7BVDQ5FDPRT2@nodes.example.org"); } @@ -576,13 +575,13 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); - assertThat(networkArg.getValue().getGenesisConfig()) - .isEqualTo(encodeJsonGenesis(GENESIS_VALID_JSON)); - assertThat(networkArg.getValue().getBootNodes()).isEmpty(); - assertThat(networkArg.getValue().getNetworkId()).isEqualTo(GENESIS_CONFIG_TEST_CHAINID); + assertThat(networkArg.getValue().genesisConfigFile()) + .isEqualTo(GenesisConfigFile.fromConfig(encodeJsonGenesis(GENESIS_VALID_JSON))); + assertThat(networkArg.getValue().bootNodes()).isEmpty(); + assertThat(networkArg.getValue().networkId()).isEqualTo(GENESIS_CONFIG_TEST_CHAINID); assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -597,11 +596,11 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); - assertThat(networkArg.getValue().getGenesisConfig()) - .isEqualTo(encodeJsonGenesis(GENESIS_INVALID_DATA)); + assertThat(networkArg.getValue().genesisConfigFile()) + .isEqualTo(GenesisConfigFile.fromConfig(encodeJsonGenesis(GENESIS_INVALID_DATA))); assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -614,11 +613,11 @@ public class BesuCommandTest extends CommandTestAbstract { // id // in this network genesis file. - final GenesisConfigFile genesisConfigFile = - GenesisConfigFile.fromConfig(EthNetworkConfig.getNetworkConfig(MAINNET).getGenesisConfig()); - assertThat(genesisConfigFile.getConfigOptions().getChainId().isPresent()).isTrue(); - assertThat(genesisConfigFile.getConfigOptions().getChainId().get()) - .isEqualTo(EthNetworkConfig.getNetworkConfig(MAINNET).getNetworkId()); + final var genesisConfig = + EthNetworkConfig.getNetworkConfig(MAINNET).genesisConfigFile().getConfigOptions(); + assertThat(genesisConfig.getChainId().isPresent()).isTrue(); + assertThat(genesisConfig.getChainId().get()) + .isEqualTo(EthNetworkConfig.getNetworkConfig(MAINNET).networkId()); } @Test @@ -755,13 +754,13 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getDnsDiscoveryUrl()).isEqualTo(DNS_DISCOVERY_URL); + assertThat(config.dnsDiscoveryUrl()).isEqualTo(DNS_DISCOVERY_URL); - assertThat(config.getBootNodes()) + assertThat(config.bootNodes()) .extracting(bootnode -> bootnode.toURI().toString()) .containsExactly(VALID_ENODE_STRINGS); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -777,11 +776,11 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getDnsDiscoveryUrl()).isEqualTo(discoveryDnsUrlCliArg); + assertThat(config.dnsDiscoveryUrl()).isEqualTo(discoveryDnsUrlCliArg); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @@ -796,11 +795,11 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getBootNodes()).extracting(EnodeURL::toURI).containsExactly(bootnode); + assertThat(config.bootNodes()).extracting(EnodeURL::toURI).containsExactly(bootnode); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @@ -812,7 +811,7 @@ public class BesuCommandTest extends CommandTestAbstract { verify(mockRunnerBuilder).ethNetworkConfig(ethNetworkConfigArgumentCaptor.capture()); verify(mockRunnerBuilder).build(); - assertThat(ethNetworkConfigArgumentCaptor.getValue().getBootNodes()).isEmpty(); + assertThat(ethNetworkConfigArgumentCaptor.getValue().bootNodes()).isEmpty(); assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -882,7 +881,7 @@ public class BesuCommandTest extends CommandTestAbstract { verify(mockRunnerBuilder).ethNetworkConfig(ethNetworkConfigArgumentCaptor.capture()); verify(mockRunnerBuilder).build(); - assertThat(ethNetworkConfigArgumentCaptor.getValue().getBootNodes()) + assertThat(ethNetworkConfigArgumentCaptor.getValue().bootNodes()) .isEqualTo( Stream.of(VALID_ENODE_STRINGS) .map(EnodeURLImpl::fromString) @@ -1614,13 +1613,13 @@ public class BesuCommandTest extends CommandTestAbstract { } @Test - public void devModeOptionMustBeUsed() throws Exception { + public void devModeOptionMustBeUsed() { parseCommand("--network", "dev"); final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); assertThat(networkArg.getValue()).isEqualTo(EthNetworkConfig.getNetworkConfig(DEV)); @@ -1636,7 +1635,7 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); assertThat(networkArg.getValue()).isEqualTo(EthNetworkConfig.getNetworkConfig(GOERLI)); @@ -1654,7 +1653,7 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); assertThat(networkArg.getValue()).isEqualTo(EthNetworkConfig.getNetworkConfig(FUTURE_EIPS)); @@ -1670,7 +1669,7 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); assertThat(networkArg.getValue()) @@ -1687,7 +1686,7 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); assertThat(networkArg.getValue()).isEqualTo(EthNetworkConfig.getNetworkConfig(SEPOLIA)); @@ -1705,7 +1704,7 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); assertThat(networkArg.getValue()).isEqualTo(EthNetworkConfig.getNetworkConfig(HOLESKY)); @@ -1717,13 +1716,13 @@ public class BesuCommandTest extends CommandTestAbstract { } @Test - public void classicValuesAreUsed() throws Exception { + public void classicValuesAreUsed() { parseCommand("--network", "classic"); final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); assertThat(networkArg.getValue()).isEqualTo(EthNetworkConfig.getNetworkConfig(CLASSIC)); @@ -1733,13 +1732,13 @@ public class BesuCommandTest extends CommandTestAbstract { } @Test - public void mordorValuesAreUsed() throws Exception { + public void mordorValuesAreUsed() { parseCommand("--network", "mordor"); final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); assertThat(networkArg.getValue()).isEqualTo(EthNetworkConfig.getNetworkConfig(MORDOR)); @@ -1749,36 +1748,36 @@ public class BesuCommandTest extends CommandTestAbstract { } @Test - public void goerliValuesCanBeOverridden() throws Exception { + public void goerliValuesCanBeOverridden() { networkValuesCanBeOverridden("goerli"); } @Test - public void futureEipsValuesCanBeOverridden() throws Exception { + public void futureEipsValuesCanBeOverridden() { networkValuesCanBeOverridden("future_eips"); } @Test - public void experimentalEipsValuesCanBeOverridden() throws Exception { + public void experimentalEipsValuesCanBeOverridden() { networkValuesCanBeOverridden("experimental_eips"); } @Test - public void devValuesCanBeOverridden() throws Exception { + public void devValuesCanBeOverridden() { networkValuesCanBeOverridden("dev"); } @Test - public void classicValuesCanBeOverridden() throws Exception { + public void classicValuesCanBeOverridden() { networkValuesCanBeOverridden("classic"); } @Test - public void mordorValuesCanBeOverridden() throws Exception { + public void mordorValuesCanBeOverridden() { networkValuesCanBeOverridden("mordor"); } - private void networkValuesCanBeOverridden(final String network) throws Exception { + private void networkValuesCanBeOverridden(final String network) { parseCommand( "--network", network, @@ -1790,15 +1789,15 @@ public class BesuCommandTest extends CommandTestAbstract { final ArgumentCaptor networkArg = ArgumentCaptor.forClass(EthNetworkConfig.class); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); - assertThat(networkArg.getValue().getBootNodes()) + assertThat(networkArg.getValue().bootNodes()) .isEqualTo( Stream.of(VALID_ENODE_STRINGS) .map(EnodeURLImpl::fromString) .collect(Collectors.toList())); - assertThat(networkArg.getValue().getNetworkId()).isEqualTo(1234567); + assertThat(networkArg.getValue().networkId()).isEqualTo(1234567); assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @@ -2385,7 +2384,7 @@ public class BesuCommandTest extends CommandTestAbstract { parseCommand( "--genesis-file", genesisFile.toString(), "--genesis-state-hash-cache-enabled=true"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); verify(mockControllerBuilder).genesisStateHashCacheEnabled(eq(true)); diff --git a/besu/src/test/java/org/hyperledger/besu/cli/CascadingDefaultProviderTest.java b/besu/src/test/java/org/hyperledger/besu/cli/CascadingDefaultProviderTest.java index 3cc421440f..c2e26344a0 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/CascadingDefaultProviderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/CascadingDefaultProviderTest.java @@ -28,6 +28,7 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.verify; import org.hyperledger.besu.cli.config.EthNetworkConfig; +import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.api.graphql.GraphQLConfiguration; import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration; @@ -122,17 +123,18 @@ public class CascadingDefaultProviderTest extends CommandTestAbstract { EnodeURLImpl.fromString("enode://" + VALID_NODE_ID + "@192.168.0.1:4567"), EnodeURLImpl.fromString("enode://" + VALID_NODE_ID + "@192.168.0.1:4567"), EnodeURLImpl.fromString("enode://" + VALID_NODE_ID + "@192.168.0.1:4567")); - assertThat(ethNetworkConfigArgumentCaptor.getValue().getBootNodes()).isEqualTo(nodes); + assertThat(ethNetworkConfigArgumentCaptor.getValue().bootNodes()).isEqualTo(nodes); final EthNetworkConfig networkConfig = new EthNetworkConfig.Builder(EthNetworkConfig.getNetworkConfig(MAINNET)) .setNetworkId(BigInteger.valueOf(42)) - .setGenesisConfig(encodeJsonGenesis(GENESIS_VALID_JSON)) + .setGenesisConfigFile( + GenesisConfigFile.fromConfig(encodeJsonGenesis(GENESIS_VALID_JSON))) .setBootNodes(nodes) .setDnsDiscoveryUrl(null) .build(); verify(mockControllerBuilder).dataDirectory(eq(dataFolder.toPath())); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(eq(networkConfig), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(eq(networkConfig), any()); verify(mockControllerBuilder).synchronizerConfiguration(syncConfigurationCaptor.capture()); assertThat(syncConfigurationCaptor.getValue().getSyncMode()).isEqualTo(SyncMode.FAST); @@ -164,7 +166,7 @@ public class CascadingDefaultProviderTest extends CommandTestAbstract { verify(mockRunnerBuilder) .ethNetworkConfig( new EthNetworkConfig( - EthNetworkConfig.jsonConfig(MAINNET), + GenesisConfigFile.fromResource(MAINNET.getGenesisFile()), MAINNET.getNetworkId(), MAINNET_BOOTSTRAP_NODES, MAINNET_DISCOVERY_URL)); @@ -234,11 +236,11 @@ public class CascadingDefaultProviderTest extends CommandTestAbstract { ArgumentCaptor.forClass(EthNetworkConfig.class); parseCommand("--profile", "dev"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getNetworkId()).isEqualTo(DEV.getNetworkId()); + assertThat(config.networkId()).isEqualTo(DEV.getNetworkId()); } /** @@ -252,11 +254,11 @@ public class CascadingDefaultProviderTest extends CommandTestAbstract { ArgumentCaptor.forClass(EthNetworkConfig.class); parseCommand("--profile", "dev", "--network", "MAINNET"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getNetworkId()).isEqualTo(MAINNET.getNetworkId()); + assertThat(config.networkId()).isEqualTo(MAINNET.getNetworkId()); } /** @@ -271,11 +273,11 @@ public class CascadingDefaultProviderTest extends CommandTestAbstract { final String configFile = this.getClass().getResource("/partial_config.toml").getFile(); parseCommand("--profile", "dev", "--config-file", configFile); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getNetworkId()).isEqualTo(MAINNET.getNetworkId()); + assertThat(config.networkId()).isEqualTo(MAINNET.getNetworkId()); } /** @@ -289,10 +291,10 @@ public class CascadingDefaultProviderTest extends CommandTestAbstract { ArgumentCaptor.forClass(EthNetworkConfig.class); setEnvironmentVariable("BESU_NETWORK", "MAINNET"); parseCommand("--profile", "dev"); - verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any(), any()); + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); verify(mockControllerBuilder).build(); final EthNetworkConfig config = networkArg.getValue(); - assertThat(config.getNetworkId()).isEqualTo(MAINNET.getNetworkId()); + assertThat(config.networkId()).isEqualTo(MAINNET.getNetworkId()); } } diff --git a/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java b/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java index deef4f648c..5216db7036 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java @@ -266,7 +266,7 @@ public abstract class CommandTestAbstract { // doReturn used because of generic BesuController doReturn(mockControllerBuilder) .when(mockControllerBuilderFactory) - .fromEthNetworkConfig(any(), any(), any()); + .fromEthNetworkConfig(any(), any()); when(mockControllerBuilder.synchronizerConfiguration(any())).thenReturn(mockControllerBuilder); when(mockControllerBuilder.ethProtocolConfiguration(any())).thenReturn(mockControllerBuilder); when(mockControllerBuilder.transactionPoolConfiguration(any())) @@ -283,7 +283,6 @@ public abstract class CommandTestAbstract { when(mockControllerBuilder.clock(any())).thenReturn(mockControllerBuilder); when(mockControllerBuilder.isRevertReasonEnabled(false)).thenReturn(mockControllerBuilder); when(mockControllerBuilder.storageProvider(any())).thenReturn(mockControllerBuilder); - when(mockControllerBuilder.genesisConfigOverrides(any())).thenReturn(mockControllerBuilder); when(mockControllerBuilder.gasLimitCalculator(any())).thenReturn(mockControllerBuilder); when(mockControllerBuilder.requiredBlocks(any())).thenReturn(mockControllerBuilder); when(mockControllerBuilder.reorgLoggingThreshold(anyLong())).thenReturn(mockControllerBuilder); @@ -590,8 +589,8 @@ public abstract class CommandTestAbstract { } @Override - public GenesisConfigOptions getActualGenesisConfigOptions() { - return super.getActualGenesisConfigOptions(); + public GenesisConfigOptions getGenesisConfigOptions() { + return super.getGenesisConfigOptions(); } public CommandSpec getSpec() { diff --git a/besu/src/test/java/org/hyperledger/besu/cli/config/EthNetworkConfigTest.java b/besu/src/test/java/org/hyperledger/besu/cli/config/EthNetworkConfigTest.java index 3bddc7724b..75a1bc698c 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/config/EthNetworkConfigTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/config/EthNetworkConfigTest.java @@ -21,6 +21,8 @@ import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfigura import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.MAINNET_BOOTSTRAP_NODES; import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.MAINNET_DISCOVERY_URL; +import org.hyperledger.besu.config.GenesisConfigFile; + import java.math.BigInteger; import org.junit.jupiter.api.Test; @@ -33,41 +35,41 @@ public class EthNetworkConfigTest { @Test public void testDefaultMainnetConfig() { EthNetworkConfig config = EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET); - assertThat(config.getDnsDiscoveryUrl()).isEqualTo(MAINNET_DISCOVERY_URL); - assertThat(config.getBootNodes()).isEqualTo(MAINNET_BOOTSTRAP_NODES); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.ONE); + assertThat(config.dnsDiscoveryUrl()).isEqualTo(MAINNET_DISCOVERY_URL); + assertThat(config.bootNodes()).isEqualTo(MAINNET_BOOTSTRAP_NODES); + assertThat(config.networkId()).isEqualTo(BigInteger.ONE); } @Test public void testDefaultGoerliConfig() { EthNetworkConfig config = EthNetworkConfig.getNetworkConfig(NetworkName.GOERLI); - assertThat(config.getDnsDiscoveryUrl()).isEqualTo(GOERLI_DISCOVERY_URL); - assertThat(config.getBootNodes()).isEqualTo(GOERLI_BOOTSTRAP_NODES); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(5)); + assertThat(config.dnsDiscoveryUrl()).isEqualTo(GOERLI_DISCOVERY_URL); + assertThat(config.bootNodes()).isEqualTo(GOERLI_BOOTSTRAP_NODES); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(5)); } @Test public void testDefaultDevConfig() { EthNetworkConfig config = EthNetworkConfig.getNetworkConfig(NetworkName.DEV); - assertThat(config.getDnsDiscoveryUrl()).isNull(); - assertThat(config.getBootNodes()).isEmpty(); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(2018)); + assertThat(config.dnsDiscoveryUrl()).isNull(); + assertThat(config.bootNodes()).isEmpty(); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(2018)); } @Test public void testDefaultFutureConfig() { EthNetworkConfig config = EthNetworkConfig.getNetworkConfig(NetworkName.FUTURE_EIPS); - assertThat(config.getDnsDiscoveryUrl()).isNull(); - assertThat(config.getBootNodes()).isEmpty(); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(2022)); + assertThat(config.dnsDiscoveryUrl()).isNull(); + assertThat(config.bootNodes()).isEmpty(); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(2022)); } @Test public void testDefaultExperimentalConfig() { EthNetworkConfig config = EthNetworkConfig.getNetworkConfig(NetworkName.EXPERIMENTAL_EIPS); - assertThat(config.getDnsDiscoveryUrl()).isNull(); - assertThat(config.getBootNodes()).isEmpty(); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(2023)); + assertThat(config.dnsDiscoveryUrl()).isNull(); + assertThat(config.bootNodes()).isEmpty(); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(2023)); } @Test @@ -75,11 +77,20 @@ public class EthNetworkConfigTest { EthNetworkConfig config = new EthNetworkConfig.Builder(EthNetworkConfig.getNetworkConfig(MAINNET)) .setNetworkId(BigInteger.valueOf(42)) - .setGenesisConfig("{\"config\":{\"chainId\":\"1234567\"}") + .setGenesisConfigFile( + GenesisConfigFile.fromConfig( + """ + { + "config":{ + "chainId":"1234567" + } + } + """)) .build(); - assertThat(config.getGenesisConfig()).isEqualTo("{\"config\":{\"chainId\":\"1234567\"}"); - assertThat(config.getDnsDiscoveryUrl()).isNotNull(); - assertThat(config.getBootNodes()).isNotEmpty(); - assertThat(config.getNetworkId()).isEqualTo(BigInteger.valueOf(42)); + assertThat(config.genesisConfigFile().getConfigOptions().getChainId()) + .contains(BigInteger.valueOf(1234567)); + assertThat(config.dnsDiscoveryUrl()).isNotNull(); + assertThat(config.bootNodes()).isNotEmpty(); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(42)); } } diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/MiningOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/MiningOptionsTest.java index e06d711be6..e32ff0e463 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/MiningOptionsTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/MiningOptionsTest.java @@ -426,7 +426,7 @@ public class MiningOptionsTest extends AbstractCLIOptionsTest new BesuController.Builder().fromGenesisConfig(genesisConfigFile, SyncMode.FULL)) + () -> new BesuController.Builder().fromGenesisFile(genesisConfigFile, SyncMode.FULL)) .isInstanceOf(IllegalStateException.class) .hasMessage("Missing QBFT startBlock config in genesis file"); } @@ -59,19 +61,18 @@ public class BesuControllerTest { public void invalidQbftStartBlock() { mockGenesisConfigForMigration("ibft2", OptionalLong.of(-1L)); assertThatThrownBy( - () -> new BesuController.Builder().fromGenesisConfig(genesisConfigFile, SyncMode.FULL)) + () -> new BesuController.Builder().fromGenesisFile(genesisConfigFile, SyncMode.FULL)) .isInstanceOf(IllegalStateException.class) .hasMessage("Invalid QBFT startBlock config in genesis file"); } @Test public void invalidConsensusCombination() { - when(genesisConfigFile.getConfigOptions(any())).thenReturn(genesisConfigOptions); when(genesisConfigOptions.isConsensusMigration()).thenReturn(true); // explicitly not setting isIbft2() for genesisConfigOptions assertThatThrownBy( - () -> new BesuController.Builder().fromGenesisConfig(genesisConfigFile, SyncMode.FULL)) + () -> new BesuController.Builder().fromGenesisFile(genesisConfigFile, SyncMode.FULL)) .isInstanceOf(IllegalStateException.class) .hasMessage( "Invalid genesis migration config. Migration is supported from IBFT (legacy) or IBFT2 to QBFT)"); @@ -83,7 +84,7 @@ public class BesuControllerTest { mockGenesisConfigForMigration("ibft2", OptionalLong.of(qbftStartBlock)); final BesuControllerBuilder besuControllerBuilder = - new BesuController.Builder().fromGenesisConfig(genesisConfigFile, SyncMode.FULL); + new BesuController.Builder().fromGenesisFile(genesisConfigFile, SyncMode.FULL); assertThat(besuControllerBuilder).isInstanceOf(ConsensusScheduleBesuControllerBuilder.class); @@ -99,7 +100,6 @@ public class BesuControllerTest { private void mockGenesisConfigForMigration( final String consensus, final OptionalLong startBlock) { - when(genesisConfigFile.getConfigOptions(any())).thenReturn(genesisConfigOptions); when(genesisConfigOptions.isConsensusMigration()).thenReturn(true); switch (consensus.toLowerCase(Locale.ROOT)) { @@ -117,16 +117,12 @@ public class BesuControllerTest { } @Test - public void postMergeCheckpointSyncUsesMergeControllerBuilder() throws IOException { + public void postMergeCheckpointSyncUsesMergeControllerBuilder() { final GenesisConfigFile postMergeGenesisFile = - GenesisConfigFile.fromConfig( - Resources.toString( - Resources.getResource("valid_post_merge_near_head_checkpoint.json"), - StandardCharsets.UTF_8)); + GenesisConfigFile.fromResource("/valid_post_merge_near_head_checkpoint.json"); final BesuControllerBuilder besuControllerBuilder = - new BesuController.Builder() - .fromGenesisConfig(postMergeGenesisFile, Collections.emptyMap(), SyncMode.CHECKPOINT); + new BesuController.Builder().fromGenesisFile(postMergeGenesisFile, SyncMode.CHECKPOINT); assertThat(besuControllerBuilder).isInstanceOf(MergeBesuControllerBuilder.class); } @@ -135,15 +131,11 @@ public class BesuControllerTest { public void postMergeCheckpointSyncWithTotalDifficultyEqualsTTDUsesTransitionControllerBuilder() throws IOException { final GenesisConfigFile mergeAtGenesisFile = - GenesisConfigFile.fromConfig( - Resources.toString( - Resources.getResource( - "invalid_post_merge_checkpoint_total_difficulty_same_as_TTD.json"), - StandardCharsets.UTF_8)); + GenesisConfigFile.fromResource( + "/invalid_post_merge_checkpoint_total_difficulty_same_as_TTD.json"); final BesuControllerBuilder besuControllerBuilder = - new BesuController.Builder() - .fromGenesisConfig(mergeAtGenesisFile, Collections.emptyMap(), SyncMode.CHECKPOINT); + new BesuController.Builder().fromGenesisFile(mergeAtGenesisFile, SyncMode.CHECKPOINT); assertThat(besuControllerBuilder).isInstanceOf(TransitionBesuControllerBuilder.class); } @@ -152,7 +144,7 @@ public class BesuControllerTest { public void preMergeCheckpointSyncUsesTransitionControllerBuilder() { final BesuControllerBuilder besuControllerBuilder = new BesuController.Builder() - .fromGenesisConfig(genesisConfigFile, Collections.emptyMap(), SyncMode.CHECKPOINT); + .fromGenesisFile(GenesisConfigFile.mainnet(), SyncMode.CHECKPOINT); assertThat(besuControllerBuilder).isInstanceOf(TransitionBesuControllerBuilder.class); } @@ -160,8 +152,7 @@ public class BesuControllerTest { @Test public void nonCheckpointSyncUsesTransitionControllerBuild() { final BesuControllerBuilder besuControllerBuilder = - new BesuController.Builder() - .fromGenesisConfig(genesisConfigFile, Collections.emptyMap(), SyncMode.SNAP); + new BesuController.Builder().fromGenesisFile(GenesisConfigFile.mainnet(), SyncMode.SNAP); assertThat(besuControllerBuilder).isInstanceOf(TransitionBesuControllerBuilder.class); } diff --git a/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java index c410ac9ec5..12f36c9f6e 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java @@ -17,7 +17,6 @@ package org.hyperledger.besu.controller; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; -import static org.mockito.ArgumentMatchers.anyMap; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; @@ -101,11 +100,11 @@ public class ConsensusScheduleBesuControllerBuilderTest { final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions(); genesisConfigOptions.chainId(BigInteger.TEN); - when(genesisConfigFile.getConfigOptions(anyMap())).thenReturn(genesisConfigOptions); final ConsensusScheduleBesuControllerBuilder consensusScheduleBesuControllerBuilder = new ConsensusScheduleBesuControllerBuilder( besuControllerBuilderSchedule, combinedProtocolScheduleFactory); + when(genesisConfigFile.getConfigOptions()).thenReturn(genesisConfigOptions); consensusScheduleBesuControllerBuilder.genesisConfigFile(genesisConfigFile); consensusScheduleBesuControllerBuilder.createProtocolSchedule(); diff --git a/besu/src/test/java/org/hyperledger/besu/controller/IbftBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/IbftBesuControllerBuilderTest.java index 63d2bba9c0..055e136c8c 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/IbftBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/IbftBesuControllerBuilderTest.java @@ -33,7 +33,7 @@ import org.mockito.junit.jupiter.MockitoExtension; public class IbftBesuControllerBuilderTest extends AbstractBftBesuControllerBuilderTest { @Override - public void setupBftGenesisConfigOptions() throws JsonProcessingException { + public void setupBftGenesisConfigFile() throws JsonProcessingException { // Ibft prepForBuild setup lenient() diff --git a/besu/src/test/java/org/hyperledger/besu/controller/QbftBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/QbftBesuControllerBuilderTest.java index 50f17fd8a6..1d3c6ad011 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/QbftBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/QbftBesuControllerBuilderTest.java @@ -45,7 +45,7 @@ import org.mockito.junit.jupiter.MockitoExtension; public class QbftBesuControllerBuilderTest extends AbstractBftBesuControllerBuilderTest { @Override - public void setupBftGenesisConfigOptions() throws JsonProcessingException { + public void setupBftGenesisConfigFile() throws JsonProcessingException { // qbft prepForBuild setup lenient() diff --git a/besu/src/test/java/org/hyperledger/besu/util/LocalPermissioningConfigurationValidatorTest.java b/besu/src/test/java/org/hyperledger/besu/util/LocalPermissioningConfigurationValidatorTest.java index 84344c2491..6a39bd3b6b 100644 --- a/besu/src/test/java/org/hyperledger/besu/util/LocalPermissioningConfigurationValidatorTest.java +++ b/besu/src/test/java/org/hyperledger/besu/util/LocalPermissioningConfigurationValidatorTest.java @@ -67,7 +67,7 @@ public class LocalPermissioningConfigurationValidatorTest { true, toml.toAbsolutePath().toString()); - final List enodeURIs = ethNetworkConfig.getBootNodes(); + final List enodeURIs = ethNetworkConfig.bootNodes(); PermissioningConfigurationValidator.areAllNodesInAllowlist( enodeURIs, permissioningConfiguration); } @@ -91,7 +91,7 @@ public class LocalPermissioningConfigurationValidatorTest { toml.toAbsolutePath().toString()); try { - final List enodeURIs = ethNetworkConfig.getBootNodes(); + final List enodeURIs = ethNetworkConfig.bootNodes(); PermissioningConfigurationValidator.areAllNodesInAllowlist( enodeURIs, permissioningConfiguration); fail("expected exception because sepolia bootnodes are not in node-allowlist"); diff --git a/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java b/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java index 638d221e0a..cf5a13d855 100644 --- a/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java +++ b/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java @@ -14,23 +14,23 @@ */ package org.hyperledger.besu.config; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.hyperledger.besu.config.JsonUtil.normalizeKeys; import org.hyperledger.besu.datatypes.Wei; -import java.io.IOException; +import java.net.URL; import java.util.Arrays; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; +import java.util.stream.Collectors; import java.util.stream.Stream; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.collect.Streams; -import com.google.common.io.Resources; /** The Genesis config file. */ public class GenesisConfigFile { @@ -42,10 +42,10 @@ public class GenesisConfigFile { /** The constant BASEFEE_AT_GENESIS_DEFAULT_VALUE. */ public static final Wei BASEFEE_AT_GENESIS_DEFAULT_VALUE = Wei.of(1_000_000_000L); - private final ObjectNode configRoot; + private final ObjectNode genesisRoot; private GenesisConfigFile(final ObjectNode config) { - this.configRoot = config; + this.genesisRoot = config; } /** @@ -54,46 +54,27 @@ public class GenesisConfigFile { * @return the genesis config file */ public static GenesisConfigFile mainnet() { - return genesisFileFromResources("/mainnet.json"); + return fromSource(GenesisConfigFile.class.getResource("/mainnet.json")); } /** - * Mainnet json node object node. - * - * @return the object node - */ - public static ObjectNode mainnetJsonNode() { - try { - final String jsonString = - Resources.toString(GenesisConfigFile.class.getResource("/mainnet.json"), UTF_8); - return JsonUtil.objectNodeFromString(jsonString, false); - } catch (final IOException e) { - throw new IllegalStateException(e); - } - } - - /** - * Development genesis config file. + * Genesis file from URL. * + * @param jsonSource the URL * @return the genesis config file */ - public static GenesisConfigFile development() { - return genesisFileFromResources("/dev.json"); + public static GenesisConfigFile fromSource(final URL jsonSource) { + return fromConfig(JsonUtil.objectNodeFromURL(jsonSource, false)); } /** - * Genesis file from resources genesis config file. + * Genesis file from resource. * - * @param resourceName the resource name + * @param jsonResource the resource name * @return the genesis config file */ - public static GenesisConfigFile genesisFileFromResources(final String resourceName) { - try { - return fromConfig( - Resources.toString(GenesisConfigFile.class.getResource(resourceName), UTF_8)); - } catch (final IOException e) { - throw new IllegalStateException(e); - } + public static GenesisConfigFile fromResource(final String jsonResource) { + return fromSource(GenesisConfigFile.class.getResource(jsonResource)); } /** @@ -133,7 +114,7 @@ public class GenesisConfigFile { */ public GenesisConfigOptions getConfigOptions(final Map overrides) { final ObjectNode config = - JsonUtil.getObjectNode(configRoot, "config").orElse(JsonUtil.createEmptyObjectNode()); + JsonUtil.getObjectNode(genesisRoot, "config").orElse(JsonUtil.createEmptyObjectNode()); Map overridesRef = overrides; @@ -154,7 +135,7 @@ public class GenesisConfigFile { * @return the stream */ public Stream streamAllocations() { - return JsonUtil.getObjectNode(configRoot, "alloc").stream() + return JsonUtil.getObjectNode(genesisRoot, "alloc").stream() .flatMap( allocations -> Streams.stream(allocations.fieldNames()) @@ -170,7 +151,7 @@ public class GenesisConfigFile { * @return the parent hash */ public String getParentHash() { - return JsonUtil.getString(configRoot, "parenthash", ""); + return JsonUtil.getString(genesisRoot, "parenthash", ""); } /** @@ -188,7 +169,7 @@ public class GenesisConfigFile { * @return the extra data */ public String getExtraData() { - return JsonUtil.getString(configRoot, "extradata", ""); + return JsonUtil.getString(genesisRoot, "extradata", ""); } /** @@ -206,7 +187,7 @@ public class GenesisConfigFile { * @return the base fee per gas */ public Optional getBaseFeePerGas() { - return JsonUtil.getString(configRoot, "basefeepergas") + return JsonUtil.getString(genesisRoot, "basefeepergas") .map(baseFeeStr -> Wei.of(parseLong("baseFeePerGas", baseFeeStr))); } @@ -235,7 +216,7 @@ public class GenesisConfigFile { * @return the mix hash */ public String getMixHash() { - return JsonUtil.getString(configRoot, "mixhash", ""); + return JsonUtil.getString(genesisRoot, "mixhash", ""); } /** @@ -244,7 +225,7 @@ public class GenesisConfigFile { * @return the nonce */ public String getNonce() { - return JsonUtil.getValueAsString(configRoot, "nonce", "0x0"); + return JsonUtil.getValueAsString(genesisRoot, "nonce", "0x0"); } /** @@ -253,7 +234,7 @@ public class GenesisConfigFile { * @return the excess blob gas */ public String getExcessBlobGas() { - return JsonUtil.getValueAsString(configRoot, "excessblobgas", "0x0"); + return JsonUtil.getValueAsString(genesisRoot, "excessblobgas", "0x0"); } /** @@ -262,7 +243,7 @@ public class GenesisConfigFile { * @return the blob gas used */ public String getBlobGasUsed() { - return JsonUtil.getValueAsString(configRoot, "blobgasused", "0x0"); + return JsonUtil.getValueAsString(genesisRoot, "blobgasused", "0x0"); } /** @@ -272,7 +253,7 @@ public class GenesisConfigFile { */ public String getParentBeaconBlockRoot() { return JsonUtil.getValueAsString( - configRoot, + genesisRoot, "parentbeaconblockroot", "0x0000000000000000000000000000000000000000000000000000000000000000"); } @@ -283,7 +264,7 @@ public class GenesisConfigFile { * @return the coinbase */ public Optional getCoinbase() { - return JsonUtil.getString(configRoot, "coinbase"); + return JsonUtil.getString(genesisRoot, "coinbase"); } /** @@ -292,7 +273,7 @@ public class GenesisConfigFile { * @return the timestamp */ public long getTimestamp() { - return parseLong("timestamp", JsonUtil.getValueAsString(configRoot, "timestamp", "0x0")); + return parseLong("timestamp", JsonUtil.getValueAsString(genesisRoot, "timestamp", "0x0")); } private String getRequiredString(final String key) { @@ -302,9 +283,9 @@ public class GenesisConfigFile { private String getFirstRequiredString(final String... keys) { List keysList = Arrays.asList(keys); return keysList.stream() - .filter(configRoot::has) + .filter(genesisRoot::has) .findFirst() - .map(key -> configRoot.get(key).asText()) + .map(key -> genesisRoot.get(key).asText()) .orElseThrow( () -> new IllegalArgumentException( @@ -343,4 +324,27 @@ public class GenesisConfigFile { public List getForkTimestamps() { return getConfigOptions().getForkBlockTimestamps(); } + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + final GenesisConfigFile that = (GenesisConfigFile) o; + return Objects.equals(genesisRoot, that.genesisRoot); + } + + @Override + public int hashCode() { + return Objects.hashCode(genesisRoot); + } + + @Override + public String toString() { + return "GenesisConfigFile{" + + "genesisRoot=" + + genesisRoot + + ", allocations=" + + streamAllocations().map(GenesisAllocation::toString).collect(Collectors.joining(",")) + + '}'; + } } diff --git a/config/src/main/java/org/hyperledger/besu/config/JsonGenesisConfigOptions.java b/config/src/main/java/org/hyperledger/besu/config/JsonGenesisConfigOptions.java index 5c1a203701..6118fc5080 100644 --- a/config/src/main/java/org/hyperledger/besu/config/JsonGenesisConfigOptions.java +++ b/config/src/main/java/org/hyperledger/besu/config/JsonGenesisConfigOptions.java @@ -24,6 +24,7 @@ import org.hyperledger.besu.datatypes.Wei; import java.math.BigInteger; import java.util.List; import java.util.Map; +import java.util.Objects; import java.util.Optional; import java.util.OptionalInt; import java.util.OptionalLong; @@ -615,4 +616,18 @@ public class JsonGenesisConfigOptions implements GenesisConfigOptions { .sorted() .toList(); } + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + final JsonGenesisConfigOptions that = (JsonGenesisConfigOptions) o; + return Objects.equals(configRoot, that.configRoot) + && Objects.equals(configOverrides, that.configOverrides); + } + + @Override + public int hashCode() { + return Objects.hash(configRoot, configOverrides); + } } diff --git a/config/src/main/java/org/hyperledger/besu/config/JsonUtil.java b/config/src/main/java/org/hyperledger/besu/config/JsonUtil.java index ef19bc7b83..da31a0ca0a 100644 --- a/config/src/main/java/org/hyperledger/besu/config/JsonUtil.java +++ b/config/src/main/java/org/hyperledger/besu/config/JsonUtil.java @@ -17,6 +17,7 @@ package org.hyperledger.besu.config; import org.hyperledger.besu.util.number.PositiveNumber; import java.io.IOException; +import java.net.URL; import java.util.Locale; import java.util.Map; import java.util.Optional; @@ -287,7 +288,7 @@ public class JsonUtil { * @return the object node */ public static ObjectNode objectNodeFromMap(final Map map) { - return (ObjectNode) getObjectMapper().valueToTree(map); + return getObjectMapper().valueToTree(map); } /** @@ -321,6 +322,27 @@ public class JsonUtil { } } + /** + * Object node from URL. + * + * @param jsonSource the URL of the json source + * @param allowComments true to allow comments + * @return the object node + */ + public static ObjectNode objectNodeFromURL(final URL jsonSource, final boolean allowComments) { + + final ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.configure(Feature.ALLOW_COMMENTS, allowComments); + try { + final JsonNode jsonNode = objectMapper.readTree(jsonSource); + validateType(jsonNode, JsonNodeType.OBJECT); + return (ObjectNode) jsonNode; + } catch (final IOException e) { + // Reading directly from a string should not raise an IOException, just catch and rethrow + throw new RuntimeException(e); + } + } + /** * Gets json. * @@ -455,14 +477,14 @@ public class JsonUtil { private static boolean validateLong(final JsonNode node) { if (!node.canConvertToLong()) { - throw new IllegalArgumentException("Cannot convert value to long: " + node.toString()); + throw new IllegalArgumentException("Cannot convert value to long: " + node); } return true; } private static boolean validateInt(final JsonNode node) { if (!node.canConvertToInt()) { - throw new IllegalArgumentException("Cannot convert value to integer: " + node.toString()); + throw new IllegalArgumentException("Cannot convert value to integer: " + node); } return true; } diff --git a/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java b/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java index 8f2d2e09bd..7e863b024d 100644 --- a/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java +++ b/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java @@ -59,7 +59,7 @@ class GenesisConfigFileTest { @Test void shouldLoadDevelopmentConfigFile() { - final GenesisConfigFile config = GenesisConfigFile.development(); + final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); // Sanity check some basic properties to confirm this is the dev file. assertThat(config.getConfigOptions().isEthHash()).isTrue(); assertThat(config.getConfigOptions().getChainId()).hasValue(DEVELOPMENT_CHAIN_ID); @@ -198,7 +198,7 @@ class GenesisConfigFileTest { @Test void assertSepoliaTerminalTotalDifficulty() { GenesisConfigOptions sepoliaOptions = - GenesisConfigFile.genesisFileFromResources("/sepolia.json").getConfigOptions(); + GenesisConfigFile.fromResource("/sepolia.json").getConfigOptions(); assertThat(sepoliaOptions.getTerminalTotalDifficulty()).isPresent(); assertThat(sepoliaOptions.getTerminalTotalDifficulty()) @@ -208,7 +208,7 @@ class GenesisConfigFileTest { @Test void assertGoerliTerminalTotalDifficulty() { GenesisConfigOptions goerliOptions = - GenesisConfigFile.genesisFileFromResources("/goerli.json").getConfigOptions(); + GenesisConfigFile.fromResource("/goerli.json").getConfigOptions(); assertThat(goerliOptions.getTerminalTotalDifficulty()).isPresent(); assertThat(goerliOptions.getTerminalTotalDifficulty()) @@ -218,7 +218,7 @@ class GenesisConfigFileTest { @Test void assertMainnetTerminalTotalDifficulty() { GenesisConfigOptions mainnetOptions = - GenesisConfigFile.genesisFileFromResources("/mainnet.json").getConfigOptions(); + GenesisConfigFile.fromResource("/mainnet.json").getConfigOptions(); assertThat(mainnetOptions.getTerminalTotalDifficulty()).isPresent(); // tentative as of 2022-08-11: @@ -229,7 +229,7 @@ class GenesisConfigFileTest { @Test void assertTerminalTotalDifficultyOverride() { GenesisConfigOptions sepoliaOverrideOptions = - GenesisConfigFile.genesisFileFromResources("/sepolia.json") + GenesisConfigFile.fromResource("/sepolia.json") .getConfigOptions(Map.of("terminalTotalDifficulty", String.valueOf(Long.MAX_VALUE))); assertThat(sepoliaOverrideOptions.getTerminalTotalDifficulty()).isPresent(); @@ -337,7 +337,7 @@ class GenesisConfigFileTest { @Test void testOverridePresent() { - final GenesisConfigFile config = GenesisConfigFile.development(); + final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); final int bigBlock = 999_999_999; final String bigBlockString = Integer.toString(bigBlock); final Map override = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); @@ -354,7 +354,7 @@ class GenesisConfigFileTest { @Test void testOverrideNull() { - final GenesisConfigFile config = GenesisConfigFile.development(); + final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); final Map override = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); override.put("istanbulBlock", null); override.put("chainId", null); @@ -368,7 +368,7 @@ class GenesisConfigFileTest { @Test void testOverrideCaseInsensitivity() { - final GenesisConfigFile config = GenesisConfigFile.development(); + final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); final int bigBlock = 999_999_999; final String bigBlockString = Integer.toString(bigBlock); final Map override = new HashMap<>(); @@ -387,7 +387,7 @@ class GenesisConfigFileTest { @Test void testOverrideEmptyString() { - final GenesisConfigFile config = GenesisConfigFile.development(); + final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); final Map override = new TreeMap<>(String.CASE_INSENSITIVE_ORDER); override.put("istanbulBlock", ""); override.put("chainId", ""); @@ -400,7 +400,7 @@ class GenesisConfigFileTest { @Test void testNoOverride() { - final GenesisConfigFile config = GenesisConfigFile.development(); + final GenesisConfigFile config = GenesisConfigFile.fromResource("/dev.json"); assertThat(config.getConfigOptions().getLondonBlockNumber()).hasValue(0); assertThat(config.getConfigOptions().getIstanbulBlockNumber()).isNotPresent(); @@ -413,7 +413,7 @@ class GenesisConfigFileTest { @Test void testConstantinopleFixShouldNotBeSupportedAlongPetersburg() { // petersburg node - final GenesisConfigFile config = GenesisConfigFile.genesisFileFromResources("/all_forks.json"); + final GenesisConfigFile config = GenesisConfigFile.fromResource("/all_forks.json"); assertThat(config.getConfigOptions().getPetersburgBlockNumber()).hasValue(7); diff --git a/config/src/test/java/org/hyperledger/besu/config/JsonUtilTest.java b/config/src/test/java/org/hyperledger/besu/config/JsonUtilTest.java index 962bb42f05..1b251d5cd1 100644 --- a/config/src/test/java/org/hyperledger/besu/config/JsonUtilTest.java +++ b/config/src/test/java/org/hyperledger/besu/config/JsonUtilTest.java @@ -17,6 +17,9 @@ package org.hyperledger.besu.config; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.List; import java.util.Locale; import java.util.Map; @@ -31,6 +34,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; public class JsonUtilTest { private final ObjectMapper mapper = new ObjectMapper(); @@ -654,6 +658,24 @@ public class JsonUtilTest { assertThat(result.get("b").asInt()).isEqualTo(2); } + @Test + public void objectNodeFromURL(@TempDir final Path folder) throws IOException { + final String jsonStr = + """ + { + "a":1, + "b":2, + "c":3 + } + """; + final var genesisFile = Files.writeString(folder.resolve("genesis.json"), jsonStr); + + final ObjectNode result = JsonUtil.objectNodeFromURL(genesisFile.toUri().toURL(), false); + assertThat(result.get("a").asInt()).isEqualTo(1); + assertThat(result.get("b").asInt()).isEqualTo(2); + assertThat(result.get("c").asInt()).isEqualTo(3); + } + @Test public void getJson() throws JsonProcessingException { final String jsonStr = "{\"a\":1, \"b\":2}"; diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeGenesisConfigHelper.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeGenesisConfigHelper.java index 80615552e7..dd0661ded4 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeGenesisConfigHelper.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeGenesisConfigHelper.java @@ -14,8 +14,6 @@ */ package org.hyperledger.besu.consensus.merge.blockcreation; -import static java.nio.charset.StandardCharsets.UTF_8; - import org.hyperledger.besu.config.GenesisAllocation; import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.consensus.merge.MergeProtocolSchedule; @@ -29,14 +27,12 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.stream.Stream; -import com.google.common.io.Resources; - public interface MergeGenesisConfigHelper { default GenesisConfigFile getPosGenesisConfigFile() { try { final URI uri = MergeGenesisConfigHelper.class.getResource("/posAtGenesis.json").toURI(); - return GenesisConfigFile.fromConfig(Resources.toString(uri.toURL(), UTF_8)); + return GenesisConfigFile.fromSource(uri.toURL()); } catch (final URISyntaxException | IOException e) { throw new IllegalStateException(e); } @@ -45,7 +41,7 @@ public interface MergeGenesisConfigHelper { default GenesisConfigFile getPowGenesisConfigFile() { try { final URI uri = MergeGenesisConfigHelper.class.getResource("/powAtGenesis.json").toURI(); - return GenesisConfigFile.fromConfig(Resources.toString(uri.toURL(), UTF_8)); + return GenesisConfigFile.fromSource(uri.toURL()); } catch (final URISyntaxException | IOException e) { throw new IllegalStateException(e); } diff --git a/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/support/TestContextBuilder.java b/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/support/TestContextBuilder.java index f66973ef6a..7a014986a2 100644 --- a/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/support/TestContextBuilder.java +++ b/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/support/TestContextBuilder.java @@ -23,6 +23,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; import org.hyperledger.besu.config.BftFork; +import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.config.JsonQbftConfigOptions; import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.config.QbftConfigOptions; @@ -115,7 +116,6 @@ import org.hyperledger.besu.testutil.TestClock; import org.hyperledger.besu.util.Subscribers; import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.time.Clock; import java.time.Instant; @@ -365,8 +365,9 @@ public class TestContextBuilder { } private GenesisState createGenesisBlock(final String genesisFile) throws IOException { - final String json = Files.readString(Path.of(genesisFile)); - return GenesisState.fromJson(json, ProtocolScheduleFixture.MAINNET); + return GenesisState.fromConfig( + GenesisConfigFile.fromSource(Path.of(genesisFile).toUri().toURL()), + ProtocolScheduleFixture.MAINNET); } private static ControllerAndState createControllerAndFinalState( diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockTransactionSelectorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockTransactionSelectorTest.java index 36b965697d..dba3ef4be9 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockTransactionSelectorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockTransactionSelectorTest.java @@ -220,7 +220,7 @@ public abstract class AbstractBlockTransactionSelectorTest { public void emptyPendingTransactionsResultsInEmptyVettingResult() { final ProtocolSchedule protocolSchedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.development().getConfigOptions(), + GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager()); diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LegacyFeeMarketBlockTransactionSelectorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LegacyFeeMarketBlockTransactionSelectorTest.java index 91b58fab8d..3b1ae938f7 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LegacyFeeMarketBlockTransactionSelectorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LegacyFeeMarketBlockTransactionSelectorTest.java @@ -51,8 +51,7 @@ public class LegacyFeeMarketBlockTransactionSelectorTest @Override protected GenesisConfigFile getGenesisConfigFile() { - return GenesisConfigFile.genesisFileFromResources( - "/block-transaction-selector/gas-price-genesis.json"); + return GenesisConfigFile.fromResource("/block-transaction-selector/gas-price-genesis.json"); } @Override diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LondonFeeMarketBlockTransactionSelectorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LondonFeeMarketBlockTransactionSelectorTest.java index 5fb915fd09..e9bfcfb762 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LondonFeeMarketBlockTransactionSelectorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/LondonFeeMarketBlockTransactionSelectorTest.java @@ -58,8 +58,7 @@ public class LondonFeeMarketBlockTransactionSelectorTest @Override protected GenesisConfigFile getGenesisConfigFile() { - return GenesisConfigFile.genesisFileFromResources( - "/block-transaction-selector/london-genesis.json"); + return GenesisConfigFile.fromResource("/block-transaction-selector/london-genesis.json"); } @Override diff --git a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java index f0ffbb9862..60b40c5f24 100644 --- a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java +++ b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java @@ -45,14 +45,11 @@ import org.hyperledger.besu.testutil.BlockTestUtil.ChainResources; import java.io.IOException; import java.net.URISyntaxException; -import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.ArrayList; import java.util.Collections; import java.util.List; -import com.google.common.io.Resources; - public class BlockchainSetupUtil { private final GenesisState genesisState; private final MutableBlockchain blockchain; @@ -169,13 +166,12 @@ public class BlockchainSetupUtil { final ProtocolContextProvider protocolContextProvider, final EthScheduler scheduler) { try { - final String genesisJson = - Resources.toString(chainResources.getGenesisURL(), StandardCharsets.UTF_8); - - final GenesisConfigFile genesisConfigFile = GenesisConfigFile.fromConfig(genesisJson); + final GenesisConfigFile genesisConfigFile = + GenesisConfigFile.fromSource(chainResources.getGenesisURL()); final ProtocolSchedule protocolSchedule = protocolScheduleProvider.get(genesisConfigFile); - final GenesisState genesisState = GenesisState.fromJson(genesisJson, protocolSchedule); + final GenesisState genesisState = + GenesisState.fromConfig(genesisConfigFile, protocolSchedule); final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); final WorldStateArchive worldArchive = storageFormat == DataStorageFormat.BONSAI diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java index afb0e195f3..adaf4c476b 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java @@ -33,7 +33,7 @@ public class FixedProtocolScheduleTest { final ProtocolSchedule schedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.development().getConfigOptions(), + GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager()); diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/MainnetProtocolScheduleTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/MainnetProtocolScheduleTest.java index a8b5b772f8..77c8714217 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/MainnetProtocolScheduleTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/MainnetProtocolScheduleTest.java @@ -22,9 +22,6 @@ import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.evm.internal.EvmConfiguration; -import java.nio.charset.StandardCharsets; - -import com.google.common.io.Resources; import org.assertj.core.api.Assertions; import org.junit.jupiter.api.Test; @@ -127,13 +124,10 @@ public class MainnetProtocolScheduleTest { } @Test - public void shouldCreateGoerliConfig() throws Exception { + public void shouldCreateGoerliConfig() { final ProtocolSchedule sched = MainnetProtocolSchedule.fromConfig( - GenesisConfigFile.fromConfig( - Resources.toString( - this.getClass().getResource("/goerli.json"), StandardCharsets.UTF_8)) - .getConfigOptions(), + GenesisConfigFile.fromResource("/goerli.json").getConfigOptions(), EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager()); diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java index e3abbe6f0b..82bf920995 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java @@ -105,11 +105,11 @@ public abstract class AbstractIsolationTests { .createKeyPair(SECPPrivateKey.create(Bytes32.fromHexString(key), "ECDSA")); protected final ProtocolSchedule protocolSchedule = MainnetProtocolSchedule.fromConfig( - GenesisConfigFile.development().getConfigOptions(), + GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), MiningParameters.MINING_DISABLED, new BadBlockManager()); protected final GenesisState genesisState = - GenesisState.fromConfig(GenesisConfigFile.development(), protocolSchedule); + GenesisState.fromConfig(GenesisConfigFile.fromResource("/dev.json"), protocolSchedule); protected final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); protected final TransactionPoolConfiguration poolConfiguration = @@ -140,7 +140,7 @@ public abstract class AbstractIsolationTests { MiningParameters.newDefault())); protected final List accounts = - GenesisConfigFile.development() + GenesisConfigFile.fromResource("/dev.json") .streamAllocations() .filter(ga -> ga.getPrivateKey().isPresent()) .collect(Collectors.toList()); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockBodiesMessageTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockBodiesMessageTest.java index 1a69dd1dab..ac3b8f2fc6 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockBodiesMessageTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockBodiesMessageTest.java @@ -56,7 +56,7 @@ public final class BlockBodiesMessageTest { public void setup() { protocolSchedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.development().getConfigOptions(), + GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockHeadersMessageTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockHeadersMessageTest.java index 08d2262c2d..2b9105ed46 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockHeadersMessageTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/BlockHeadersMessageTest.java @@ -63,7 +63,7 @@ public final class BlockHeadersMessageTest { final List readHeaders = message.getHeaders( FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.development().getConfigOptions(), + GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/ChainHeadTrackerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/ChainHeadTrackerTest.java index 9912d66f38..393824af75 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/ChainHeadTrackerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/ChainHeadTrackerTest.java @@ -53,7 +53,7 @@ public class ChainHeadTrackerTest { private final ProtocolSchedule protocolSchedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.development().getConfigOptions(), + GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TestNode.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TestNode.java index 62dde1f8f4..743f0b47e2 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TestNode.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TestNode.java @@ -110,10 +110,10 @@ public class TestNode implements Closeable { .setBindPort(listenPort) .setSupportedProtocols(EthProtocol.get())); - final GenesisConfigFile genesisConfigFile = GenesisConfigFile.development(); + final GenesisConfigFile genesisConfigFile = GenesisConfigFile.fromResource("/dev.json"); final ProtocolSchedule protocolSchedule = FixedDifficultyProtocolSchedule.create( - GenesisConfigFile.development().getConfigOptions(), + GenesisConfigFile.fromResource("/dev.json").getConfigOptions(), false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, diff --git a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java index 81902e52c4..1fd4f58a4b 100644 --- a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java +++ b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java @@ -14,7 +14,6 @@ */ package org.hyperledger.besu.ethereum.permissioning; -import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryBlockchain; @@ -42,7 +41,6 @@ import org.hyperledger.besu.plugin.services.metrics.Counter; import java.io.IOException; import java.math.BigInteger; -import com.google.common.io.Resources; import org.apache.tuweni.bytes.Bytes; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -57,13 +55,13 @@ public class TransactionSmartContractPermissioningControllerTest { @Mock private Counter checkUnpermittedCounter; private TransactionSmartContractPermissioningController setupController( - final String resourceName, final String contractAddressString) throws IOException { + final String resourceName, final String contractAddressString) { 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); + GenesisState.fromConfig( + GenesisConfigFile.fromSource(this.getClass().getResource(resourceName)), + protocolSchedule); final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); final WorldStateArchive worldArchive = createInMemoryWorldStateArchive();