From c57c2ace830927116af0f022b5808fcbc13496eb Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 10 Oct 2023 15:44:53 +0200 Subject: [PATCH 01/24] Refactor mining options Signed-off-by: Fabio Di Fabio --- .../dsl/node/ProcessBesuNodeRunner.java | 3 +- .../BesuNodeConfigurationBuilder.java | 32 +- .../node/configuration/BesuNodeFactory.java | 16 +- .../bft/BftMiningAcceptanceTest.java | 16 +- .../org/hyperledger/besu/cli/BesuCommand.java | 251 +++--- .../besu/cli/DefaultCommandValues.java | 5 +- .../cli/options/stable/MiningOptions.java | 181 +++++ .../subcommands/blocks/BlocksSubCommand.java | 44 +- .../CliqueBesuControllerBuilder.java | 3 +- .../TransitionBesuControllerBuilder.java | 8 +- .../hyperledger/besu/PrivacyReorgTest.java | 13 +- .../org/hyperledger/besu/PrivacyTest.java | 4 +- .../java/org/hyperledger/besu/RunnerTest.java | 4 +- .../chainexport/RlpBlockExporterTest.java | 4 +- .../chainimport/JsonBlockImporterTest.java | 12 +- .../chainimport/RlpBlockImporterTest.java | 8 +- .../hyperledger/besu/cli/BesuCommandTest.java | 57 +- .../TransitionControllerBuilderTest.java | 5 +- .../besu/services/BesuEventsImplTest.java | 9 +- .../blockcreation/CliqueBlockCreator.java | 23 +- .../blockcreation/CliqueMinerExecutor.java | 12 +- .../blockcreation/CliqueBlockCreatorTest.java | 56 +- .../CliqueMinerExecutorTest.java | 74 +- .../bft/blockcreation/BftBlockCreator.java | 23 +- .../blockcreation/BftBlockCreatorFactory.java | 47 +- .../ibft/support/TestContextBuilder.java | 20 +- .../blockcreation/BftBlockCreatorTest.java | 25 +- .../blockcreation/MergeBlockCreator.java | 31 +- .../merge/blockcreation/MergeCoordinator.java | 79 +- .../blockcreation/MergeCoordinatorTest.java | 19 +- .../merge/blockcreation/MergeReorgTest.java | 5 +- .../qbft/support/TestContextBuilder.java | 20 +- .../QbftBlockCreatorFactory.java | 4 +- .../QbftBlockCreatorFactoryTest.java | 12 +- .../EthGetFilterChangesIntegrationTest.java | 9 +- .../EthGetFilterChangesIntegrationTest.java | 9 +- .../besu/ethereum/api/ApiConfiguration.java | 6 +- .../ethereum/api/query/BlockchainQueries.java | 2 +- .../AbstractEthGraphQLHttpServiceTest.java | 2 +- .../internal/methods/EthGasPriceTest.java | 2 +- .../blockcreation/AbstractBlockCreator.java | 33 +- .../blockcreation/AbstractMinerExecutor.java | 33 +- .../blockcreation/NoopMiningCoordinator.java | 2 +- .../blockcreation/PoWBlockCreator.java | 17 +- .../blockcreation/PoWMinerExecutor.java | 12 +- .../txselection/BlockSelectionContext.java | 6 +- .../txselection/BlockTransactionSelector.java | 94 ++- .../BlockSizeTransactionSelector.java | 4 +- .../selectors/PriceTransactionSelector.java | 9 +- .../AbstractBlockCreatorTest.java | 33 +- .../AbstractBlockTransactionSelectorTest.java | 16 +- .../blockcreation/PoWBlockCreatorTest.java | 72 +- .../blockcreation/PoWMinerExecutorTest.java | 9 +- .../besu/ethereum/core/MiningParameters.java | 756 ++++++++++-------- .../bonsai/AbstractIsolationTests.java | 35 +- .../eth/transactions/TransactionPool.java | 4 +- .../eth/manager/EthProtocolManagerTest.java | 10 +- .../ethtaskutils/AbstractMessageTaskTest.java | 9 +- .../AbstractTransactionPoolTest.java | 15 +- .../ethereum/eth/transactions/TestNode.java | 9 +- .../TransactionPoolFactoryTest.java | 16 +- .../ethereum/retesteth/RetestethContext.java | 6 +- .../retesteth/methods/TestMineBlocks.java | 17 +- .../data/TransactionSelectionResult.java | 6 + 64 files changed, 1533 insertions(+), 845 deletions(-) create mode 100644 besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java index 048e40553ba..f0f2faf9087 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java @@ -108,7 +108,8 @@ public void startNode(final BesuNode node) { params.add(node.getMiningParameters().getStratumNetworkInterface()); params.add("--min-gas-price"); params.add( - Integer.toString(node.getMiningParameters().getMinTransactionGasPrice().intValue())); + Integer.toString( + node.getMiningParameters().getDynamic().getMinTransactionGasPrice().intValue())); params.add("--Xminer-remote-sealers-limit"); params.add(Integer.toString(node.getMiningParameters().getRemoteSealersLimit())); params.add("--Xminer-remote-sealers-hashrate-ttl"); diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java index 4943aaf60eb..1689e2d22e3 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java @@ -30,6 +30,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.api.tls.FileBasedPasswordProvider; import org.hyperledger.besu.ethereum.core.AddressHelpers; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.p2p.config.NetworkingConfiguration; @@ -56,11 +57,19 @@ public class BesuNodeConfigurationBuilder { private String name; private Optional dataPath = Optional.empty(); private MiningParameters miningParameters = - new MiningParameters.Builder() - .miningEnabled(false) + ImmutableMiningParameters.builder() + .isMiningEnabled(false) .coinbase(AddressHelpers.ofValue(1)) - .minTransactionGasPrice(Wei.of(1000)) - .build(); + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.of(1000)) + .toParameters(); + + // new MiningParameters.Builder() + // .miningEnabled(false) + // .coinbase(AddressHelpers.ofValue(1)) + // .minTransactionGasPrice(Wei.of(1000)) + // .build(); private JsonRpcConfiguration jsonRpcConfiguration = JsonRpcConfiguration.createDefault(); private JsonRpcConfiguration engineRpcConfiguration = JsonRpcConfiguration.createEngineDefault(); private WebSocketConfiguration webSocketConfiguration = WebSocketConfiguration.createDefault(); @@ -114,11 +123,18 @@ public BesuNodeConfigurationBuilder miningEnabled() { public BesuNodeConfigurationBuilder miningEnabled(final boolean enabled) { this.miningParameters = - new MiningParameters.Builder() - .miningEnabled(enabled) - .minTransactionGasPrice(Wei.of(1000)) + ImmutableMiningParameters.builder() + .isMiningEnabled(enabled) .coinbase(AddressHelpers.ofValue(1)) - .build(); + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.of(1000)) + .toParameters(); + // new MiningParameters.Builder() + // .miningEnabled(enabled) + // .minTransactionGasPrice(Wei.of(1000)) + // .coinbase(AddressHelpers.ofValue(1)) + // .build(); this.jsonRpcConfiguration.addRpcApi(RpcApis.MINER.name()); return this; } diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java index bd635c6bfcf..6af79637e07 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java @@ -26,6 +26,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration; import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.core.AddressHelpers; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryPrivacyStorageProvider; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; @@ -303,11 +304,18 @@ public BesuNode createNodeWithMultiTenantedPrivacy( .build(); final MiningParameters miningParameters = - new MiningParameters.Builder() - .minTransactionGasPrice(Wei.ZERO) + ImmutableMiningParameters.builder() + .isMiningEnabled(true) .coinbase(AddressHelpers.ofValue(1)) - .miningEnabled(true) - .build(); + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .toParameters(); + // new MiningParameters.Builder() + // .minTransactionGasPrice(Wei.ZERO) + // .coinbase(AddressHelpers.ofValue(1)) + // .miningEnabled(true) + // .build(); return create( new BesuNodeConfigurationBuilder() diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java index e529268cb59..1b0e2bfe595 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java @@ -17,6 +17,7 @@ import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.core.AddressHelpers; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.tests.acceptance.dsl.account.Account; import org.hyperledger.besu.tests.acceptance.dsl.blockchain.Amount; @@ -59,11 +60,18 @@ public void shouldMineOnSingleNodeWithPaidGas_Berlin() throws Exception { public void shouldMineOnSingleNodeWithFreeGas_Berlin() throws Exception { final BesuNode minerNode = nodeFactory.createNode(besu, "miner1"); final MiningParameters zeroGasMiningParams = - new MiningParameters.Builder() - .miningEnabled(true) - .minTransactionGasPrice(Wei.ZERO) + ImmutableMiningParameters.builder() + .isMiningEnabled(true) .coinbase(AddressHelpers.ofValue(1)) - .build(); + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .toParameters(); + // new MiningParameters.Builder() + // .miningEnabled(true) + // .minTransactionGasPrice(Wei.ZERO) + // .coinbase(AddressHelpers.ofValue(1)) + // .build(); minerNode.setMiningParameters(zeroGasMiningParams); cluster.start(minerNode); 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 75c44198877..87413babfcd 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -307,6 +307,10 @@ public class BesuCommand implements DefaultCommandValues, Runnable { final org.hyperledger.besu.cli.options.stable.TransactionPoolOptions stableTransactionPoolOptions = TransactionPoolOptions.create(); + @CommandLine.ArgGroup(validate = false, heading = "@|bold Miner Options|@%n") + final org.hyperledger.besu.cli.options.stable.MiningOptions stableMiningOptions = + org.hyperledger.besu.cli.options.stable.MiningOptions.create(); + private final RunnerBuilder runnerBuilder; private final BesuController.Builder controllerBuilderFactory; private final BesuPluginContextImpl besuPluginContext; @@ -1069,61 +1073,60 @@ static class MetricsOptionGroup { private final Long reorgLoggingThreshold = 6L; // Miner options group - @CommandLine.ArgGroup(validate = false, heading = "@|bold Miner Options|@%n") - MinerOptionGroup minerOptionGroup = new MinerOptionGroup(); - - static class MinerOptionGroup { - @Option( - names = {"--miner-enabled"}, - description = "Set if node will perform mining (default: ${DEFAULT-VALUE})") - private final Boolean isMiningEnabled = false; - - @Option( - names = {"--miner-stratum-enabled"}, - description = "Set if node will perform Stratum mining (default: ${DEFAULT-VALUE})") - private final Boolean iStratumMiningEnabled = false; - - @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings. - @Option( - names = {"--miner-stratum-host"}, - description = "Host for Stratum network mining service (default: ${DEFAULT-VALUE})") - private String stratumNetworkInterface = "0.0.0.0"; - @Option( - names = {"--miner-stratum-port"}, - description = "Stratum port binding (default: ${DEFAULT-VALUE})") - private final Integer stratumPort = 8008; - - @Option( - names = {"--miner-coinbase"}, - description = - "Account to which mining rewards are paid. You must specify a valid coinbase if " - + "mining is enabled using --miner-enabled option", - arity = "1") - private final Address coinbase = null; - - @Option( - names = {"--miner-extra-data"}, - description = - "A hex string representing the (32) bytes to be included in the extra data " - + "field of a mined block (default: ${DEFAULT-VALUE})", - arity = "1") - private final Bytes extraData = DEFAULT_EXTRA_DATA; - } - - @Option( - names = {"--min-gas-price"}, - description = - "Minimum price (in Wei) offered by a transaction for it to be included in a mined " - + "block (default: ${DEFAULT-VALUE})", - arity = "1") - private final Wei minTransactionGasPrice = DEFAULT_MIN_TRANSACTION_GAS_PRICE; - - @Option( - names = {"--min-block-occupancy-ratio"}, - description = "Minimum occupancy ratio for a mined block (default: ${DEFAULT-VALUE})", - arity = "1") - private final Double minBlockOccupancyRatio = DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; + // static class MinerOptionGroup { + // @Option( + // names = {"--miner-enabled"}, + // description = "Set if node will perform mining (default: ${DEFAULT-VALUE})") + // private final Boolean isMiningEnabled = false; + // + // @Option( + // names = {"--miner-stratum-enabled"}, + // description = "Set if node will perform Stratum mining (default: ${DEFAULT-VALUE})") + // private final Boolean iStratumMiningEnabled = false; + // + // @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final + // Strings. + // @Option( + // names = {"--miner-stratum-host"}, + // description = "Host for Stratum network mining service (default: ${DEFAULT-VALUE})") + // private String stratumNetworkInterface = "0.0.0.0"; + // + // @Option( + // names = {"--miner-stratum-port"}, + // description = "Stratum port binding (default: ${DEFAULT-VALUE})") + // private final Integer stratumPort = 8008; + // + // @Option( + // names = {"--miner-coinbase"}, + // description = + // "Account to which mining rewards are paid. You must specify a valid coinbase if " + // + "mining is enabled using --miner-enabled option", + // arity = "1") + // private final Address coinbase = null; + // + // @Option( + // names = {"--miner-extra-data"}, + // description = + // "A hex string representing the (32) bytes to be included in the extra data " + // + "field of a mined block (default: ${DEFAULT-VALUE})", + // arity = "1") + // private final Bytes extraData = DEFAULT_EXTRA_DATA; + // } + + // @Option( + // names = {"--min-gas-price"}, + // description = + // "Minimum price (in Wei) offered by a transaction for it to be included in a mined " + // + "block (default: ${DEFAULT-VALUE})", + // arity = "1") + // private final Wei minTransactionGasPrice = DEFAULT_MIN_TRANSACTION_GAS_PRICE; + + // @Option( + // names = {"--min-block-occupancy-ratio"}, + // description = "Minimum occupancy ratio for a mined block (default: ${DEFAULT-VALUE})", + // arity = "1") + // private final Double minBlockOccupancyRatio = DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; @Option( names = {"--pruning-enabled"}, @@ -1311,6 +1314,7 @@ static class PermissionsOptionGroup { private Collection staticNodes; private BesuController besuController; private BesuConfiguration pluginCommonConfiguration; + private MiningParameters miningParameters; private BesuComponent besuComponent; private final Supplier metricsSystem = @@ -1723,7 +1727,7 @@ private void validatePluginOptions() { "--privacy-marker-transaction-signing-key-file can not be used in conjunction with a plugin that specifies a PrivateMarkerTransactionFactory"); } - if (Wei.ZERO.compareTo(minTransactionGasPrice) < 0 + if (Wei.ZERO.compareTo(miningParameters.getDynamic().getMinTransactionGasPrice()) < 0 && (privacyOptionGroup.privateMarkerTransactionSigningKeyPath == null && (privacyPluginService == null || privacyPluginService.getPrivateMarkerTransactionFactory() == null))) { @@ -1868,20 +1872,24 @@ private void validateRequiredOptions() { @SuppressWarnings("ConstantConditions") private void validateMiningParams() { - if (Boolean.TRUE.equals(minerOptionGroup.isMiningEnabled) - && minerOptionGroup.coinbase == null) { - throw new ParameterException( - this.commandLine, - "Unable to mine without a valid coinbase. Either disable mining (remove --miner-enabled) " - + "or specify the beneficiary of mining (via --miner-coinbase
)"); - } - if (Boolean.FALSE.equals(minerOptionGroup.isMiningEnabled) - && Boolean.TRUE.equals(minerOptionGroup.iStratumMiningEnabled)) { - throw new ParameterException( - this.commandLine, - "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) " - + "or specify mining is enabled (--miner-enabled)"); - } + stableMiningOptions.validate( + commandLine, logger, isMergeEnabled(), getActualGenesisConfigOptions().isEthHash()); + // if (Boolean.TRUE.equals(minerOptionGroup.isMiningEnabled) + // && minerOptionGroup.coinbase == null) { + // throw new ParameterException( + // this.commandLine, + // "Unable to mine without a valid coinbase. Either disable mining (remove + // --miner-enabled) " + // + "or specify the beneficiary of mining (via --miner-coinbase
)"); + // } + // if (Boolean.FALSE.equals(minerOptionGroup.isMiningEnabled) + // && Boolean.TRUE.equals(minerOptionGroup.iStratumMiningEnabled)) { + // throw new ParameterException( + // this.commandLine, + // "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining + // (remove --miner-stratum-enabled) " + // + "or specify mining is enabled (--miner-enabled)"); + // } if (unstableMiningOptions.getPosBlockCreationMaxTime() <= 0 || unstableMiningOptions.getPosBlockCreationMaxTime() > MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { @@ -2067,30 +2075,30 @@ private void issueOptionWarnings() { "--p2p-port", "--remote-connections-max-percentage")); - // Check that block producer options work - if (!isMergeEnabled() && getActualGenesisConfigOptions().isEthHash()) { - CommandLineUtils.checkOptionDependencies( - logger, - commandLine, - "--miner-enabled", - !minerOptionGroup.isMiningEnabled, - asList( - "--miner-coinbase", - "--min-gas-price", - "--min-block-occupancy-ratio", - "--miner-extra-data")); - - // Check that mining options are able to work - CommandLineUtils.checkOptionDependencies( - logger, - commandLine, - "--miner-enabled", - !minerOptionGroup.isMiningEnabled, - asList( - "--miner-stratum-enabled", - "--Xminer-remote-sealers-limit", - "--Xminer-remote-sealers-hashrate-ttl")); - } + // // Check that block producer options work + // if (!isMergeEnabled() && getActualGenesisConfigOptions().isEthHash()) { + // CommandLineUtils.checkOptionDependencies( + // logger, + // commandLine, + // "--miner-enabled", + // !minerOptionGroup.isMiningEnabled, + // asList( + // "--miner-coinbase", + // "--min-gas-price", + // "--min-block-occupancy-ratio", + // "--miner-extra-data")); + // + // // Check that mining options are able to work + // CommandLineUtils.checkOptionDependencies( + // logger, + // commandLine, + // "--miner-enabled", + // !minerOptionGroup.isMiningEnabled, + // asList( + // "--miner-stratum-enabled", + // "--Xminer-remote-sealers-limit", + // "--Xminer-remote-sealers-hashrate-ttl")); + // } CommandLineUtils.failIfOptionDoesntMeetRequirement( commandLine, @@ -2135,6 +2143,8 @@ private void configure() throws Exception { ethNetworkConfig = updateNetworkConfig(network); + miningParameters = buildMininingParameters(); + jsonRpcConfiguration = jsonRpcConfiguration( jsonRPCHttpOptionGroup.rpcHttpPort, jsonRPCHttpOptionGroup.rpcHttpApis, hostsAllowlist); @@ -2245,26 +2255,29 @@ public BesuControllerBuilder getControllerBuilder() { .transactionSelectorFactory(getTransactionSelectorFactory()) .pluginTransactionValidatorFactory(getPluginTransactionValidatorFactory()) .dataDirectory(dataDir()) - .miningParameters( - new MiningParameters.Builder() - .coinbase(minerOptionGroup.coinbase) - .targetGasLimit(targetGasLimit) - .minTransactionGasPrice(minTransactionGasPrice) - .extraData(minerOptionGroup.extraData) - .miningEnabled(minerOptionGroup.isMiningEnabled) - .stratumMiningEnabled(minerOptionGroup.iStratumMiningEnabled) - .stratumNetworkInterface(minerOptionGroup.stratumNetworkInterface) - .stratumPort(minerOptionGroup.stratumPort) - .stratumExtranonce(unstableMiningOptions.getStratumExtranonce()) - .minBlockOccupancyRatio(minBlockOccupancyRatio) - .remoteSealersLimit(unstableMiningOptions.getRemoteSealersLimit()) - .remoteSealersTimeToLive(unstableMiningOptions.getRemoteSealersTimeToLive()) - .powJobTimeToLive(unstableMiningOptions.getPowJobTimeToLive()) - .maxOmmerDepth(unstableMiningOptions.getMaxOmmersDepth()) - .posBlockCreationMaxTime(unstableMiningOptions.getPosBlockCreationMaxTime()) - .posBlockCreationRepetitionMinDuration( - unstableMiningOptions.getPosBlockCreationRepetitionMinDuration()) - .build()) + // .miningParameters( + // new MiningParameters.Builder() + // .coinbase(minerOptionGroup.coinbase) + // .targetGasLimit(targetGasLimit) + // .minTransactionGasPrice(minTransactionGasPrice) + // .extraData(minerOptionGroup.extraData) + // .miningEnabled(minerOptionGroup.isMiningEnabled) + // .stratumMiningEnabled(minerOptionGroup.iStratumMiningEnabled) + // .stratumNetworkInterface(minerOptionGroup.stratumNetworkInterface) + // .stratumPort(minerOptionGroup.stratumPort) + // .stratumExtranonce(unstableMiningOptions.getStratumExtranonce()) + // .minBlockOccupancyRatio(minBlockOccupancyRatio) + // .remoteSealersLimit(unstableMiningOptions.getRemoteSealersLimit()) + // + // .remoteSealersTimeToLive(unstableMiningOptions.getRemoteSealersTimeToLive()) + // .powJobTimeToLive(unstableMiningOptions.getPowJobTimeToLive()) + // .maxOmmerDepth(unstableMiningOptions.getMaxOmmersDepth()) + // + // .posBlockCreationMaxTime(unstableMiningOptions.getPosBlockCreationMaxTime()) + // .posBlockCreationRepetitionMinDuration( + // unstableMiningOptions.getPosBlockCreationRepetitionMinDuration()) + // .build()) + .miningParameters(miningParameters) .transactionPoolConfiguration(buildTransactionPoolConfiguration()) .nodeKey(new NodeKey(securityModule())) .metricsSystem(metricsSystem.get()) @@ -2607,7 +2620,9 @@ private ApiConfiguration apiConfiguration() { return ImmutableApiConfiguration.builder() .gasPriceBlocks(apiGasPriceBlocks) .gasPricePercentile(apiGasPricePercentile) - .gasPriceMin(minTransactionGasPrice.toLong()) + .gasPriceMinSupplier( + miningParameters.getDynamic().getMinTransactionGasPrice().getAsBigInteger() + ::longValueExact) .gasPriceMax(apiGasPriceMax) .build(); } @@ -2943,6 +2958,10 @@ private TransactionPoolConfiguration buildTransactionPoolConfiguration() { .build(); } + private MiningParameters buildMininingParameters() { + return stableMiningOptions.toDomainObject(); + } + private boolean isPruningEnabled() { return pruningEnabled; } @@ -3338,7 +3357,9 @@ private List getEffectivePorts() { addPortIfEnabled( effectivePorts, metricsOptionGroup.metricsPort, metricsOptionGroup.isMetricsEnabled); addPortIfEnabled( - effectivePorts, minerOptionGroup.stratumPort, minerOptionGroup.iStratumMiningEnabled); + effectivePorts, + miningParameters.getStratumPort(), + miningParameters.isStratumMiningEnabled()); return effectivePorts; } diff --git a/besu/src/main/java/org/hyperledger/besu/cli/DefaultCommandValues.java b/besu/src/main/java/org/hyperledger/besu/cli/DefaultCommandValues.java index 8b837268327..f15dc412412 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/DefaultCommandValues.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/DefaultCommandValues.java @@ -14,7 +14,6 @@ */ package org.hyperledger.besu.cli; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.api.jsonrpc.authentication.JwtAlgorithm; import org.hyperledger.besu.ethereum.p2p.config.RlpxConfiguration; import org.hyperledger.besu.nat.NatMethod; @@ -59,9 +58,9 @@ public interface DefaultCommandValues { /** The constant MANDATORY_NODE_ID_FORMAT_HELP. */ String MANDATORY_NODE_ID_FORMAT_HELP = ""; /** The constant DEFAULT_MIN_TRANSACTION_GAS_PRICE. */ - Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); + // Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); /** The constant DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO. */ - Double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; + // Double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; /** The constant DEFAULT_EXTRA_DATA. */ Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY; /** The constant PERMISSIONING_CONFIG_LOCATION. */ diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java new file mode 100644 index 00000000000..d7f3320ef96 --- /dev/null +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java @@ -0,0 +1,181 @@ +/* + * Copyright Hyperledger Besu Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.cli.options.stable; + +import static java.util.Arrays.asList; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_EXTRA_DATA; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE; + +import org.hyperledger.besu.cli.options.CLIOptions; +import org.hyperledger.besu.cli.util.CommandLineUtils; +import org.hyperledger.besu.datatypes.Address; +import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.MiningParameters; + +import java.util.List; + +import org.apache.tuweni.bytes.Bytes; +import org.slf4j.Logger; +import picocli.CommandLine; +import picocli.CommandLine.Option; + +/** The Mining CLI options. */ +public class MiningOptions implements CLIOptions { + + @Option( + names = {"--miner-enabled"}, + description = "Set if node will perform mining (default: ${DEFAULT-VALUE})") + private final Boolean isMiningEnabled = false; + + @Option( + names = {"--miner-stratum-enabled"}, + description = "Set if node will perform Stratum mining (default: ${DEFAULT-VALUE})") + private final Boolean iStratumMiningEnabled = false; + + @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings. + @Option( + names = {"--miner-stratum-host"}, + description = "Host for Stratum network mining service (default: ${DEFAULT-VALUE})") + private String stratumNetworkInterface = "0.0.0.0"; + + @Option( + names = {"--miner-stratum-port"}, + description = "Stratum port binding (default: ${DEFAULT-VALUE})") + private final Integer stratumPort = 8008; + + @Option( + names = {"--miner-coinbase"}, + description = + "Account to which mining rewards are paid. You must specify a valid coinbase if " + + "mining is enabled using --miner-enabled option", + arity = "1") + private final Address coinbase = null; + + @Option( + names = {"--miner-extra-data"}, + description = + "A hex string representing the (32) bytes to be included in the extra data " + + "field of a mined block (default: ${DEFAULT-VALUE})", + arity = "1") + private final Bytes extraData = DEFAULT_EXTRA_DATA; + + @Option( + names = {"--min-block-occupancy-ratio"}, + description = "Minimum occupancy ratio for a mined block (default: ${DEFAULT-VALUE})", + arity = "1") + private final Double minBlockOccupancyRatio = DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; + + @Option( + names = {"--min-gas-price"}, + description = + "Minimum price (in Wei) offered by a transaction for it to be included in a mined " + + "block (default: ${DEFAULT-VALUE})", + arity = "1") + private final Wei minTransactionGasPrice = DEFAULT_MIN_TRANSACTION_GAS_PRICE; + + @Option( + names = {"--target-gas-limit"}, + description = + "Sets target gas limit per block. If set, each block's gas limit will approach this setting over time if the current gas limit is different.") + private final Long targetGasLimit = null; + + private MiningOptions() {} + + /** + * Create mining options. + * + * @return the mining options + */ + public static MiningOptions create() { + return new MiningOptions(); + } + + /** + * Validate that there are no inconsistencies in the specified options. For example that the + * options are valid for the selected implementation. + * + * @param commandLine the full commandLine to check all the options specified by the user + * @param logger the logger + * @param isMergeEnabled is the Merge enabled? + * @param isEthHash is EthHash? + */ + public void validate( + final CommandLine commandLine, + final Logger logger, + final boolean isMergeEnabled, + final boolean isEthHash) { + if (Boolean.TRUE.equals(isMiningEnabled) && coinbase == null) { + throw new CommandLine.ParameterException( + commandLine, + "Unable to mine without a valid coinbase. Either disable mining (remove --miner-enabled) " + + "or specify the beneficiary of mining (via --miner-coinbase
)"); + } + if (Boolean.FALSE.equals(isMiningEnabled) && Boolean.TRUE.equals(iStratumMiningEnabled)) { + throw new CommandLine.ParameterException( + commandLine, + "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) " + + "or specify mining is enabled (--miner-enabled)"); + } + + // Check that block producer options work + if (!isMergeEnabled && isEthHash) { + CommandLineUtils.checkOptionDependencies( + logger, + commandLine, + "--miner-enabled", + !isMiningEnabled, + asList( + "--miner-coinbase", + "--min-gas-price", + "--min-block-occupancy-ratio", + "--miner-extra-data")); + + // Check that mining options are able to work + CommandLineUtils.checkOptionDependencies( + logger, + commandLine, + "--miner-enabled", + !isMiningEnabled, + asList( + "--miner-stratum-enabled", + "--Xminer-remote-sealers-limit", + "--Xminer-remote-sealers-hashrate-ttl")); + } + } + + @Override + public MiningParameters toDomainObject() { + return ImmutableMiningParameters.builder() + .isMiningEnabled(isMiningEnabled) + .coinbase(coinbase) + .isStratumMiningEnabled(iStratumMiningEnabled) + .stratumNetworkInterface(stratumNetworkInterface) + .stratumPort(stratumPort) + .build() + .getDynamic() + .setExtraData(extraData) + .setMinBlockOccupancyRatio(minBlockOccupancyRatio) + .setMinTransactionGasPrice(minTransactionGasPrice) + .setTargetGasLimit(targetGasLimit) + .toParameters(); + } + + @Override + public List getCLIOptions() { + return null; + } +} diff --git a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java index 9417aad8f55..3a1a65981a4 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java @@ -16,10 +16,6 @@ import static com.google.common.base.Preconditions.checkNotNull; import static org.hyperledger.besu.cli.subcommands.blocks.BlocksSubCommand.COMMAND_NAME; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_MAX_OMMERS_DEPTH; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POW_JOB_TTL; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_LIMIT; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_TTL; import org.hyperledger.besu.chainexport.RlpBlockExporter; import org.hyperledger.besu.chainimport.JsonBlockImporter; @@ -35,6 +31,7 @@ import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.blockcreation.IncrementingNonceGenerator; import org.hyperledger.besu.ethereum.chain.Blockchain; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.metrics.MetricsService; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; @@ -271,22 +268,31 @@ private MiningParameters getMiningParameters() { // Extradata and coinbase can be configured on a per-block level via the json file final Address coinbase = Address.ZERO; final Bytes extraData = Bytes.EMPTY; - return new MiningParameters.Builder() + return ImmutableMiningParameters.builder() .coinbase(coinbase) - .minTransactionGasPrice(minTransactionGasPrice) - .extraData(extraData) - .miningEnabled(false) - .stratumMiningEnabled(false) - .stratumNetworkInterface("0.0.0.0") - .stratumPort(8008) - .stratumExtranonce("080c") - .maybeNonceGenerator(new IncrementingNonceGenerator(0)) - .minBlockOccupancyRatio(0.0) - .remoteSealersLimit(DEFAULT_REMOTE_SEALERS_LIMIT) - .remoteSealersTimeToLive(DEFAULT_REMOTE_SEALERS_TTL) - .powJobTimeToLive(DEFAULT_POW_JOB_TTL) - .maxOmmerDepth(DEFAULT_MAX_OMMERS_DEPTH) - .build(); + .nonceGenerator(new IncrementingNonceGenerator(0)) + .build() + .getDynamic() + .setExtraData(extraData) + .setMinTransactionGasPrice(minTransactionGasPrice) + .toParameters(); + + // return new MiningParameters.Builder() + // .coinbase(coinbase) + // .minTransactionGasPrice(minTransactionGasPrice) + // .extraData(extraData) + // .miningEnabled(false) + // .stratumMiningEnabled(false) + // .stratumNetworkInterface("0.0.0.0") + // .stratumPort(8008) + // .stratumExtranonce("080c") + // .maybeNonceGenerator(new IncrementingNonceGenerator(0)) + // .minBlockOccupancyRatio(0.0) + // .remoteSealersLimit(DEFAULT_REMOTE_SEALERS_LIMIT) + // .remoteSealersTimeToLive(DEFAULT_REMOTE_SEALERS_TTL) + // .powJobTimeToLive(DEFAULT_POW_JOB_TTL) + // .maxOmmerDepth(DEFAULT_MAX_OMMERS_DEPTH) + // .build(); } private void importJsonBlocks(final BesuController controller, final Path path) 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 1e894e0d9c5..6e6bff2b237 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java @@ -34,6 +34,7 @@ import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.core.BlockHeader; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; @@ -148,6 +149,6 @@ protected CliqueContext createConsensusContext( @Override public MiningParameters getMiningParameterOverrides(final MiningParameters fromCli) { // Clique mines by default, reflect that with in the mining parameters: - return new MiningParameters.Builder(fromCli).miningEnabled(true).build(); + return ImmutableMiningParameters.builder().from(fromCli).isMiningEnabled(true).build(); } } 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 9323f3b81d6..1a82c24b932 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java @@ -32,6 +32,7 @@ import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; @@ -134,7 +135,10 @@ protected MiningCoordinator createMiningCoordinator( transitionProtocolSchedule.getPreMergeSchedule(), protocolContext, transactionPool, - new MiningParameters.Builder(miningParameters).miningEnabled(false).build(), + ImmutableMiningParameters.builder() + .from(miningParameters) + .isMiningEnabled(false) + .build(), syncState, ethProtocolManager), mergeBesuControllerBuilder.createTransitionMiningCoordinator( @@ -277,7 +281,7 @@ private void initTransitionWatcher( } }); - // initialize our merge context merge status before we would start either + // initialize our merge miningParameters merge status before we would start either Blockchain blockchain = protocolContext.getBlockchain(); blockchain .getTotalDifficultyByHash(blockchain.getChainHeadHash()) diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java index f831e1ecd59..2889ffefb13 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java @@ -39,9 +39,9 @@ import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.InMemoryPrivacyStorageProvider; -import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; @@ -188,10 +188,13 @@ public void setUp() throws IOException { .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) .miningParameters( - new MiningParameters.Builder() - .minTransactionGasPrice(Wei.of(1000)) - .miningEnabled(false) - .build()) + ImmutableMiningParameters.builder().isMiningEnabled(false).build() + + // new MiningParameters.Builder() + // .minTransactionGasPrice(Wei.of(1000)) + // .miningEnabled(false) + // .build() + ) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .dataDirectory(folder) diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java index bfdd71b3d2a..f587faab4f2 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java @@ -30,8 +30,8 @@ import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; -import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -111,7 +111,7 @@ private BesuController setUpControllerWithPrivacyEnabled(final boolean flexibleE .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(new MiningParameters.Builder().miningEnabled(false).build()) + .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .dataDirectory(dataDir) diff --git a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java index 93207b1d11a..e7166133672 100644 --- a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java +++ b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java @@ -40,8 +40,8 @@ import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockImporter; import org.hyperledger.besu.ethereum.core.BlockSyncTestUtils; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; -import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -448,7 +448,7 @@ private BesuController getController( .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .dataDirectory(dataDir) .networkId(NETWORK_ID) - .miningParameters(new MiningParameters.Builder().miningEnabled(false).build()) + .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) .nodeKey(nodeKey) .storageProvider(storageProvider) .metricsSystem(metricsSystem) 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 e6b60dad197..94266aa7d81 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java @@ -27,8 +27,8 @@ import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; -import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -91,7 +91,7 @@ private static BesuController createController() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(new MiningParameters.Builder().miningEnabled(false).build()) + .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) 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 00c86133ea6..505f4f5d7fc 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java @@ -29,8 +29,8 @@ import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeader; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; -import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; @@ -421,10 +421,12 @@ protected BesuController createController(final GenesisConfigFile genesisConfigF .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.valueOf(10)) .miningParameters( - new MiningParameters.Builder() - .minTransactionGasPrice(Wei.ZERO) - .miningEnabled(true) - .build()) + ImmutableMiningParameters.builder() + .isMiningEnabled(true) + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .toParameters()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) 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 3260b8ee55b..a1e4374ee2e 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java @@ -22,8 +22,8 @@ import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; -import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -67,7 +67,7 @@ public void blockImport() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(new MiningParameters.Builder().miningEnabled(false).build()) + .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) @@ -100,7 +100,7 @@ public void blockImportRejectsBadPow() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(new MiningParameters.Builder().miningEnabled(false).build()) + .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) @@ -130,7 +130,7 @@ public void blockImportCanSkipPow() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(new MiningParameters.Builder().miningEnabled(false).build()) + .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) 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 553220c9431..787e9e60733 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -72,6 +72,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.authentication.JwtAlgorithm; import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.api.tls.TlsConfiguration; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -291,8 +292,9 @@ public void callingBesuCommandWithoutOptionsMustSyncWithDefaultValues() { assertThat(syncConfigurationCaptor.getValue().getSyncMode()).isEqualTo(SyncMode.FAST); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); assertThat(miningArg.getValue().getCoinbase()).isEqualTo(Optional.empty()); - assertThat(miningArg.getValue().getMinTransactionGasPrice()).isEqualTo(Wei.of(1000)); - assertThat(miningArg.getValue().getExtraData()).isEqualTo(Bytes.EMPTY); + assertThat(miningArg.getValue().getDynamic().getMinTransactionGasPrice()) + .isEqualTo(Wei.of(1000)); + assertThat(miningArg.getValue().getDynamic().getExtraData()).isEqualTo(Bytes.EMPTY); assertThat(ethNetworkArg.getValue().getNetworkId()).isEqualTo(1); assertThat(ethNetworkArg.getValue().getBootNodes()).isEqualTo(MAINNET_BOOTSTRAP_NODES); } @@ -916,12 +918,23 @@ public void envVariableOverridesValueFromConfigFile() { verify(mockControllerBuilder) .miningParameters( - new MiningParameters.Builder() + ImmutableMiningParameters.builder() + .isMiningEnabled(false) .coinbase(Address.fromHexString(expectedCoinbase)) - .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) - .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) - .miningEnabled(false) - .build()); + .build() + .getDynamic() + .setMinTransactionGasPrice( + MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE) + .setExtraData(MiningParameters.Dynamic.DEFAULT_EXTRA_DATA) + .toParameters()); + + // new MiningParameters.Builder() + // .coinbase(Address.fromHexString(expectedCoinbase)) + // + // .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) + // .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) + // .miningEnabled(false) + // .build()); } @Test @@ -933,12 +946,24 @@ public void cliOptionOverridesEnvVariableAndConfig() { verify(mockControllerBuilder) .miningParameters( - new MiningParameters.Builder() + ImmutableMiningParameters.builder() + .isMiningEnabled(false) .coinbase(Address.fromHexString(expectedCoinbase)) - .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) - .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) - .miningEnabled(false) - .build()); + .build() + .getDynamic() + .setMinTransactionGasPrice( + MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE) + .setExtraData(MiningParameters.Dynamic.DEFAULT_EXTRA_DATA) + .toParameters() + + // new MiningParameters.Builder() + // .coinbase(Address.fromHexString(expectedCoinbase)) + // + // .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) + // .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) + // .miningEnabled(false) + // .build() + ); } @Test @@ -3903,8 +3928,9 @@ public void miningParametersAreCaptured() { assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); assertThat(miningArg.getValue().getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); - assertThat(miningArg.getValue().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); - assertThat(miningArg.getValue().getExtraData()).isEqualTo(Bytes.fromHexString(extraDataString)); + assertThat(miningArg.getValue().getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); + assertThat(miningArg.getValue().getDynamic().getExtraData()) + .isEqualTo(Bytes.fromHexString(extraDataString)); } @Test @@ -4633,7 +4659,8 @@ public void targetGasLimitIsEnabledWhenSpecified() { assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - assertThat(miningParametersArgumentCaptor.getValue().getTargetGasLimit().get().longValue()) + assertThat( + miningParametersArgumentCaptor.getValue().getDynamic().getTargetGasLimit().getAsLong()) .isEqualTo(10_000_000L); } diff --git a/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java index 9fc337095f2..d5c7a95d4ba 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java @@ -34,6 +34,7 @@ import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; @@ -99,7 +100,7 @@ public void setup() { .thenReturn(mock(CliqueContext.class)); when(protocolContext.getConsensusContext(PostMergeContext.class)).thenReturn(mergeContext); when(protocolContext.getConsensusContext(MergeContext.class)).thenReturn(mergeContext); - miningParameters = new MiningParameters.Builder().miningEnabled(false).build(); + miningParameters = ImmutableMiningParameters.builder().isMiningEnabled(false).build(); } @Test @@ -118,7 +119,7 @@ public void assertPoWIsNotMiningPreMerge() { @Test public void assertPowMiningPreMerge() { - miningParameters = new MiningParameters.Builder().miningEnabled(true).build(); + miningParameters = ImmutableMiningParameters.builder().isMiningEnabled(true).build(); var transCoordinator = buildTransitionCoordinator(powBuilder, postMergeBuilder); assertThat(transCoordinator.isMiningBeforeMerge()).isTrue(); } diff --git a/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java b/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java index 8b6b10f5493..aed4b9c3f26 100644 --- a/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java +++ b/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java @@ -33,7 +33,7 @@ import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; -import org.hyperledger.besu.ethereum.core.MiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionTestFixture; @@ -155,7 +155,12 @@ public void setUp() { TestClock.system(ZoneId.systemDefault()), new NoOpMetricsSystem(), syncState, - new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .toParameters(), + // new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), txPoolConfig, null); diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java index 30bf9b6476d..63eb9cacdd6 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java @@ -25,12 +25,12 @@ import org.hyperledger.besu.cryptoservices.NodeKey; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Hash; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.blockcreation.AbstractBlockCreator; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; @@ -38,7 +38,6 @@ import org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions; import java.util.Optional; -import java.util.function.Supplier; /** The Clique block creator. */ public class CliqueBlockCreator extends AbstractBlockCreator { @@ -49,40 +48,40 @@ public class CliqueBlockCreator extends AbstractBlockCreator { /** * Instantiates a new Clique block creator. * + * @param miningParameters the mining parameters * @param coinbase the coinbase - * @param targetGasLimitSupplier the target gas limit supplier * @param extraDataCalculator the extra data calculator * @param transactionPool the pending transactions - * @param protocolContext the protocol context + * @param protocolContext the protocol miningParameters * @param protocolSchedule the protocol schedule * @param nodeKey the node key - * @param minTransactionGasPrice the min transaction gas price - * @param minBlockOccupancyRatio the min block occupancy ratio * @param parentHeader the parent header * @param epochManager the epoch manager */ public CliqueBlockCreator( + final MiningParameters miningParameters, final Address coinbase, - final Supplier> targetGasLimitSupplier, + // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, final NodeKey nodeKey, - final Wei minTransactionGasPrice, - final Double minBlockOccupancyRatio, + // final Wei minTransactionGasPrice, + // final Double minBlockOccupancyRatio, final BlockHeader parentHeader, final EpochManager epochManager) { super( + miningParameters, coinbase, __ -> Util.publicKeyToAddress(nodeKey.getPublicKey()), - targetGasLimitSupplier, + // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - minTransactionGasPrice, - minBlockOccupancyRatio, + // minTransactionGasPrice, + // minBlockOccupancyRatio, parentHeader, Optional.empty()); this.nodeKey = nodeKey; diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java index 9f2be2e1e76..1f194349522 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java @@ -35,7 +35,6 @@ import java.util.Collection; import java.util.List; import java.util.Optional; -import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; import com.google.common.annotations.VisibleForTesting; @@ -82,15 +81,17 @@ public CliqueBlockMiner createMiner( final Function blockCreator = (header) -> new CliqueBlockCreator( + miningParameters, localAddress, // TOOD(tmm): This can be removed (used for voting not coinbase). - () -> targetGasLimit.map(AtomicLong::longValue), + // () -> + // miningContext.getTargetGasLimit().map(AtomicLong::longValue), this::calculateExtraData, transactionPool, protocolContext, protocolSchedule, nodeKey, - minTransactionGasPrice, - minBlockOccupancyRatio, + // miningContext.getMinTransactionGasPrice(), + // miningContext.getMinBlockOccupancyRatio(), header, epochManager); @@ -120,7 +121,8 @@ Bytes calculateExtraData(final BlockHeader parentHeader) { final List
validators = Lists.newArrayList(); final Bytes vanityDataToInsert = - ConsensusHelpers.zeroLeftPad(extraData, CliqueExtraData.EXTRA_VANITY_LENGTH); + ConsensusHelpers.zeroLeftPad( + miningParameters.getDynamic().getExtraData(), CliqueExtraData.EXTRA_VANITY_LENGTH); // Building ON TOP of canonical head, if the next block is epoch, include validators. if (epochManager.isEpochBlock(parentHeader.getNumber() + 1)) { diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java index 0b0210d4ef3..ad6c15b2f17 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java @@ -47,6 +47,7 @@ import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -134,17 +135,30 @@ public void proposerAddressCanBeExtractFromAConstructedBlock() { CliqueExtraData.createWithoutProposerSeal(Bytes.wrap(new byte[32]), validatorList); final Address coinbase = AddressHelpers.ofValue(1); + + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(coinbase) + .build() + .getDynamic() + .setExtraData(extraData) + .setTargetGasLimit(10_000_000L) + .setMinTransactionGasPrice(Wei.ZERO) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final CliqueBlockCreator blockCreator = new CliqueBlockCreator( + miningParameters, coinbase, - () -> Optional.of(10_000_000L), + // () -> Optional.of(10_000_000L), parent -> extraData, createTransactionPool(), protocolContext, protocolSchedule, proposerNodeKey, - Wei.ZERO, - 0.8, + // Wei.ZERO, + // 0.8, blockchain.getChainHeadHeader(), epochManager); @@ -163,17 +177,29 @@ public void insertsValidVoteIntoConstructedBlock() { when(voteProvider.getVoteAfterBlock(any(), any())) .thenReturn(Optional.of(new ValidatorVote(VoteType.ADD, coinbase, a1))); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(coinbase) + .build() + .getDynamic() + .setExtraData(extraData) + .setTargetGasLimit(10_000_000L) + .setMinTransactionGasPrice(Wei.ZERO) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final CliqueBlockCreator blockCreator = new CliqueBlockCreator( + miningParameters, coinbase, - () -> Optional.of(10_000_000L), + // () -> Optional.of(10_000_000L), parent -> extraData, createTransactionPool(), protocolContext, protocolSchedule, proposerNodeKey, - Wei.ZERO, - 0.8, + // Wei.ZERO, + // 0.8, blockchain.getChainHeadHeader(), epochManager); @@ -197,17 +223,29 @@ public void insertsNoVoteWhenAtEpoch() { when(mockVoteProvider.getVoteAfterBlock(any(), any())) .thenReturn(Optional.of(new ValidatorVote(VoteType.ADD, coinbase, a1))); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(coinbase) + .build() + .getDynamic() + .setExtraData(extraData) + .setTargetGasLimit(10_000_000L) + .setMinTransactionGasPrice(Wei.ZERO) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final CliqueBlockCreator blockCreator = new CliqueBlockCreator( + miningParameters, coinbase, - () -> Optional.of(10_000_000L), + // () -> Optional.of(10_000_000L), parent -> extraData, createTransactionPool(), protocolContext, protocolSchedule, proposerNodeKey, - Wei.ZERO, - 0.8, + // Wei.ZERO, + // 0.8, blockchain.getChainHeadHeader(), epochManager); diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java index 4a3bf5424d7..13c5ebbe7ba 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java @@ -37,6 +37,7 @@ import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -101,18 +102,31 @@ public void setup() { public void extraDataCreatedOnEpochBlocksContainsValidators() { final Bytes vanityData = generateRandomVanityData(); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .isMiningEnabled(false) + .coinbase(AddressHelpers.ofValue(1)) + .build() + .getDynamic() + .setExtraData(vanityData) + .setMinTransactionGasPrice(Wei.ZERO) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final CliqueMinerExecutor executor = new CliqueMinerExecutor( cliqueProtocolContext, cliqueProtocolSchedule, createTransactionPool(), proposerNodeKey, - new MiningParameters.Builder() - .coinbase(AddressHelpers.ofValue(1)) - .minTransactionGasPrice(Wei.ZERO) - .extraData(vanityData) - .miningEnabled(false) - .build(), + miningParameters, + + // new MiningParameters.Builder() + // .coinbase(AddressHelpers.ofValue(1)) + // .minTransactionGasPrice(Wei.ZERO) + // .extraData(vanityData) + // .miningEnabled(false) + // .build(), mock(CliqueBlockScheduler.class), new EpochManager(EPOCH_LENGTH)); @@ -138,18 +152,30 @@ public void extraDataCreatedOnEpochBlocksContainsValidators() { public void extraDataForNonEpochBlocksDoesNotContainValidaors() { final Bytes vanityData = generateRandomVanityData(); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .isMiningEnabled(false) + .coinbase(AddressHelpers.ofValue(1)) + .build() + .getDynamic() + .setExtraData(vanityData) + .setMinTransactionGasPrice(Wei.ZERO) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final CliqueMinerExecutor executor = new CliqueMinerExecutor( cliqueProtocolContext, cliqueProtocolSchedule, createTransactionPool(), proposerNodeKey, - new MiningParameters.Builder() - .coinbase(AddressHelpers.ofValue(1)) - .minTransactionGasPrice(Wei.ZERO) - .extraData(vanityData) - .miningEnabled(false) - .build(), + miningParameters, + // new MiningParameters.Builder() + // .coinbase(AddressHelpers.ofValue(1)) + // .minTransactionGasPrice(Wei.ZERO) + // .extraData(vanityData) + // .miningEnabled(false) + // .build(), mock(CliqueBlockScheduler.class), new EpochManager(EPOCH_LENGTH)); @@ -175,18 +201,30 @@ public void shouldUseLatestVanityData() { final Bytes initialVanityData = generateRandomVanityData(); final Bytes modifiedVanityData = generateRandomVanityData(); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .isMiningEnabled(false) + .coinbase(AddressHelpers.ofValue(1)) + .build() + .getDynamic() + .setExtraData(initialVanityData) + .setMinTransactionGasPrice(Wei.ZERO) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final CliqueMinerExecutor executor = new CliqueMinerExecutor( cliqueProtocolContext, cliqueProtocolSchedule, createTransactionPool(), proposerNodeKey, - new MiningParameters.Builder() - .coinbase(AddressHelpers.ofValue(1)) - .minTransactionGasPrice(Wei.ZERO) - .extraData(initialVanityData) - .miningEnabled(false) - .build(), + miningParameters, + // new MiningParameters.Builder() + // .coinbase(AddressHelpers.ofValue(1)) + // .minTransactionGasPrice(Wei.ZERO) + // .extraData(initialVanityData) + // .miningEnabled(false) + // .build(), mock(CliqueBlockScheduler.class), new EpochManager(EPOCH_LENGTH)); diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java index 4e5a39f335f..3848d38bc77 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java @@ -20,17 +20,16 @@ import org.hyperledger.besu.consensus.common.bft.BftExtraDataCodec; import org.hyperledger.besu.consensus.common.bft.BftHelpers; import org.hyperledger.besu.datatypes.Address; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.blockcreation.AbstractBlockCreator; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import java.util.Optional; -import java.util.function.Supplier; /** The Bft block creator. */ // This class is responsible for creating a block without committer seals (basically it was just @@ -42,40 +41,40 @@ public class BftBlockCreator extends AbstractBlockCreator { /** * Instantiates a new Bft block creator. * + * @param miningParameters the mining parameters * @param forksSchedule the forks schedule * @param localAddress the local address - * @param targetGasLimitSupplier the target gas limit supplier * @param extraDataCalculator the extra data calculator * @param transactionPool the pending transactions - * @param protocolContext the protocol context + * @param protocolContext the protocol miningParameters * @param protocolSchedule the protocol schedule - * @param minTransactionGasPrice the min transaction gas price - * @param minBlockOccupancyRatio the min block occupancy ratio * @param parentHeader the parent header * @param bftExtraDataCodec the bft extra data codec */ public BftBlockCreator( + final MiningParameters miningParameters, final ForksSchedule forksSchedule, final Address localAddress, - final Supplier> targetGasLimitSupplier, + // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - final Wei minTransactionGasPrice, - final Double minBlockOccupancyRatio, + // final Wei minTransactionGasPrice, + // final Double minBlockOccupancyRatio, final BlockHeader parentHeader, final BftExtraDataCodec bftExtraDataCodec) { super( + miningParameters, localAddress, miningBeneficiaryCalculator(localAddress, forksSchedule), - targetGasLimitSupplier, + // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - minTransactionGasPrice, - minBlockOccupancyRatio, + // minTransactionGasPrice, + // minBlockOccupancyRatio, parentHeader, Optional.empty()); this.bftExtraDataCodec = bftExtraDataCodec; diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java index 35c6a33c94e..5d391bcbda9 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java @@ -40,7 +40,6 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.concurrent.atomic.AtomicLong; import org.apache.tuweni.bytes.Bytes; @@ -53,8 +52,9 @@ public class BftBlockCreatorFactory { /** The Forks schedule. */ protected final ForksSchedule forksSchedule; + protected final MiningParameters miningParameters; private final TransactionPool transactionPool; - /** The Protocol context. */ + /** The Protocol miningParameters. */ protected final ProtocolContext protocolContext; /** The Protocol schedule. */ protected final ProtocolSchedule protocolSchedule; @@ -64,17 +64,17 @@ public class BftBlockCreatorFactory { private final Address localAddress; /** The Vanity data. */ - protected volatile Bytes vanityData; - - private volatile Wei minTransactionGasPrice; - private volatile Double minBlockOccupancyRatio; - private volatile Optional targetGasLimit; + // protected volatile Bytes vanityData; + // + // private volatile Wei minTransactionGasPrice; + // private volatile Double minBlockOccupancyRatio; + // private volatile Optional targetGasLimit; /** * Instantiates a new Bft block creator factory. * * @param transactionPool the pending transactions - * @param protocolContext the protocol context + * @param protocolContext the protocol miningParameters * @param protocolSchedule the protocol schedule * @param forksSchedule the forks schedule * @param miningParams the mining params @@ -94,11 +94,12 @@ public BftBlockCreatorFactory( this.protocolSchedule = protocolSchedule; this.forksSchedule = forksSchedule; this.localAddress = localAddress; - this.minTransactionGasPrice = miningParams.getMinTransactionGasPrice(); - this.minBlockOccupancyRatio = miningParams.getMinBlockOccupancyRatio(); - this.vanityData = miningParams.getExtraData(); + this.miningParameters = miningParams; + // this.minTransactionGasPrice = miningParams.getMinTransactionGasPrice(); + // this.minBlockOccupancyRatio = miningParams.getMinBlockOccupancyRatio(); + // this.vanityData = miningParams.getExtraData(); this.bftExtraDataCodec = bftExtraDataCodec; - this.targetGasLimit = miningParams.getTargetGasLimit(); + // this.targetGasLimit = miningParams.getTargetGasLimit(); } /** @@ -110,15 +111,16 @@ public BftBlockCreatorFactory( */ public BlockCreator create(final BlockHeader parentHeader, final int round) { return new BftBlockCreator( + miningParameters, forksSchedule, localAddress, - () -> targetGasLimit.map(AtomicLong::longValue), + // () -> targetGasLimit.map(AtomicLong::longValue), ph -> createExtraData(round, ph), transactionPool, protocolContext, protocolSchedule, - minTransactionGasPrice, - minBlockOccupancyRatio, + // minTransactionGasPrice, + // minBlockOccupancyRatio, parentHeader, bftExtraDataCodec); } @@ -129,7 +131,8 @@ public BlockCreator create(final BlockHeader parentHeader, final int round) { * @param extraData the extra data */ public void setExtraData(final Bytes extraData) { - this.vanityData = extraData.copy(); + + miningParameters.getDynamic().setExtraData(extraData.copy()); } /** @@ -138,7 +141,7 @@ public void setExtraData(final Bytes extraData) { * @param minTransactionGasPrice the min transaction gas price */ public void setMinTransactionGasPrice(final Wei minTransactionGasPrice) { - this.minTransactionGasPrice = minTransactionGasPrice; + miningParameters.getDynamic().setMinTransactionGasPrice(minTransactionGasPrice); } /** @@ -147,7 +150,7 @@ public void setMinTransactionGasPrice(final Wei minTransactionGasPrice) { * @return the min transaction gas price */ public Wei getMinTransactionGasPrice() { - return minTransactionGasPrice; + return miningParameters.getDynamic().getMinTransactionGasPrice(); } /** @@ -171,7 +174,9 @@ public Bytes createExtraData(final int round, final BlockHeader parentHeader) { final BftExtraData extraData = new BftExtraData( - ConsensusHelpers.zeroLeftPad(vanityData, BftExtraDataCodec.EXTRA_VANITY_LENGTH), + ConsensusHelpers.zeroLeftPad( + miningParameters.getDynamic().getExtraData(), + BftExtraDataCodec.EXTRA_VANITY_LENGTH), Collections.emptyList(), toVote(proposal), round, @@ -187,9 +192,7 @@ public Bytes createExtraData(final int round, final BlockHeader parentHeader) { */ public void changeTargetGasLimit(final Long newTargetGasLimit) { if (AbstractGasLimitSpecification.isValidTargetGasLimit(newTargetGasLimit)) { - this.targetGasLimit.ifPresentOrElse( - existing -> existing.set(newTargetGasLimit), - () -> this.targetGasLimit = Optional.of(new AtomicLong(newTargetGasLimit))); + miningParameters.getDynamic().setTargetGasLimit(newTargetGasLimit); } else { throw new UnsupportedOperationException("Specified target gas limit is invalid"); } diff --git a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java index 42d68250821..839ad0926b2 100644 --- a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java +++ b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java @@ -77,6 +77,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -304,12 +305,21 @@ private static ControllerAndState createControllerAndFinalState( final WorldStateArchive worldStateArchive = createInMemoryWorldStateArchive(); final MiningParameters miningParams = - new MiningParameters.Builder() + ImmutableMiningParameters.builder() + .isMiningEnabled(true) .coinbase(AddressHelpers.ofValue(1)) - .minTransactionGasPrice(Wei.ZERO) - .extraData(Bytes.wrap("Ibft Int tests".getBytes(UTF_8))) - .miningEnabled(true) - .build(); + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .setExtraData(Bytes.wrap("Ibft Int tests".getBytes(UTF_8))) + .toParameters(); + // + // new MiningParameters.Builder() + // .coinbase(AddressHelpers.ofValue(1)) + // .minTransactionGasPrice(Wei.ZERO) + // .extraData(Bytes.wrap("Ibft Int tests".getBytes(UTF_8))) + // .miningEnabled(true) + // .build(); final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions(); genesisConfigOptions.byzantiumBlock(0); diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java index 1039b3579c1..e7424e11504 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java @@ -41,6 +41,7 @@ import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -150,11 +151,29 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( transactionPool.setEnabled(); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(AddressHelpers.ofValue(1)) + .build() + .getDynamic() + .setExtraData( + bftExtraDataEncoder.encode( + new BftExtraData( + Bytes.wrap(new byte[32]), + Collections.emptyList(), + Optional.empty(), + 0, + initialValidatorList))) + .setMinTransactionGasPrice(Wei.ZERO) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final BftBlockCreator blockCreator = new BftBlockCreator( + miningParameters, forksSchedule, initialValidatorList.get(0), - () -> Optional.of(10_000_000L), + // () -> Optional.of(10_000_000L), parent -> bftExtraDataEncoder.encode( new BftExtraData( @@ -166,8 +185,8 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( transactionPool, protContext, protocolSchedule, - Wei.ZERO, - 0.8, + // Wei.ZERO, + // 0.8, parentHeader, bftExtraDataEncoder); diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java index dd8adae7e9b..27f688dc5ea 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java @@ -15,12 +15,12 @@ package org.hyperledger.besu.consensus.merge.blockcreation; import org.hyperledger.besu.datatypes.Address; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.blockcreation.AbstractBlockCreator; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.Withdrawal; @@ -30,55 +30,46 @@ import java.util.Collections; import java.util.List; import java.util.Optional; -import java.util.function.Supplier; import org.apache.tuweni.bytes.Bytes32; /** The Merge block creator. */ class MergeBlockCreator extends AbstractBlockCreator { - /** - * On PoS you do not need to compete with other nodes for block production, since you have an - * allocated slot for that, so in this case make sense to always try to fill the block, if there - * are enough pending transactions, until the remaining gas is less than the minimum needed for - * the smaller transaction. So for PoS the min-block-occupancy-ratio option is set to always try - * to fill 100% of the block. - */ - private static final double TRY_FILL_BLOCK = 1.0; /** * Instantiates a new Merge block creator. * - * @param coinbase the coinbase - * @param targetGasLimitSupplier the target gas limit supplier + * @param miningParameters the mining parameters * @param extraDataCalculator the extra data calculator * @param transactionPool the pending transactions - * @param protocolContext the protocol context + * @param protocolContext the protocol miningParameters * @param protocolSchedule the protocol schedule - * @param minTransactionGasPrice the min transaction gas price * @param miningBeneficiary the mining beneficiary * @param parentHeader the parent header */ public MergeBlockCreator( - final Address coinbase, - final Supplier> targetGasLimitSupplier, + final MiningParameters miningParameters, + // final Address coinbase, + // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - final Wei minTransactionGasPrice, + // final Wei minTransactionGasPrice, final Address miningBeneficiary, final BlockHeader parentHeader, final Optional
depositContractAddress) { super( + miningParameters, miningBeneficiary, __ -> miningBeneficiary, - targetGasLimitSupplier, + // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - minTransactionGasPrice, - TRY_FILL_BLOCK, + // minTransactionGasPrice, + // TRY_FILL_BLOCK, parentHeader, depositContractAddress); } diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java index d7e2856941f..bb98d273e00 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java @@ -56,7 +56,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; @@ -69,9 +68,16 @@ /** The Merge coordinator. */ public class MergeCoordinator implements MergeMiningCoordinator, BadChainListener { private static final Logger LOG = LoggerFactory.getLogger(MergeCoordinator.class); - + /** + * On PoS you do not need to compete with other nodes for block production, since you have an + * allocated slot for that, so in this case make sense to always try to fill the block, if there + * are enough pending transactions, until the remaining gas is less than the minimum needed for + * the smaller transaction. So for PoS the min-block-occupancy-ratio option is set to always try + * to fill 100% of the block. + */ + private static final double TRY_FILL_BLOCK = 1.0; /** The Target gas limit. */ - protected final AtomicLong targetGasLimit; + // protected final AtomicLong targetGasLimit; /** The Mining parameters. */ protected final MiningParameters miningParameters; /** The Merge block creator factory. */ @@ -79,15 +85,13 @@ public class MergeCoordinator implements MergeMiningCoordinator, BadChainListene /** The Extra data. */ protected final AtomicReference extraData = new AtomicReference<>(Bytes.fromHexString("0x")); - /** The Latest descends from terminal. */ - protected final AtomicReference latestDescendsFromTerminal = new AtomicReference<>(); - /** The Merge context. */ + /** The Merge miningParameters. */ protected final MergeContext mergeContext; - /** The Protocol context. */ + /** The Protocol miningParameters. */ protected final ProtocolContext protocolContext; /** The Block builder executor. */ protected final ProposalBuilderExecutor blockBuilderExecutor; - /** The Backward sync context. */ + /** The Backward sync miningParameters. */ protected final BackwardSyncContext backwardSyncContext; /** The Protocol schedule. */ protected final ProtocolSchedule protocolSchedule; @@ -98,12 +102,12 @@ public class MergeCoordinator implements MergeMiningCoordinator, BadChainListene /** * Instantiates a new Merge coordinator. * - * @param protocolContext the protocol context + * @param protocolContext the protocol miningParameters * @param protocolSchedule the protocol schedule * @param blockBuilderExecutor the block builder executor * @param transactionPool the pending transactions * @param miningParams the mining params - * @param backwardSyncContext the backward sync context + * @param backwardSyncContext the backward sync miningParameters * @param depositContractAddress the address of the deposit contract */ public MergeCoordinator( @@ -118,25 +122,33 @@ public MergeCoordinator( this.protocolSchedule = protocolSchedule; this.blockBuilderExecutor = blockBuilderExecutor; this.mergeContext = protocolContext.getConsensusContext(MergeContext.class); - this.miningParameters = miningParams; this.backwardSyncContext = backwardSyncContext; - this.targetGasLimit = - miningParameters - .getTargetGasLimit() - // TODO: revisit default target gas limit - .orElse(new AtomicLong(30000000L)); - this.extraData.set(miningParams.getExtraData()); + + if (miningParams.getDynamic().getTargetGasLimit().isEmpty()) { + miningParams.getDynamic().setTargetGasLimit(30000000L); + } + miningParams.getDynamic().setMinBlockOccupancyRatio(TRY_FILL_BLOCK); + + this.miningParameters = miningParams; + + // this.targetGasLimit = + // miningParameters + // .getTargetGasLimit() + // // TODO: revisit default target gas limit + // .orElse(new AtomicLong(30000000L)); + // this.extraData.set(miningParams.getExtraData()); this.mergeBlockCreatorFactory = (parentHeader, address) -> new MergeBlockCreator( - address.or(miningParameters::getCoinbase).orElse(Address.ZERO), - () -> Optional.of(targetGasLimit.longValue()), + miningParameters, + // address.or(miningParameters::getCoinbase).orElse(Address.ZERO), + // () -> Optional.of(targetGasLimit.longValue()), parent -> extraData.get(), transactionPool, protocolContext, protocolSchedule, - this.miningParameters.getMinTransactionGasPrice(), + // this.miningParameters.getMinTransactionGasPrice(), address.or(miningParameters::getCoinbase).orElse(Address.ZERO), parentHeader, depositContractAddress); @@ -147,11 +159,11 @@ public MergeCoordinator( /** * Instantiates a new Merge coordinator. * - * @param protocolContext the protocol context + * @param protocolContext the protocol miningParameters * @param protocolSchedule the protocol schedule * @param blockBuilderExecutor the block builder executor * @param miningParams the mining params - * @param backwardSyncContext the backward sync context + * @param backwardSyncContext the backward sync miningParameters * @param mergeBlockCreatorFactory the merge block creator factory */ public MergeCoordinator( @@ -166,13 +178,20 @@ public MergeCoordinator( this.protocolSchedule = protocolSchedule; this.blockBuilderExecutor = blockBuilderExecutor; this.mergeContext = protocolContext.getConsensusContext(MergeContext.class); - this.miningParameters = miningParams; + // this.miningParameters = miningParams; this.backwardSyncContext = backwardSyncContext; - this.targetGasLimit = - miningParameters - .getTargetGasLimit() - // TODO: revisit default target gas limit - .orElse(new AtomicLong(30000000L)); + if (miningParams.getDynamic().getTargetGasLimit().isEmpty()) { + miningParams.getDynamic().setTargetGasLimit(30000000L); + } + miningParams.getDynamic().setMinBlockOccupancyRatio(TRY_FILL_BLOCK); + this.miningParameters = miningParams; + // + // + // this.targetGasLimit = + // miningParameters + // .getTargetGasLimit() + // // TODO: revisit default target gas limit + // .orElse(new AtomicLong(30000000L)); this.mergeBlockCreatorFactory = mergeBlockCreatorFactory; @@ -205,7 +224,7 @@ public boolean isMining() { @Override public Wei getMinTransactionGasPrice() { - return miningParameters.getMinTransactionGasPrice(); + return miningParameters.getDynamic().getMinTransactionGasPrice(); } @Override @@ -234,7 +253,7 @@ public Optional createBlock(final BlockHeader parentHeader, final long ti @Override public void changeTargetGasLimit(final Long newTargetGasLimit) { if (AbstractGasLimitSpecification.isValidTargetGasLimit(newTargetGasLimit)) { - this.targetGasLimit.set(newTargetGasLimit); + this.miningParameters.getDynamic().setTargetGasLimit(newTargetGasLimit); } else { throw new IllegalArgumentException("Specified target gas limit is invalid"); } diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java index 232140fac57..c2aed4b10ac 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java @@ -57,6 +57,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.TransactionTestFixture; @@ -134,7 +135,7 @@ public class MergeCoordinatorTest implements MergeGenesisConfigHelper { @Spy MiningParameters miningParameters = - new MiningParameters.Builder() + ImmutableMiningParameters.builder() .coinbase(coinbase) .posBlockCreationRepetitionMinDuration(REPETITION_MIN_DURATION) .build(); @@ -278,13 +279,15 @@ public void exceptionDuringBuildingBlockShouldNotBeInvalid() MergeBlockCreator beingSpiedOn = spy( new MergeBlockCreator( - address.or(miningParameters::getCoinbase).orElse(Address.ZERO), - () -> Optional.of(30000000L), + miningParameters, + // + // address.or(miningParameters::getCoinbase).orElse(Address.ZERO), + // () -> Optional.of(30000000L), parent -> Bytes.EMPTY, transactionPool, protocolContext, protocolSchedule, - this.miningParameters.getMinTransactionGasPrice(), + // miningParameters.getMinTransactionGasPrice(), address.or(miningParameters::getCoinbase).orElse(Address.ZERO), parentHeader, Optional.empty())); @@ -738,7 +741,13 @@ public void shouldCancelPreviousBlockCreationJobIfCalledAgainWithNewPayloadId() public void shouldUseExtraDataFromMiningParameters() { final Bytes extraData = Bytes.fromHexString("0x1234"); - miningParameters = new MiningParameters.Builder().extraData(extraData).build(); + miningParameters = + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setExtraData(extraData) + .toParameters(); + // new MiningParameters.Builder().extraData(extraData).build(); this.coordinator = new MergeCoordinator( diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java index d5dbd139c6c..f2305ab83ca 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java @@ -33,7 +33,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; -import org.hyperledger.besu.ethereum.core.MiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.eth.sync.backwardsync.BackwardSyncContext; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator; @@ -93,7 +93,8 @@ public void setUp() { mockProtocolSchedule, CompletableFuture::runAsync, mockTransactionPool, - new MiningParameters.Builder().coinbase(coinbase).build(), + ImmutableMiningParameters.builder().coinbase(coinbase).build(), + // new MiningParameters.Builder().coinbase(coinbase).build(), mock(BackwardSyncContext.class), Optional.empty()); mergeContext.setIsPostMerge(genesisState.getBlock().getHeader().getDifficulty()); 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 ac824df6c0f..290dc3d5f5e 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 @@ -90,6 +90,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.core.Util; @@ -365,12 +366,21 @@ private static ControllerAndState createControllerAndFinalState( final List qbftForks) { final MiningParameters miningParams = - new MiningParameters.Builder() + ImmutableMiningParameters.builder() + .isMiningEnabled(true) .coinbase(AddressHelpers.ofValue(1)) - .minTransactionGasPrice(Wei.ZERO) - .extraData(Bytes.wrap("Qbft Int tests".getBytes(UTF_8))) - .miningEnabled(true) - .build(); + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .setExtraData(Bytes.wrap("Qbft Int tests".getBytes(UTF_8))) + .toParameters(); + + // new MiningParameters.Builder() + // .coinbase(AddressHelpers.ofValue(1)) + // .minTransactionGasPrice(Wei.ZERO) + // .extraData(Bytes.wrap("Qbft Int tests".getBytes(UTF_8))) + // .miningEnabled(true) + // .build(); final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions(); final Map qbftConfigValues = diff --git a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactory.java b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactory.java index c2007ededf7..b655c1a3693 100644 --- a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactory.java +++ b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactory.java @@ -83,7 +83,9 @@ public Bytes createExtraData(final int round, final BlockHeader parentHeader) { // vote and validators will come from contract instead of block final BftExtraData extraData = new BftExtraData( - ConsensusHelpers.zeroLeftPad(vanityData, BftExtraDataCodec.EXTRA_VANITY_LENGTH), + ConsensusHelpers.zeroLeftPad( + miningParameters.getDynamic().getExtraData(), + BftExtraDataCodec.EXTRA_VANITY_LENGTH), Collections.emptyList(), Optional.empty(), round, diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java index fa2e8158530..ad4aafc579f 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java @@ -30,6 +30,7 @@ import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.core.BlockHeader; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; @@ -46,9 +47,14 @@ public class QbftBlockCreatorFactoryTest { @BeforeEach @SuppressWarnings("unchecked") - public void setUp() throws Exception { - final MiningParameters miningParams = mock(MiningParameters.class); - when(miningParams.getExtraData()).thenReturn(Bytes.wrap("Qbft tests".getBytes(UTF_8))); + public void setUp() { + final MiningParameters miningParams = + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setExtraData(Bytes.wrap("Qbft tests".getBytes(UTF_8))) + .toParameters(); + // when(miningParams.getExtraData()).thenReturn(Bytes.wrap("Qbft tests".getBytes(UTF_8))); final MutableQbftConfigOptions qbftConfigOptions = new MutableQbftConfigOptions(JsonQbftConfigOptions.DEFAULT); diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java index bdb94af6e3d..7234df9f70d 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java @@ -44,7 +44,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; -import org.hyperledger.besu.ethereum.core.MiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -117,7 +117,12 @@ public void setUp() { protocolContext, batchAddedListener, ethContext, - new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .toParameters(), + // new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), new TransactionPoolMetrics(metricsSystem), TransactionPoolConfiguration.DEFAULT, null); diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java index 3ea2ee83633..af908d5520b 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java @@ -44,7 +44,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; -import org.hyperledger.besu.ethereum.core.MiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -117,7 +117,12 @@ public void setUp() { protocolContext, batchAddedListener, ethContext, - new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .toParameters(), + // new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), new TransactionPoolMetrics(metricsSystem), TransactionPoolConfiguration.DEFAULT, null); diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/ApiConfiguration.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/ApiConfiguration.java index f8b52054d57..6652682fc4f 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/ApiConfiguration.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/ApiConfiguration.java @@ -16,6 +16,8 @@ package org.hyperledger.besu.ethereum.api; +import java.util.function.LongSupplier; + import org.immutables.value.Value; @Value.Immutable @@ -33,8 +35,8 @@ public double getGasPricePercentile() { } @Value.Default - public long getGasPriceMin() { - return 1_000_000_000L; // 1 GWei + public LongSupplier getGasPriceMinSupplier() { + return () -> 1_000_000_000L; // 1 GWei } @Value.Default diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueries.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueries.java index 04bfdd9727a..eede84fb82b 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueries.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueries.java @@ -969,7 +969,7 @@ public Optional gasPrice() { ? Optional.empty() : Optional.of( Math.max( - apiConfig.getGasPriceMin(), + apiConfig.getGasPriceMinSupplier().getAsLong(), Math.min( apiConfig.getGasPriceMax(), gasCollection[ diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/graphql/AbstractEthGraphQLHttpServiceTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/graphql/AbstractEthGraphQLHttpServiceTest.java index bba69967d52..9a03f782e5b 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/graphql/AbstractEthGraphQLHttpServiceTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/graphql/AbstractEthGraphQLHttpServiceTest.java @@ -118,7 +118,7 @@ public void setupTest() throws Exception { context.getWorldStateArchive(), Optional.empty(), Optional.empty(), - ImmutableApiConfiguration.builder().gasPriceMin(0).build()); + ImmutableApiConfiguration.builder().gasPriceMinSupplier(() -> 0).build()); final Set supportedCapabilities = new HashSet<>(); supportedCapabilities.add(EthProtocol.ETH62); diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGasPriceTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGasPriceTest.java index eef2b4422e8..27462501010 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGasPriceTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGasPriceTest.java @@ -67,7 +67,7 @@ public void setUp() { null, Optional.empty(), Optional.empty(), - ImmutableApiConfiguration.builder().gasPriceMin(100).build()), + ImmutableApiConfiguration.builder().gasPriceMinSupplier(() -> 100).build()), miningCoordinator); } diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java index 3fa80f1dd0a..b623817ae35 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java @@ -31,6 +31,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.Deposit; import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; @@ -61,7 +62,6 @@ import java.util.Optional; import java.util.concurrent.CancellationException; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.function.Supplier; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.Lists; @@ -81,41 +81,44 @@ public interface ExtraDataCalculator { protected final Address coinbase; private final MiningBeneficiaryCalculator miningBeneficiaryCalculator; - protected final Supplier> targetGasLimitSupplier; + // protected final Supplier> targetGasLimitSupplier; private final ExtraDataCalculator extraDataCalculator; private final TransactionPool transactionPool; + protected final MiningParameters miningParameters; protected final ProtocolContext protocolContext; protected final ProtocolSchedule protocolSchedule; protected final BlockHeaderFunctions blockHeaderFunctions; - private final Wei minTransactionGasPrice; - private final Double minBlockOccupancyRatio; + // private final Wei minTransactionGasPrice; + // private final Double minBlockOccupancyRatio; protected final BlockHeader parentHeader; private final Optional
depositContractAddress; private final AtomicBoolean isCancelled = new AtomicBoolean(false); protected AbstractBlockCreator( + final MiningParameters miningParameters, final Address coinbase, final MiningBeneficiaryCalculator miningBeneficiaryCalculator, - final Supplier> targetGasLimitSupplier, + // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - final Wei minTransactionGasPrice, - final Double minBlockOccupancyRatio, + // final Wei minTransactionGasPrice, + // final Double minBlockOccupancyRatio, final BlockHeader parentHeader, final Optional
depositContractAddress) { + this.miningParameters = miningParameters; this.coinbase = coinbase; this.miningBeneficiaryCalculator = miningBeneficiaryCalculator; - this.targetGasLimitSupplier = targetGasLimitSupplier; + // this.targetGasLimitSupplier = targetGasLimitSupplier; this.extraDataCalculator = extraDataCalculator; this.transactionPool = transactionPool; this.protocolContext = protocolContext; this.protocolSchedule = protocolSchedule; - this.minTransactionGasPrice = minTransactionGasPrice; - this.minBlockOccupancyRatio = minBlockOccupancyRatio; + // this.minTransactionGasPrice = minTransactionGasPrice; + // this.minBlockOccupancyRatio = minBlockOccupancyRatio; this.parentHeader = parentHeader; this.depositContractAddress = depositContractAddress; blockHeaderFunctions = ScheduleBasedBlockHeaderFunctions.create(protocolSchedule); @@ -341,14 +344,15 @@ private TransactionSelectionResults selectTransactions( final BlockTransactionSelector selector = new BlockTransactionSelector( + miningParameters, transactionProcessor, protocolContext.getBlockchain(), disposableWorldState, transactionPool, processableBlockHeader, transactionReceiptFactory, - minTransactionGasPrice, - minBlockOccupancyRatio, + // minTransactionGasPrice, + // minBlockOccupancyRatio, isCancelled::get, miningBeneficiary, blobGasPrice, @@ -395,7 +399,10 @@ private ProcessableBlockHeader createPendingBlockHeader( .getGasLimitCalculator() .nextGasLimit( parentHeader.getGasLimit(), - targetGasLimitSupplier.get().orElse(parentHeader.getGasLimit()), + miningParameters + .getDynamic() + .getTargetGasLimit() + .orElse(parentHeader.getGasLimit()), newBlockNumber); final DifficultyCalculator difficultyCalculator = protocolSpec.getDifficultyCalculator(); diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java index 3434c6f1b26..80dc651d9c7 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java @@ -32,7 +32,6 @@ import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; import org.apache.tuweni.bytes.Bytes; import org.slf4j.Logger; @@ -48,10 +47,12 @@ public abstract class AbstractMinerExecutor targetGasLimit; + // protected volatile Bytes extraData; + // protected volatile Wei minTransactionGasPrice; + // protected volatile Double minBlockOccupancyRatio; + // protected volatile Optional targetGasLimit; + + protected final MiningParameters miningParameters; private final AtomicBoolean stopped = new AtomicBoolean(false); @@ -64,11 +65,12 @@ protected AbstractMinerExecutor( this.protocolContext = protocolContext; this.protocolSchedule = protocolSchedule; this.transactionPool = transactionPool; - this.extraData = miningParams.getExtraData(); - this.minTransactionGasPrice = miningParams.getMinTransactionGasPrice(); + // this.extraData = miningParams.getExtraData(); + // this.minTransactionGasPrice = miningParams.getMinTransactionGasPrice(); this.blockScheduler = blockScheduler; - this.minBlockOccupancyRatio = miningParams.getMinBlockOccupancyRatio(); - this.targetGasLimit = miningParams.getTargetGasLimit(); + // this.minBlockOccupancyRatio = miningParams.getMinBlockOccupancyRatio(); + // this.targetGasLimit = miningParams.getTargetGasLimit(); + this.miningParameters = miningParams; } public Optional startAsyncMining( @@ -103,24 +105,25 @@ public abstract M createMiner( final BlockHeader parentHeader); public void setExtraData(final Bytes extraData) { - this.extraData = extraData.copy(); + miningParameters.getDynamic().setExtraData(extraData.copy()); } public void setMinTransactionGasPrice(final Wei minTransactionGasPrice) { - this.minTransactionGasPrice = minTransactionGasPrice; + miningParameters.getDynamic().setMinTransactionGasPrice(minTransactionGasPrice); } public Wei getMinTransactionGasPrice() { - return minTransactionGasPrice; + return miningParameters.getDynamic().getMinTransactionGasPrice(); } public abstract Optional
getCoinbase(); public void changeTargetGasLimit(final Long newTargetGasLimit) { if (AbstractGasLimitSpecification.isValidTargetGasLimit(newTargetGasLimit)) { - this.targetGasLimit.ifPresentOrElse( - existing -> existing.set(newTargetGasLimit), - () -> this.targetGasLimit = Optional.of(new AtomicLong(newTargetGasLimit))); + // miningContext.getTargetGasLimit().ifPresentOrElse( + // existing -> existing.set(newTargetGasLimit), + // () -> miningContext.setTargetGasLimit(Optional.of(new + // AtomicLong(newTargetGasLimit)))); } else { throw new UnsupportedOperationException("Specified target gas limit is invalid"); } diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/NoopMiningCoordinator.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/NoopMiningCoordinator.java index ab0a5c3d717..eccd2f291fc 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/NoopMiningCoordinator.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/NoopMiningCoordinator.java @@ -61,7 +61,7 @@ public boolean isMining() { @Override public Wei getMinTransactionGasPrice() { - return miningParameters.getMinTransactionGasPrice(); + return miningParameters.getDynamic().getMinTransactionGasPrice(); } @Override diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java index 46eb9d5c5ff..2a7e4447aac 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java @@ -15,10 +15,10 @@ package org.hyperledger.besu.ethereum.blockcreation; import org.hyperledger.besu.datatypes.Address; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.EthHash; @@ -31,7 +31,6 @@ import java.util.Optional; import java.util.concurrent.CancellationException; import java.util.concurrent.ExecutionException; -import java.util.function.Supplier; import org.apache.tuweni.units.bigints.UInt256; @@ -40,26 +39,28 @@ public class PoWBlockCreator extends AbstractBlockCreator { private final PoWSolver nonceSolver; public PoWBlockCreator( + final MiningParameters miningParameters, final Address coinbase, - final Supplier> targetGasLimitSupplier, + // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, final PoWSolver nonceSolver, - final Wei minTransactionGasPrice, - final Double minBlockOccupancyRatio, + // final Wei minTransactionGasPrice, + // final Double minBlockOccupancyRatio, final BlockHeader parentHeader) { super( + miningParameters, coinbase, __ -> coinbase, - targetGasLimitSupplier, + // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - minTransactionGasPrice, - minBlockOccupancyRatio, + // minTransactionGasPrice, + // minBlockOccupancyRatio, parentHeader, Optional.empty()); diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java index 49f7e702c23..91a6d0576bb 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java @@ -28,7 +28,6 @@ import org.hyperledger.besu.util.Subscribers; import java.util.Optional; -import java.util.concurrent.atomic.AtomicLong; import java.util.function.Function; public class PoWMinerExecutor extends AbstractMinerExecutor { @@ -51,7 +50,7 @@ public PoWMinerExecutor( final int maxOmmerDepth) { super(protocolContext, protocolSchedule, transactionPool, miningParams, blockScheduler); this.coinbase = miningParams.getCoinbase(); - this.nonceGenerator = miningParams.getNonceGenerator().orElse(new RandomNonceGenerator()); + this.nonceGenerator = miningParams.nonceGenerator().orElse(new RandomNonceGenerator()); this.epochCalculator = epochCalculator; this.powJobTimeToLive = powJobTimeToLive; this.maxOmmerDepth = maxOmmerDepth; @@ -89,15 +88,16 @@ public PoWBlockMiner createMiner( final Function blockCreator = (header) -> new PoWBlockCreator( + miningParameters, coinbase.orElse(Address.ZERO), - () -> targetGasLimit.map(AtomicLong::longValue), - parent -> extraData, + // () -> miningParameters.getTargetGasLimit()::get, + parent -> miningParameters.getDynamic().getExtraData(), transactionPool, protocolContext, protocolSchedule, solver, - minTransactionGasPrice, - minBlockOccupancyRatio, + // miningParameters.getMinTransactionGasPrice(), + // miningParameters.getMinBlockOccupancyRatio(), parentHeader); return new PoWBlockMiner( diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java index 0292f0bf67c..d16952b4390 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java @@ -17,16 +17,18 @@ import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket; import org.hyperledger.besu.evm.gascalculator.GasCalculator; public record BlockSelectionContext( + MiningParameters miningParameters, GasCalculator gasCalculator, GasLimitCalculator gasLimitCalculator, - Wei minTransactionGasPrice, - Double minBlockOccupancyRatio, + // Wei minTransactionGasPrice, + // Double minBlockOccupancyRatio, ProcessableBlockHeader processableBlockHeader, FeeMarket feeMarket, Wei blobGasPrice, diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java index 580b5be8bf2..bd05ad43f14 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java @@ -24,6 +24,7 @@ import org.hyperledger.besu.ethereum.blockcreation.txselection.selectors.PriceTransactionSelector; import org.hyperledger.besu.ethereum.blockcreation.txselection.selectors.ProcessingResultTransactionSelector; import org.hyperledger.besu.ethereum.chain.Blockchain; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader; import org.hyperledger.besu.ethereum.core.Transaction; @@ -46,6 +47,11 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.CancellationException; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.ExecutionException; +import java.util.concurrent.TimeUnit; +import java.util.concurrent.TimeoutException; +import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import org.slf4j.Logger; @@ -75,6 +81,7 @@ public class BlockTransactionSelector { private static final Logger LOG = LoggerFactory.getLogger(BlockTransactionSelector.class); + // private final MiningParameters miningParameters; private final Supplier isCancelled; private final MainnetTransactionProcessor transactionProcessor; private final Blockchain blockchain; @@ -85,16 +92,18 @@ public class BlockTransactionSelector { new TransactionSelectionResults(); private final List transactionSelectors; private final TransactionSelector externalTransactionSelector; + private final AtomicBoolean isTimeout = new AtomicBoolean(false); public BlockTransactionSelector( + final MiningParameters miningParameters, final MainnetTransactionProcessor transactionProcessor, final Blockchain blockchain, final MutableWorldState worldState, final TransactionPool transactionPool, final ProcessableBlockHeader processableBlockHeader, final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory, - final Wei minTransactionGasPrice, - final Double minBlockOccupancyRatio, + // final Wei minTransactionGasPrice, + // final Double minBlockOccupancyRatio, final Supplier isCancelled, final Address miningBeneficiary, final Wei blobGasPrice, @@ -102,6 +111,7 @@ public BlockTransactionSelector( final GasCalculator gasCalculator, final GasLimitCalculator gasLimitCalculator, final Optional transactionSelectorFactory) { + // this.miningParameters = miningParameters; this.transactionProcessor = transactionProcessor; this.blockchain = blockchain; this.worldState = worldState; @@ -109,10 +119,11 @@ public BlockTransactionSelector( this.isCancelled = isCancelled; this.blockSelectionContext = new BlockSelectionContext( + miningParameters, gasCalculator, gasLimitCalculator, - minTransactionGasPrice, - minBlockOccupancyRatio, + // minTransactionGasPrice, + // minBlockOccupancyRatio, processableBlockHeader, feeMarket, blobGasPrice, @@ -139,17 +150,7 @@ public TransactionSelectionResults buildTransactionListForBlock() { .setMessage("Transaction pool stats {}") .addArgument(blockSelectionContext.transactionPool().logStats()) .log(); - blockSelectionContext - .transactionPool() - .selectTransactions( - pendingTransaction -> { - final var res = evaluateTransaction(pendingTransaction); - if (!res.selected()) { - transactionSelectionResults.updateNotSelected( - pendingTransaction.getTransaction(), res); - } - return res; - }); + timeLimitedSelection(); LOG.atTrace() .setMessage("Transaction selection result {}") .addArgument(transactionSelectionResults::toTraceLog) @@ -157,6 +158,37 @@ public TransactionSelectionResults buildTransactionListForBlock() { return transactionSelectionResults; } + private void timeLimitedSelection() { + final var txSelection = + CompletableFuture.runAsync( + () -> + blockSelectionContext + .transactionPool() + .selectTransactions( + pendingTransaction -> { + final var res = evaluateTransaction(pendingTransaction); + if (!res.selected()) { + transactionSelectionResults.updateNotSelected( + pendingTransaction.getTransaction(), res); + } + return res; + })); + + try { + txSelection.get(5000, TimeUnit.MILLISECONDS); + } catch (InterruptedException | ExecutionException e) { + if (isCancelled.get()) { + throw new CancellationException("Cancelled during transaction selection."); + } + LOG.warn("Error during block transaction selection", e); + } catch (TimeoutException e) { + synchronized (isTimeout) { + isTimeout.set(true); + } + LOG.warn("Timeout during block transaction selection, interrupting transaction selection", e); + } + } + /** * Evaluates a list of transactions and updates the selection results accordingly. If a * transaction is not selected during the evaluation, it is updated as not selected in the @@ -226,23 +258,29 @@ private TransactionSelectionResult evaluateTransaction( final long cumulativeGasUsed = transactionSelectionResults.getCumulativeGasUsed() + gasUsedByTransaction; - worldStateUpdater.commit(); - final TransactionReceipt receipt = - transactionReceiptFactory.create( - transaction.getType(), effectiveResult, worldState, cumulativeGasUsed); + synchronized (isTimeout) { + if (!isTimeout.get()) { + worldStateUpdater.commit(); + final TransactionReceipt receipt = + transactionReceiptFactory.create( + transaction.getType(), effectiveResult, worldState, cumulativeGasUsed); - final long blobGasUsed = - blockSelectionContext.gasCalculator().blobGasCost(transaction.getBlobCount()); + final long blobGasUsed = + blockSelectionContext.gasCalculator().blobGasCost(transaction.getBlobCount()); - transactionSelectionResults.updateSelected( - transaction, receipt, gasUsedByTransaction, blobGasUsed); + transactionSelectionResults.updateSelected( + transaction, receipt, gasUsedByTransaction, blobGasUsed); - LOG.atTrace() - .setMessage("Selected {} for block creation") - .addArgument(transaction::toTraceLog) - .log(); + LOG.atTrace() + .setMessage("Selected {} for block creation") + .addArgument(transaction::toTraceLog) + .log(); - return TransactionSelectionResult.SELECTED; + return TransactionSelectionResult.SELECTED; + } else { + return TransactionSelectionResult.BLOCK_SELECTION_TIMEOUT; + } + } } /** diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java index 5d60ef8fc62..14ad0d81294 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java @@ -118,13 +118,13 @@ private boolean blockOccupancyAboveThreshold( LOG.trace( "Min block occupancy ratio {}, gas used {}, available {}, remaining {}, used/available {}", - context.minBlockOccupancyRatio(), + context.miningParameters().getDynamic().getMinBlockOccupancyRatio(), gasUsed, gasAvailable, gasRemaining, occupancyRatio); - return occupancyRatio >= context.minBlockOccupancyRatio(); + return occupancyRatio >= context.miningParameters().getDynamic().getMinBlockOccupancyRatio(); } /** diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/PriceTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/PriceTransactionSelector.java index a6c1889e497..57cef550a21 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/PriceTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/PriceTransactionSelector.java @@ -87,11 +87,16 @@ private boolean transactionCurrentPriceBelowMin(final PendingTransaction pending .feeMarket() .getTransactionPriceCalculator() .price(transaction, context.processableBlockHeader().getBaseFee()); - if (context.minTransactionGasPrice().compareTo(currentMinTransactionGasPriceInBlock) > 0) { + if (context + .miningParameters() + .getDynamic() + .getMinTransactionGasPrice() + .compareTo(currentMinTransactionGasPriceInBlock) + > 0) { LOG.trace( "Current gas fee of {} is lower than configured minimum {}, skipping", transaction, - context.minTransactionGasPrice()); + context.miningParameters().getDynamic().getMinTransactionGasPrice()); return true; } } diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java index b5ad06d8248..a3a85e7606e 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java @@ -49,6 +49,7 @@ import org.hyperledger.besu.ethereum.core.Deposit; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; @@ -81,7 +82,6 @@ import java.util.List; import java.util.Map; import java.util.Optional; -import java.util.function.Supplier; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; @@ -385,16 +385,27 @@ private AbstractBlockCreator createBlockCreator( null); transactionPool.setEnabled(); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(Address.ZERO) + .build() + .getDynamic() + .setExtraData(Bytes.fromHexString("deadbeef")) + .setMinTransactionGasPrice(Wei.ONE) + .setMinBlockOccupancyRatio(0d) + .toParameters(); + return new TestBlockCreator( + miningParameters, Address.ZERO, __ -> Address.ZERO, - () -> Optional.of(30_000_000L), + // () -> Optional.of(30_000_000L), __ -> Bytes.fromHexString("deadbeef"), transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), - Wei.of(1L), - 0d, + // Wei.of(1L), + // 0d, blockchain.getChainHeadHeader(), depositContractAddress); } @@ -402,27 +413,29 @@ private AbstractBlockCreator createBlockCreator( static class TestBlockCreator extends AbstractBlockCreator { protected TestBlockCreator( + final MiningParameters miningParameters, final Address coinbase, final MiningBeneficiaryCalculator miningBeneficiaryCalculator, - final Supplier> targetGasLimitSupplier, + // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - final Wei minTransactionGasPrice, - final Double minBlockOccupancyRatio, + // final Wei minTransactionGasPrice, + // final Double minBlockOccupancyRatio, final BlockHeader parentHeader, final Optional
depositContractAddress) { super( + miningParameters, coinbase, miningBeneficiaryCalculator, - targetGasLimitSupplier, + // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - minTransactionGasPrice, - minBlockOccupancyRatio, + // minTransactionGasPrice, + // minBlockOccupancyRatio, parentHeader, depositContractAddress); } 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 15b99b3461c..96d8d5cf7f7 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 @@ -111,7 +111,9 @@ public abstract class AbstractBlockTransactionSelectorTest { protected ProtocolContext protocolContext; @Mock protected MainnetTransactionProcessor transactionProcessor; - @Mock protected MiningParameters miningParameters; + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + protected MiningParameters miningParameters; @Mock(answer = Answers.RETURNS_DEEP_STUBS) protected EthContext ethContext; @@ -143,7 +145,7 @@ public void setup() { when(protocolContext.getWorldStateArchive().getMutable(any(), anyBoolean())) .thenReturn(Optional.of(worldState)); when(ethContext.getEthPeers().subscribeConnect(any())).thenReturn(1L); - when(miningParameters.getMinTransactionGasPrice()).thenReturn(Wei.ONE); + when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.ONE); transactionPool = createTransactionPool(); } @@ -699,14 +701,15 @@ protected BlockTransactionSelector createBlockSelector( final double minBlockOccupancyRatio) { final BlockTransactionSelector selector = new BlockTransactionSelector( + miningParameters, transactionProcessor, blockchain, worldState, transactionPool, blockHeader, this::createReceipt, - minGasPrice, - minBlockOccupancyRatio, + // minGasPrice, + // minBlockOccupancyRatio, this::isCancelled, miningBeneficiary, blobGasPrice, @@ -728,14 +731,15 @@ protected BlockTransactionSelector createBlockSelectorWithTxSelPlugin( final TransactionSelectorFactory transactionSelectorFactory) { final BlockTransactionSelector selector = new BlockTransactionSelector( + miningParameters, transactionProcessor, blockchain, worldState, transactionPool, blockHeader, this::createReceipt, - minGasPrice, - minBlockOccupancyRatio, + // minGasPrice, + // minBlockOccupancyRatio, this::isCancelled, miningBeneficiary, blobGasPrice, diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java index 818210f88a4..37d6fb3ab24 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java @@ -31,6 +31,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.PrivacyParameters; @@ -58,7 +59,6 @@ import java.io.IOException; import java.math.BigInteger; import java.util.Collections; -import java.util.Optional; import java.util.function.Function; import com.google.common.collect.Lists; @@ -106,17 +106,28 @@ void createMainnetBlock1() throws IOException { final TransactionPool transactionPool = createTransactionPool(executionContextTestFixture); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(BLOCK_1_COINBASE) + .build() + .getDynamic() + .setExtraData(BLOCK_1_EXTRA_DATA) + .setMinTransactionGasPrice(Wei.ONE) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final PoWBlockCreator blockCreator = new PoWBlockCreator( + miningParameters, BLOCK_1_COINBASE, - Optional::empty, + // Optional::empty, parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), solver, - Wei.ZERO, - 0.8, + // Wei.ZERO, + // 0.8, executionContextTestFixture.getBlockchain().getChainHeadHeader()); // A Hashrate should not exist in the block creator prior to creating a block @@ -162,17 +173,28 @@ void createMainnetBlock1_fixedDifficulty1() { final TransactionPool transactionPool = createTransactionPool(executionContextTestFixture); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(BLOCK_1_COINBASE) + .build() + .getDynamic() + .setExtraData(BLOCK_1_EXTRA_DATA) + .setMinTransactionGasPrice(Wei.ONE) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final PoWBlockCreator blockCreator = new PoWBlockCreator( + miningParameters, BLOCK_1_COINBASE, - Optional::empty, + // Optional::empty, parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), solver, - Wei.ZERO, - 0.8, + // Wei.ZERO, + // 0.8, executionContextTestFixture.getBlockchain().getChainHeadHeader()); assertThat(blockCreator.createBlock(BLOCK_1_TIMESTAMP)).isNotNull(); @@ -209,17 +231,29 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsFalse() { final TransactionPool transactionPool = createTransactionPool(executionContextTestFixture); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(BLOCK_1_COINBASE) + .build() + .getDynamic() + .setTargetGasLimit(10_000_000L) + .setExtraData(BLOCK_1_EXTRA_DATA) + .setMinTransactionGasPrice(Wei.ONE) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final PoWBlockCreator blockCreator = new PoWBlockCreator( + miningParameters, BLOCK_1_COINBASE, - () -> Optional.of(10_000_000L), + // () -> Optional.of(10_000_000L), parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), solver, - Wei.ZERO, - 0.8, + // Wei.ZERO, + // 0.8, executionContextTestFixture.getBlockchain().getChainHeadHeader()); final MutableWorldState mutableWorldState = @@ -278,17 +312,29 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsTrue() { final TransactionPool transactionPool = createTransactionPool(executionContextTestFixture); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(BLOCK_1_COINBASE) + .build() + .getDynamic() + .setTargetGasLimit(10_000_000L) + .setExtraData(BLOCK_1_EXTRA_DATA) + .setMinTransactionGasPrice(Wei.ONE) + .setMinBlockOccupancyRatio(0.8) + .toParameters(); + final PoWBlockCreator blockCreator = new PoWBlockCreator( + miningParameters, BLOCK_1_COINBASE, - () -> Optional.of(10_000_000L), + // () -> Optional.of(10_000_000L), parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), solver, - Wei.ZERO, - 0.8, + // Wei.ZERO, + // 0.8, executionContextTestFixture.getBlockchain().getChainHeadHeader()); final MutableWorldState mutableWorldState = diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java index b3ab4ff0688..0b31b9759c2 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java @@ -20,9 +20,9 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.core.BlockHeader; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.transactions.ImmutableTransactionPoolConfiguration; @@ -48,8 +48,9 @@ public class PoWMinerExecutorTest { @Test public void startingMiningWithoutCoinbaseThrowsException() { - final MiningParameters miningParameters = - new MiningParameters.Builder().coinbase(null).minTransactionGasPrice(Wei.of(1000)).build(); + final MiningParameters miningParameters = ImmutableMiningParameters.builder().build(); + // new + // MiningParameters.Builder().coinbase(null).minTransactionGasPrice(Wei.of(1000)).build(); final TransactionPool transactionPool = createTransactionPool(miningParameters); @@ -71,7 +72,7 @@ public void startingMiningWithoutCoinbaseThrowsException() { @Test public void settingCoinbaseToNullThrowsException() { - final MiningParameters miningParameters = new MiningParameters.Builder().build(); + final MiningParameters miningParameters = ImmutableMiningParameters.builder().build(); final TransactionPool transactionPool = createTransactionPool(miningParameters); diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java index e90efaba5b9..386a74d4656 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java @@ -18,387 +18,453 @@ import org.hyperledger.besu.datatypes.Wei; import java.time.Duration; -import java.util.Objects; import java.util.Optional; -import java.util.concurrent.atomic.AtomicLong; +import java.util.OptionalLong; import org.apache.tuweni.bytes.Bytes; +import org.immutables.value.Value; + +@Value.Immutable +@Value.Style(allParameters = true) +@Value.Enclosing +public interface MiningParameters { + class Dynamic { + public static final Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY; + public static final Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); + public static final double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; + + private final MiningParameters miningParameters; + private volatile Bytes extraData = DEFAULT_EXTRA_DATA; + private volatile Wei minTransactionGasPrice = DEFAULT_MIN_TRANSACTION_GAS_PRICE; + private volatile double minBlockOccupancyRatio = DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; + private volatile OptionalLong targetGasLimit = OptionalLong.empty(); + + private Dynamic(final MiningParameters miningParameters) { + this.miningParameters = miningParameters; + } -public class MiningParameters { - - public static final int DEFAULT_REMOTE_SEALERS_LIMIT = 1000; - - public static final long DEFAULT_REMOTE_SEALERS_TTL = Duration.ofMinutes(10).toMinutes(); - - public static final long DEFAULT_POW_JOB_TTL = Duration.ofMinutes(5).toMillis(); - - public static final int DEFAULT_MAX_OMMERS_DEPTH = 8; - - public static final long DEFAULT_POS_BLOCK_CREATION_MAX_TIME = Duration.ofSeconds(12).toMillis(); - - public static final long DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION = - Duration.ofMillis(500).toMillis(); - - private final Optional
coinbase; - private final Optional targetGasLimit; - private final Wei minTransactionGasPrice; - private final Bytes extraData; - private final boolean miningEnabled; - private final boolean stratumMiningEnabled; - private final String stratumNetworkInterface; - private final int stratumPort; - private final String stratumExtranonce; - private final Optional> maybeNonceGenerator; - private final Double minBlockOccupancyRatio; - private final int remoteSealersLimit; - private final long remoteSealersTimeToLive; - private final long powJobTimeToLive; - private final int maxOmmerDepth; - private final long posBlockCreationMaxTime; - private final long posBlockCreationRepetitionMinDuration; - - private MiningParameters( - final Address coinbase, - final Long targetGasLimit, - final Wei minTransactionGasPrice, - final Bytes extraData, - final boolean miningEnabled, - final boolean stratumMiningEnabled, - final String stratumNetworkInterface, - final int stratumPort, - final String stratumExtranonce, - final Optional> maybeNonceGenerator, - final Double minBlockOccupancyRatio, - final int remoteSealersLimit, - final long remoteSealersTimeToLive, - final long powJobTimeToLive, - final int maxOmmerDepth, - final long posBlockCreationMaxTime, - final long posBlockCreationRepetitionMinDuration) { - this.coinbase = Optional.ofNullable(coinbase); - this.targetGasLimit = Optional.ofNullable(targetGasLimit).map(AtomicLong::new); - this.minTransactionGasPrice = minTransactionGasPrice; - this.extraData = extraData; - this.miningEnabled = miningEnabled; - this.stratumMiningEnabled = stratumMiningEnabled; - this.stratumNetworkInterface = stratumNetworkInterface; - this.stratumPort = stratumPort; - this.stratumExtranonce = stratumExtranonce; - this.maybeNonceGenerator = maybeNonceGenerator; - this.minBlockOccupancyRatio = minBlockOccupancyRatio; - this.remoteSealersLimit = remoteSealersLimit; - this.remoteSealersTimeToLive = remoteSealersTimeToLive; - this.powJobTimeToLive = powJobTimeToLive; - this.maxOmmerDepth = maxOmmerDepth; - this.posBlockCreationMaxTime = posBlockCreationMaxTime; - this.posBlockCreationRepetitionMinDuration = posBlockCreationRepetitionMinDuration; - } - - public Optional
getCoinbase() { - return coinbase; - } - - public Optional getTargetGasLimit() { - return targetGasLimit; - } - - public Wei getMinTransactionGasPrice() { - return minTransactionGasPrice; - } - - public Bytes getExtraData() { - return extraData; - } - - public boolean isMiningEnabled() { - return miningEnabled; - } - - public boolean isStratumMiningEnabled() { - return stratumMiningEnabled; - } - - public String getStratumNetworkInterface() { - return stratumNetworkInterface; - } - - public int getStratumPort() { - return stratumPort; - } - - public String getStratumExtranonce() { - return stratumExtranonce; - } - - public Optional> getNonceGenerator() { - return maybeNonceGenerator; - } - - public Double getMinBlockOccupancyRatio() { - return minBlockOccupancyRatio; - } - - public int getRemoteSealersLimit() { - return remoteSealersLimit; - } - - public long getRemoteSealersTimeToLive() { - return remoteSealersTimeToLive; - } - - public long getPowJobTimeToLive() { - return powJobTimeToLive; - } - - public int getMaxOmmerDepth() { - return maxOmmerDepth; - } - - public long getPosBlockCreationMaxTime() { - return posBlockCreationMaxTime; - } - - public long getPosBlockCreationRepetitionMinDuration() { - return posBlockCreationRepetitionMinDuration; - } - - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - MiningParameters that = (MiningParameters) o; - return stratumPort == that.stratumPort - && Objects.equals(coinbase, that.coinbase) - && Objects.equals(targetGasLimit, that.targetGasLimit) - && Objects.equals(minTransactionGasPrice, that.minTransactionGasPrice) - && Objects.equals(extraData, that.extraData) - && miningEnabled == that.miningEnabled - && stratumMiningEnabled == that.stratumMiningEnabled - && Objects.equals(stratumNetworkInterface, that.stratumNetworkInterface) - && Objects.equals(stratumExtranonce, that.stratumExtranonce) - && Objects.equals(minBlockOccupancyRatio, that.minBlockOccupancyRatio) - && remoteSealersTimeToLive == that.remoteSealersTimeToLive - && remoteSealersLimit == that.remoteSealersLimit - && powJobTimeToLive == that.powJobTimeToLive - && posBlockCreationMaxTime == that.posBlockCreationMaxTime - && posBlockCreationRepetitionMinDuration == that.posBlockCreationRepetitionMinDuration; - } - - @Override - public int hashCode() { - return Objects.hash( - coinbase, - targetGasLimit, - minTransactionGasPrice, - extraData, - miningEnabled, - stratumMiningEnabled, - stratumNetworkInterface, - stratumPort, - stratumExtranonce, - minBlockOccupancyRatio, - remoteSealersLimit, - remoteSealersTimeToLive, - powJobTimeToLive, - posBlockCreationMaxTime, - posBlockCreationRepetitionMinDuration); - } - - @Override - public String toString() { - return "MiningParameters{" - + "coinbase=" - + coinbase - + ", targetGasLimit=" - + targetGasLimit.map(Object::toString).orElse("null") - + ", minTransactionGasPrice=" - + minTransactionGasPrice - + ", extraData=" - + extraData - + ", miningEnabled=" - + miningEnabled - + ", stratumMiningEnabled=" - + stratumMiningEnabled - + ", stratumNetworkInterface='" - + stratumNetworkInterface - + '\'' - + ", stratumPort=" - + stratumPort - + ", stratumExtranonce='" - + stratumExtranonce - + '\'' - + ", maybeNonceGenerator=" - + maybeNonceGenerator - + ", minBlockOccupancyRatio=" - + minBlockOccupancyRatio - + ", remoteSealersLimit=" - + remoteSealersLimit - + ", remoteSealersTimeToLive=" - + remoteSealersTimeToLive - + ", powJobTimeToLive=" - + powJobTimeToLive - + ", posBlockCreationMaxTime=" - + posBlockCreationMaxTime - + ", posBlockCreationRepetitionMinDuration=" - + posBlockCreationRepetitionMinDuration - + '}'; - } - - public static class Builder { - - private Address coinbase = null; - private Long targetGasLimit = null; - private Wei minTransactionGasPrice = Wei.ZERO; - private Bytes extraData = Bytes.EMPTY; - private boolean miningEnabled = false; - private boolean stratumMiningEnabled = false; - private String stratumNetworkInterface = "0.0.0.0"; - private int stratumPort = 8008; - private String stratumExtranonce = "080c"; - private Iterable maybeNonceGenerator; - private Double minBlockOccupancyRatio = 0.8; - private int remoteSealersLimit = DEFAULT_REMOTE_SEALERS_LIMIT; - private long remoteSealersTimeToLive = DEFAULT_REMOTE_SEALERS_TTL; - private long powJobTimeToLive = DEFAULT_POW_JOB_TTL; - private int maxOmmerDepth = DEFAULT_MAX_OMMERS_DEPTH; - private long posBlockCreationMaxTime = DEFAULT_POS_BLOCK_CREATION_MAX_TIME; - - private long posBlockCreationRepetitionMinDuration = - DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; - - public Builder() { - // zero arg + public MiningParameters toParameters() { + return miningParameters; } - public Builder(final MiningParameters existing) { - existing.getCoinbase().ifPresent(cb -> this.coinbase = cb); - existing - .getTargetGasLimit() - .map(AtomicLong::longValue) - .ifPresent(gasLimit -> this.targetGasLimit = gasLimit); - this.minTransactionGasPrice = existing.getMinTransactionGasPrice(); - this.extraData = existing.getExtraData(); - this.miningEnabled = existing.isMiningEnabled(); - this.stratumMiningEnabled = existing.isStratumMiningEnabled(); - this.stratumNetworkInterface = existing.getStratumNetworkInterface(); - this.stratumPort = existing.getStratumPort(); - this.stratumExtranonce = existing.getStratumExtranonce(); - existing.getNonceGenerator().ifPresent(ng -> this.maybeNonceGenerator = ng); - this.minBlockOccupancyRatio = existing.getMinBlockOccupancyRatio(); - this.remoteSealersLimit = existing.getRemoteSealersLimit(); - this.remoteSealersTimeToLive = existing.getRemoteSealersTimeToLive(); - this.powJobTimeToLive = existing.getPowJobTimeToLive(); - this.maxOmmerDepth = existing.getMaxOmmerDepth(); - this.posBlockCreationMaxTime = existing.getPosBlockCreationMaxTime(); - this.posBlockCreationRepetitionMinDuration = - existing.getPosBlockCreationRepetitionMinDuration(); + public Bytes getExtraData() { + return extraData; } - public Builder coinbase(final Address address) { - this.coinbase = address; + public Dynamic setExtraData(final Bytes extraData) { + this.extraData = extraData; return this; } - public Builder targetGasLimit(final Long targetGasLimit) { - this.targetGasLimit = targetGasLimit; - return this; + public Wei getMinTransactionGasPrice() { + return minTransactionGasPrice; } - public Builder minTransactionGasPrice(final Wei minTransactionGasPrice) { + public Dynamic setMinTransactionGasPrice(final Wei minTransactionGasPrice) { this.minTransactionGasPrice = minTransactionGasPrice; return this; } - public Builder extraData(final Bytes extraData) { - this.extraData = extraData; - return this; + public double getMinBlockOccupancyRatio() { + return minBlockOccupancyRatio; } - public Builder miningEnabled(final boolean miningEnabled) { - this.miningEnabled = miningEnabled; + public Dynamic setMinBlockOccupancyRatio(final double minBlockOccupancyRatio) { + this.minBlockOccupancyRatio = minBlockOccupancyRatio; return this; } - public Builder stratumMiningEnabled(final boolean stratumMiningEnabled) { - this.stratumMiningEnabled = stratumMiningEnabled; - return this; + public OptionalLong getTargetGasLimit() { + return targetGasLimit; } - public Builder stratumNetworkInterface(final String stratumNetworkInterface) { - this.stratumNetworkInterface = stratumNetworkInterface; + public Dynamic setTargetGasLimit(final long targetGasLimit) { + this.targetGasLimit = OptionalLong.of(targetGasLimit); return this; } + } - public Builder stratumPort(final int stratumPort) { - this.stratumPort = stratumPort; - return this; - } + // Double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; + int DEFAULT_REMOTE_SEALERS_LIMIT = 1000; + long DEFAULT_REMOTE_SEALERS_TTL = Duration.ofMinutes(10).toMinutes(); + long DEFAULT_POW_JOB_TTL = Duration.ofMinutes(5).toMillis(); + int DEFAULT_MAX_OMMERS_DEPTH = 8; + long DEFAULT_POS_BLOCK_CREATION_MAX_TIME = Duration.ofSeconds(12).toMillis(); + long DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION = Duration.ofMillis(500).toMillis(); + // private final Optional
coinbase; + // private final Optional targetGasLimit; + // private final Wei minTransactionGasPrice; + // private final Bytes extraData; + // private final boolean miningEnabled; + // private final boolean stratumMiningEnabled; + // private final String stratumNetworkInterface; + // private final int stratumPort; + // private final String stratumExtranonce; + // private final Optional> maybeNonceGenerator; + // private final Double minBlockOccupancyRatio; + // private final int remoteSealersLimit; + // private final long remoteSealersTimeToLive; + // private final long powJobTimeToLive; + // private final int maxOmmerDepth; + // private final long posBlockCreationMaxTime; + // private final long posBlockCreationRepetitionMinDuration; + + // private MiningParameters( + // final Address coinbase, + // final Long targetGasLimit, + // final Wei minTransactionGasPrice, + // final Bytes extraData, + // final boolean miningEnabled, + // final boolean stratumMiningEnabled, + // final String stratumNetworkInterface, + // final int stratumPort, + // final String stratumExtranonce, + // final Optional> maybeNonceGenerator, + // final Double minBlockOccupancyRatio, + // final int remoteSealersLimit, + // final long remoteSealersTimeToLive, + // final long powJobTimeToLive, + // final int maxOmmerDepth, + // final long posBlockCreationMaxTime, + // final long posBlockCreationRepetitionMinDuration) { + // this.coinbase = Optional.ofNullable(coinbase); + // this.targetGasLimit = Optional.ofNullable(targetGasLimit).map(AtomicLong::new); + // this.minTransactionGasPrice = minTransactionGasPrice; + // this.extraData = extraData; + // this.miningEnabled = miningEnabled; + // this.stratumMiningEnabled = stratumMiningEnabled; + // this.stratumNetworkInterface = stratumNetworkInterface; + // this.stratumPort = stratumPort; + // this.stratumExtranonce = stratumExtranonce; + // this.maybeNonceGenerator = maybeNonceGenerator; + // this.minBlockOccupancyRatio = minBlockOccupancyRatio; + // this.remoteSealersLimit = remoteSealersLimit; + // this.remoteSealersTimeToLive = remoteSealersTimeToLive; + // this.powJobTimeToLive = powJobTimeToLive; + // this.maxOmmerDepth = maxOmmerDepth; + // this.posBlockCreationMaxTime = posBlockCreationMaxTime; + // this.posBlockCreationRepetitionMinDuration = posBlockCreationRepetitionMinDuration; + // } + + @Value.Default + default Dynamic getDynamic() { + return new Dynamic(this); + } - public Builder stratumExtranonce(final String stratumExtranonce) { - this.stratumExtranonce = stratumExtranonce; - return this; - } + Optional
getCoinbase(); + // + // Optional getTargetGasLimit(); + // + // @Value.Default + // default Wei getMinTransactionGasPrice() { + // return Wei.ZERO; + // } + + // @Value.Default + // default Bytes getExtraData() { + // return DEFAULT_EXTRA_DATA; + // } + + @Value.Default + default boolean isMiningEnabled() { + return false; + } - public Builder maybeNonceGenerator(final Iterable maybeNonceGenerator) { - this.maybeNonceGenerator = maybeNonceGenerator; - return this; - } + @Value.Default + default boolean isStratumMiningEnabled() { + return false; + } - public Builder minBlockOccupancyRatio(final Double minBlockOccupancyRatio) { - this.minBlockOccupancyRatio = minBlockOccupancyRatio; - return this; - } + @Value.Default + default String getStratumNetworkInterface() { + return "0.0.0.0"; + } - public Builder remoteSealersLimit(final int remoteSealersLimit) { - this.remoteSealersLimit = remoteSealersLimit; - return this; - } + @Value.Default + default int getStratumPort() { + return 8008; + } - public Builder remoteSealersTimeToLive(final long remoteSealersTimeToLive) { - this.remoteSealersTimeToLive = remoteSealersTimeToLive; - return this; - } + @Value.Default + default String getStratumExtranonce() { + return "080c"; + } + // + // @Value.Default + // default Double getMinBlockOccupancyRatio() { + // return DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; + // } + + @Value.Default + default int getRemoteSealersLimit() { + return DEFAULT_REMOTE_SEALERS_LIMIT; + } - public Builder powJobTimeToLive(final long powJobTimeToLive) { - this.powJobTimeToLive = powJobTimeToLive; - return this; - } + @Value.Default + default long getRemoteSealersTimeToLive() { + return DEFAULT_REMOTE_SEALERS_TTL; + } - public Builder maxOmmerDepth(final int maxOmmerDepth) { - this.maxOmmerDepth = maxOmmerDepth; - return this; - } + @Value.Default + default long getPowJobTimeToLive() { + return DEFAULT_POW_JOB_TTL; + } - public Builder posBlockCreationMaxTime(final long posBlockCreationMaxTime) { - this.posBlockCreationMaxTime = posBlockCreationMaxTime; - return this; - } + @Value.Default + default int getMaxOmmerDepth() { + return DEFAULT_MAX_OMMERS_DEPTH; + } - public Builder posBlockCreationRepetitionMinDuration( - final long posBlockCreationRepetitionMinDuration) { - this.posBlockCreationRepetitionMinDuration = posBlockCreationRepetitionMinDuration; - return this; - } + @Value.Default + default long getPosBlockCreationMaxTime() { + return DEFAULT_POS_BLOCK_CREATION_MAX_TIME; + } - public MiningParameters build() { - return new MiningParameters( - coinbase, - targetGasLimit, - minTransactionGasPrice, - extraData, - miningEnabled, - stratumMiningEnabled, - stratumNetworkInterface, - stratumPort, - stratumExtranonce, - Optional.ofNullable(maybeNonceGenerator), - minBlockOccupancyRatio, - remoteSealersLimit, - remoteSealersTimeToLive, - powJobTimeToLive, - maxOmmerDepth, - posBlockCreationMaxTime, - posBlockCreationRepetitionMinDuration); - } + @Value.Default + default long getPosBlockCreationRepetitionMinDuration() { + return DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; } + + Optional> nonceGenerator(); + + // + // @Override + // public boolean equals(final Object o) { + // if (this == o) return true; + // if (o == null || getClass() != o.getClass()) return false; + // MiningParameters that = (MiningParameters) o; + // return stratumPort == that.stratumPort + // && Objects.equals(coinbase, that.coinbase) + // && Objects.equals(targetGasLimit, that.targetGasLimit) + // && Objects.equals(minTransactionGasPrice, that.minTransactionGasPrice) + // && Objects.equals(extraData, that.extraData) + // && miningEnabled == that.miningEnabled + // && stratumMiningEnabled == that.stratumMiningEnabled + // && Objects.equals(stratumNetworkInterface, that.stratumNetworkInterface) + // && Objects.equals(stratumExtranonce, that.stratumExtranonce) + // && Objects.equals(minBlockOccupancyRatio, that.minBlockOccupancyRatio) + // && remoteSealersTimeToLive == that.remoteSealersTimeToLive + // && remoteSealersLimit == that.remoteSealersLimit + // && powJobTimeToLive == that.powJobTimeToLive + // && posBlockCreationMaxTime == that.posBlockCreationMaxTime + // && posBlockCreationRepetitionMinDuration == that.posBlockCreationRepetitionMinDuration; + // } + // + // @Override + // public int hashCode() { + // return Objects.hash( + // coinbase, + // targetGasLimit, + // minTransactionGasPrice, + // extraData, + // miningEnabled, + // stratumMiningEnabled, + // stratumNetworkInterface, + // stratumPort, + // stratumExtranonce, + // minBlockOccupancyRatio, + // remoteSealersLimit, + // remoteSealersTimeToLive, + // powJobTimeToLive, + // posBlockCreationMaxTime, + // posBlockCreationRepetitionMinDuration); + // } + // + // @Override + // public String toString() { + // return "MiningParameters{" + // + "coinbase=" + // + coinbase + // + ", targetGasLimit=" + // + targetGasLimit.map(Object::toString).orElse("null") + // + ", minTransactionGasPrice=" + // + minTransactionGasPrice + // + ", extraData=" + // + extraData + // + ", miningEnabled=" + // + miningEnabled + // + ", stratumMiningEnabled=" + // + stratumMiningEnabled + // + ", stratumNetworkInterface='" + // + stratumNetworkInterface + // + '\'' + // + ", stratumPort=" + // + stratumPort + // + ", stratumExtranonce='" + // + stratumExtranonce + // + '\'' + // + ", maybeNonceGenerator=" + // + maybeNonceGenerator + // + ", minBlockOccupancyRatio=" + // + minBlockOccupancyRatio + // + ", remoteSealersLimit=" + // + remoteSealersLimit + // + ", remoteSealersTimeToLive=" + // + remoteSealersTimeToLive + // + ", powJobTimeToLive=" + // + powJobTimeToLive + // + ", posBlockCreationMaxTime=" + // + posBlockCreationMaxTime + // + ", posBlockCreationRepetitionMinDuration=" + // + posBlockCreationRepetitionMinDuration + // + '}'; + // } + + // public static class Builder { + // + // private Address coinbase = null; + // private Long targetGasLimit = null; + // private Wei minTransactionGasPrice = Wei.ZERO; + // private Bytes extraData = Bytes.EMPTY; + // private boolean miningEnabled = false; + // private boolean stratumMiningEnabled = false; + // private String stratumNetworkInterface = "0.0.0.0"; + // private int stratumPort = 8008; + // private String stratumExtranonce = "080c"; + // private Iterable maybeNonceGenerator; + // private Double minBlockOccupancyRatio = 0.8; + // private int remoteSealersLimit = DEFAULT_REMOTE_SEALERS_LIMIT; + // private long remoteSealersTimeToLive = DEFAULT_REMOTE_SEALERS_TTL; + // private long powJobTimeToLive = DEFAULT_POW_JOB_TTL; + // private int maxOmmerDepth = DEFAULT_MAX_OMMERS_DEPTH; + // private long posBlockCreationMaxTime = DEFAULT_POS_BLOCK_CREATION_MAX_TIME; + // + // private long posBlockCreationRepetitionMinDuration = + // DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; + // + // public Builder() { + // // zero arg + // } + // + // public Builder(final MiningParameters existing) { + // existing.getCoinbase().ifPresent(cb -> this.coinbase = cb); + // existing + // .getTargetGasLimit() + // .map(AtomicLong::longValue) + // .ifPresent(gasLimit -> this.targetGasLimit = gasLimit); + // this.minTransactionGasPrice = existing.getMinTransactionGasPrice(); + // this.extraData = existing.getExtraData(); + // this.miningEnabled = existing.isMiningEnabled(); + // this.stratumMiningEnabled = existing.isStratumMiningEnabled(); + // this.stratumNetworkInterface = existing.getStratumNetworkInterface(); + // this.stratumPort = existing.getStratumPort(); + // this.stratumExtranonce = existing.getStratumExtranonce(); + // existing.getNonceGenerator().ifPresent(ng -> this.maybeNonceGenerator = ng); + // this.minBlockOccupancyRatio = existing.getMinBlockOccupancyRatio(); + // this.remoteSealersLimit = existing.getRemoteSealersLimit(); + // this.remoteSealersTimeToLive = existing.getRemoteSealersTimeToLive(); + // this.powJobTimeToLive = existing.getPowJobTimeToLive(); + // this.maxOmmerDepth = existing.getMaxOmmerDepth(); + // this.posBlockCreationMaxTime = existing.getPosBlockCreationMaxTime(); + // this.posBlockCreationRepetitionMinDuration = + // existing.getPosBlockCreationRepetitionMinDuration(); + // } + // + // public Builder coinbase(final Address address) { + // this.coinbase = address; + // return this; + // } + // + // public Builder targetGasLimit(final Long targetGasLimit) { + // this.targetGasLimit = targetGasLimit; + // return this; + // } + // + // public Builder minTransactionGasPrice(final Wei minTransactionGasPrice) { + // this.minTransactionGasPrice = minTransactionGasPrice; + // return this; + // } + // + // public Builder extraData(final Bytes extraData) { + // this.extraData = extraData; + // return this; + // } + // + // public Builder miningEnabled(final boolean miningEnabled) { + // this.miningEnabled = miningEnabled; + // return this; + // } + // + // public Builder stratumMiningEnabled(final boolean stratumMiningEnabled) { + // this.stratumMiningEnabled = stratumMiningEnabled; + // return this; + // } + // + // public Builder stratumNetworkInterface(final String stratumNetworkInterface) { + // this.stratumNetworkInterface = stratumNetworkInterface; + // return this; + // } + // + // public Builder stratumPort(final int stratumPort) { + // this.stratumPort = stratumPort; + // return this; + // } + // + // public Builder stratumExtranonce(final String stratumExtranonce) { + // this.stratumExtranonce = stratumExtranonce; + // return this; + // } + // + // public Builder maybeNonceGenerator(final Iterable maybeNonceGenerator) { + // this.maybeNonceGenerator = maybeNonceGenerator; + // return this; + // } + // + // public Builder minBlockOccupancyRatio(final Double minBlockOccupancyRatio) { + // this.minBlockOccupancyRatio = minBlockOccupancyRatio; + // return this; + // } + // + // public Builder remoteSealersLimit(final int remoteSealersLimit) { + // this.remoteSealersLimit = remoteSealersLimit; + // return this; + // } + // + // public Builder remoteSealersTimeToLive(final long remoteSealersTimeToLive) { + // this.remoteSealersTimeToLive = remoteSealersTimeToLive; + // return this; + // } + // + // public Builder powJobTimeToLive(final long powJobTimeToLive) { + // this.powJobTimeToLive = powJobTimeToLive; + // return this; + // } + // + // public Builder maxOmmerDepth(final int maxOmmerDepth) { + // this.maxOmmerDepth = maxOmmerDepth; + // return this; + // } + // + // public Builder posBlockCreationMaxTime(final long posBlockCreationMaxTime) { + // this.posBlockCreationMaxTime = posBlockCreationMaxTime; + // return this; + // } + // + // public Builder posBlockCreationRepetitionMinDuration( + // final long posBlockCreationRepetitionMinDuration) { + // this.posBlockCreationRepetitionMinDuration = posBlockCreationRepetitionMinDuration; + // return this; + // } + // + // public MiningParameters build() { + // return new MiningParameters( + // coinbase, + // targetGasLimit, + // minTransactionGasPrice, + // extraData, + // miningEnabled, + // stratumMiningEnabled, + // stratumNetworkInterface, + // stratumPort, + // stratumExtranonce, + // Optional.ofNullable(maybeNonceGenerator), + // minBlockOccupancyRatio, + // remoteSealersLimit, + // remoteSealersTimeToLive, + // powJobTimeToLive, + // maxOmmerDepth, + // posBlockCreationMaxTime, + // posBlockCreationRepetitionMinDuration); + // } + // } } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java index da12289afa8..e38cde5c3f6 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java @@ -41,6 +41,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; @@ -77,7 +78,6 @@ import java.util.Optional; import java.util.function.BiFunction; import java.util.function.Function; -import java.util.function.Supplier; import java.util.stream.Collectors; import org.apache.tuweni.bytes.Bytes; @@ -205,26 +205,28 @@ public int getDatabaseVersion() { static class TestBlockCreator extends AbstractBlockCreator { private TestBlockCreator( + final MiningParameters miningParameters, final Address coinbase, final MiningBeneficiaryCalculator miningBeneficiaryCalculator, - final Supplier> targetGasLimitSupplier, + // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - final Wei minTransactionGasPrice, - final Double minBlockOccupancyRatio, + // final Wei minTransactionGasPrice, + // final Double minBlockOccupancyRatio, final BlockHeader parentHeader) { super( + miningParameters, coinbase, miningBeneficiaryCalculator, - targetGasLimitSupplier, + // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - minTransactionGasPrice, - minBlockOccupancyRatio, + // minTransactionGasPrice, + // minBlockOccupancyRatio, parentHeader, Optional.empty()); } @@ -234,16 +236,29 @@ static TestBlockCreator forHeader( final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, final TransactionPool transactionPool) { + + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .coinbase(Address.ZERO) + .build() + .getDynamic() + .setExtraData(Bytes.fromHexString("deadbeef")) + .setTargetGasLimit(30_000_000L) + .setMinTransactionGasPrice(Wei.ONE) + .setMinBlockOccupancyRatio(0d) + .toParameters(); + return new TestBlockCreator( + miningParameters, Address.ZERO, __ -> Address.ZERO, - () -> Optional.of(30_000_000L), + // () -> Optional.of(30_000_000L), __ -> Bytes.fromHexString("deadbeef"), transactionPool, protocolContext, protocolSchedule, - Wei.of(1L), - 0d, + // Wei.of(1L), + // 0d, parentHeader); } diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPool.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPool.java index 9b24f6cb539..afaffaeaefd 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPool.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPool.java @@ -203,7 +203,7 @@ private Optional getMaxGasPrice(final Transaction transaction) { private boolean isMaxGasPriceBelowConfiguredMinGasPrice(final Transaction transaction) { return getMaxGasPrice(transaction) - .map(g -> g.lessThan(miningParameters.getMinTransactionGasPrice())) + .map(g -> g.lessThan(miningParameters.getDynamic().getMinTransactionGasPrice())) .orElse(true); } @@ -524,7 +524,7 @@ && isMaxGasPriceBelowConfiguredMinGasPrice(transaction)) LOG.atTrace() .setMessage("Discard transaction {} below min gas price {}") .addArgument(transaction::toTraceLog) - .addArgument(miningParameters::getMinTransactionGasPrice) + .addArgument(miningParameters.getDynamic()::getMinTransactionGasPrice) .log(); return TransactionInvalidReason.GAS_PRICE_TOO_LOW; } diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java index 60574c92152..dd99e0f4bc6 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java @@ -37,7 +37,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.Difficulty; -import org.hyperledger.besu.ethereum.core.MiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.TransactionReceipt; @@ -1116,7 +1116,13 @@ public void transactionMessagesGoToTheCorrectExecutor() { TestClock.system(ZoneId.systemDefault()), metricsSystem, new SyncState(blockchain, ethManager.ethContext().getEthPeers()), - new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .toParameters(), + // new + // MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), TransactionPoolConfiguration.DEFAULT, null) .setEnabled(); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java index dc410937341..e05a4925913 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java @@ -26,7 +26,7 @@ import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; -import org.hyperledger.besu.ethereum.core.MiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.eth.EthProtocol; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.manager.DeterministicEthScheduler; @@ -136,7 +136,12 @@ public void setupTest() { TestClock.system(ZoneId.systemDefault()), metricsSystem, syncState, - new MiningParameters.Builder().minTransactionGasPrice(Wei.ONE).build(), + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ONE) + .toParameters(), + // new MiningParameters.Builder().minTransactionGasPrice(Wei.ONE).build(), TransactionPoolConfiguration.DEFAULT, null); transactionPool.setEnabled(); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTest.java index beeb2b1e43b..b44575c9914 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTest.java @@ -131,7 +131,10 @@ public abstract class AbstractTransactionPoolTest { protected TransactionValidatorFactory transactionValidatorFactory; @Mock protected PendingTransactionAddedListener listener; - @Mock protected MiningParameters miningParameters; + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + protected MiningParameters miningParameters; + @Mock protected TransactionsMessageSender transactionsMessageSender; @Mock protected NewPooledTransactionHashesMessageSender newPooledTransactionHashesMessageSender; @Mock protected ProtocolSpec protocolSpec; @@ -249,7 +252,7 @@ public void setUp() { transactionPool = createTransactionPool(); blockchain.observeBlockAdded(transactionPool); - when(miningParameters.getMinTransactionGasPrice()).thenReturn(Wei.of(2)); + when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.of(2)); } protected TransactionPool createTransactionPool() { @@ -944,7 +947,7 @@ public void shouldAcceptZeroGasPriceFrontierLocalTransactionsWhenMining() { public void shouldAcceptZeroGasPriceTransactionWhenMinGasPriceIsZero( final boolean disableLocalTxs) { transactionPool = createTransactionPool(b -> b.disableLocalTransactions(disableLocalTxs)); - when(miningParameters.getMinTransactionGasPrice()).thenReturn(Wei.ZERO); + when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.ZERO); final Transaction transaction = createTransaction(0, Wei.ZERO); @@ -958,7 +961,7 @@ public void shouldAcceptZeroGasPriceTransactionWhenMinGasPriceIsZero( public void shouldAcceptZeroGasPriceFrontierTxsWhenMinGasPriceIsZeroAndLondonWithZeroBaseFee( final boolean disableLocalTxs) { transactionPool = createTransactionPool(b -> b.disableLocalTransactions(disableLocalTxs)); - when(miningParameters.getMinTransactionGasPrice()).thenReturn(Wei.ZERO); + when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.ZERO); when(protocolSpec.getFeeMarket()).thenReturn(FeeMarket.london(0, Optional.of(Wei.ZERO))); whenBlockBaseFeeIs(Wei.ZERO); @@ -973,7 +976,7 @@ public void shouldAcceptZeroGasPriceFrontierTxsWhenMinGasPriceIsZeroAndLondonWit public void shouldAcceptZeroGasPrice1559TxsWhenMinGasPriceIsZeroAndLondonWithZeroBaseFee( final boolean disableLocalTxs) { transactionPool = createTransactionPool(b -> b.disableLocalTransactions(disableLocalTxs)); - when(miningParameters.getMinTransactionGasPrice()).thenReturn(Wei.ZERO); + when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.ZERO); when(protocolSpec.getFeeMarket()).thenReturn(FeeMarket.london(0, Optional.of(Wei.ZERO))); whenBlockBaseFeeIs(Wei.ZERO); @@ -1243,7 +1246,7 @@ protected int add1559TxAndGetPendingTxsCount( final Wei lastBlockBaseFee, final Wei txMaxFeePerGas, final boolean isLocal) { - when(miningParameters.getMinTransactionGasPrice()).thenReturn(minGasPrice); + when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(minGasPrice); when(protocolSpec.getFeeMarket()).thenReturn(FeeMarket.london(0, Optional.of(genesisBaseFee))); whenBlockBaseFeeIs(lastBlockBaseFee); 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 6d3eb668f8f..8480090c201 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 @@ -31,8 +31,8 @@ import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; -import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.difficulty.fixed.FixedDifficultyProtocolSchedule; import org.hyperledger.besu.ethereum.eth.EthProtocol; @@ -163,7 +163,12 @@ public boolean isMessagePermitted(final EnodeURL destinationEnode, final int cod TestClock.system(ZoneId.systemDefault()), metricsSystem, syncState, - new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ZERO) + .toParameters(), + // new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), TransactionPoolConfiguration.DEFAULT, null); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java index 3da9bb9c66d..6fea6dec4d9 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java @@ -32,7 +32,7 @@ import org.hyperledger.besu.ethereum.chain.BlockAddedObserver; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; -import org.hyperledger.besu.ethereum.core.MiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -241,7 +241,12 @@ private void setupInitialSyncPhase(final boolean hasInitialSyncPhase) { TestClock.fixed(), new TransactionPoolMetrics(new NoOpMetricsSystem()), syncState, - new MiningParameters.Builder().minTransactionGasPrice(Wei.ONE).build(), + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ONE) + .toParameters(), + // new MiningParameters.Builder().minTransactionGasPrice(Wei.ONE).build(), ImmutableTransactionPoolConfiguration.builder() .txPoolMaxSize(1) .pendingTxRetentionPeriod(1) @@ -350,7 +355,12 @@ private TransactionPool createTransactionPool( TestClock.fixed(), new NoOpMetricsSystem(), syncState, - new MiningParameters.Builder().minTransactionGasPrice(Wei.ONE).build(), + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ONE) + .toParameters(), + // new MiningParameters.Builder().minTransactionGasPrice(Wei.ONE).build(), ImmutableTransactionPoolConfiguration.builder() .txPoolImplementation(implementation) .txPoolMaxSize(1) diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java index 4d29bfd213e..4b1f0ac586b 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java @@ -32,6 +32,7 @@ import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; @@ -231,6 +232,9 @@ private boolean buildContext( .txPoolLimitByAccountPercentage(Fraction.fromFloat(0.004f)) .build(); + final MiningParameters miningParameters = ImmutableMiningParameters.builder().build(); + miningParameters.getDynamic().setMinTransactionGasPrice(Wei.ZERO); + transactionPool = TransactionPoolFactory.createTransactionPool( protocolSchedule, @@ -239,7 +243,7 @@ private boolean buildContext( retestethClock, metricsSystem, syncState, - new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), + miningParameters, transactionPoolConfiguration, null); diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java index f802ee73e4b..20736c0cde4 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java @@ -24,14 +24,14 @@ import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockImporter; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.mainnet.BlockImportResult; import org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.retesteth.RetestethClock; import org.hyperledger.besu.ethereum.retesteth.RetestethContext; -import java.util.Optional; - public class TestMineBlocks implements JsonRpcMethod { private final RetestethContext context; @@ -62,17 +62,24 @@ private boolean mineNewBlock() { final ProtocolContext protocolContext = context.getProtocolContext(); final MutableBlockchain blockchain = context.getBlockchain(); final HeaderValidationMode headerValidationMode = context.getHeaderValidationMode(); + final MiningParameters miningParameters = ImmutableMiningParameters.builder().build(); + miningParameters + .getDynamic() + .setTargetGasLimit(blockchain.getChainHeadHeader().getGasLimit()) + .setMinBlockOccupancyRatio(0.0) + .setMinTransactionGasPrice(Wei.ZERO); final PoWBlockCreator blockCreator = new PoWBlockCreator( + miningParameters, context.getCoinbase(), - () -> Optional.of(blockchain.getChainHeadHeader().getGasLimit()), + // () -> Optional.of(blockchain.getChainHeadHeader().getGasLimit()), header -> context.getExtraData(), context.getTransactionPool(), protocolContext, protocolSchedule, context.getEthHashSolver(), - Wei.ZERO, - 0.0, + // Wei.ZERO, + // 0.0, blockchain.getChainHeadHeader()); final Block block = blockCreator.createBlock(retesethClock.instant().getEpochSecond()).getBlock(); diff --git a/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/TransactionSelectionResult.java b/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/TransactionSelectionResult.java index ffae842ca72..dee35f82b7b 100644 --- a/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/TransactionSelectionResult.java +++ b/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/TransactionSelectionResult.java @@ -28,6 +28,7 @@ private enum Status { SELECTED, BLOCK_FULL(true, false), BLOCK_OCCUPANCY_ABOVE_THRESHOLD(true, false), + BLOCK_SELECTION_TIMEOUT(true, false), INVALID_TRANSIENT(false, false), INVALID(false, true); @@ -56,6 +57,11 @@ public String toString() { /** The transaction has not been selected since the block is full. */ public static final TransactionSelectionResult BLOCK_FULL = new TransactionSelectionResult(Status.BLOCK_FULL); + /** There was no more time to add transaction to the block */ + public static final TransactionSelectionResult BLOCK_SELECTION_TIMEOUT = + new TransactionSelectionResult(Status.BLOCK_SELECTION_TIMEOUT); + ; + /** * The transaction has not been selected since too large and the occupancy of the block is enough * to stop the selection. From b408b641af9b228e15083324a0a9dc19f2f2f098 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 10 Oct 2023 16:12:25 +0200 Subject: [PATCH 02/24] Fix null pointer exception Signed-off-by: Fabio Di Fabio --- .../org/hyperledger/besu/cli/BesuCommand.java | 22 ++++++------ .../cli/options/stable/MiningOptions.java | 36 ++++++++++++------- 2 files changed, 34 insertions(+), 24 deletions(-) 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 87413babfcd..0d22f801c9f 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -1206,12 +1206,13 @@ static class PermissionsOptionGroup { arity = "*", split = ",") private final Map requiredBlocks = new HashMap<>(); - - @Option( - names = {"--target-gas-limit"}, - description = - "Sets target gas limit per block. If set, each block's gas limit will approach this setting over time if the current gas limit is different.") - private final Long targetGasLimit = null; + // + // @Option( + // names = {"--target-gas-limit"}, + // description = + // "Sets target gas limit per block. If set, each block's gas limit will approach this + // setting over time if the current gas limit is different.") + // private final Long targetGasLimit = null; @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings. @Option( @@ -2137,14 +2138,13 @@ private void issueOptionWarnings() { } private void configure() throws Exception { + miningParameters = buildMininingParameters(); checkPortClash(); checkIfRequiredPortsAreAvailable(); syncMode = getDefaultSyncModeIfNotSet(); ethNetworkConfig = updateNetworkConfig(network); - miningParameters = buildMininingParameters(); - jsonRpcConfiguration = jsonRpcConfiguration( jsonRPCHttpOptionGroup.rpcHttpPort, jsonRPCHttpOptionGroup.rpcHttpApis, hostsAllowlist); @@ -2292,9 +2292,9 @@ public BesuControllerBuilder getControllerBuilder() { new PrunerConfiguration(pruningBlockConfirmations, pruningBlocksRetained)) .genesisConfigOverrides(genesisConfigOverrides) .gasLimitCalculator( - Optional.ofNullable(targetGasLimit) - .map(z -> new FrontierTargetingGasLimitCalculator()) - .orElse(GasLimitCalculator.constant())) + miningParameters.getDynamic().getTargetGasLimit().isPresent() + ? new FrontierTargetingGasLimitCalculator() + : GasLimitCalculator.constant()) .requiredBlocks(requiredBlocks) .reorgLoggingThreshold(reorgLoggingThreshold) .evmConfiguration(unstableEvmOptions.toDomainObject()) diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java index d7f3320ef96..1ee477e01c3 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java @@ -159,19 +159,29 @@ public void validate( @Override public MiningParameters toDomainObject() { - return ImmutableMiningParameters.builder() - .isMiningEnabled(isMiningEnabled) - .coinbase(coinbase) - .isStratumMiningEnabled(iStratumMiningEnabled) - .stratumNetworkInterface(stratumNetworkInterface) - .stratumPort(stratumPort) - .build() - .getDynamic() - .setExtraData(extraData) - .setMinBlockOccupancyRatio(minBlockOccupancyRatio) - .setMinTransactionGasPrice(minTransactionGasPrice) - .setTargetGasLimit(targetGasLimit) - .toParameters(); + final var miningParametersBuilder = + ImmutableMiningParameters.builder() + .isMiningEnabled(isMiningEnabled) + .isStratumMiningEnabled(iStratumMiningEnabled) + .stratumNetworkInterface(stratumNetworkInterface) + .stratumPort(stratumPort); + + if (coinbase != null) { + miningParametersBuilder.coinbase(coinbase); + } + + final var dynamicParameters = + miningParametersBuilder + .build() + .getDynamic() + .setExtraData(extraData) + .setMinBlockOccupancyRatio(minBlockOccupancyRatio) + .setMinTransactionGasPrice(minTransactionGasPrice); + + if (targetGasLimit != null) { + dynamicParameters.setTargetGasLimit(targetGasLimit); + } + return dynamicParameters.toParameters(); } @Override From da79e092608a57f6a0719df51bb4f7bea26e144f Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 10 Oct 2023 17:16:32 +0200 Subject: [PATCH 03/24] fix another null pointer exception Signed-off-by: Fabio Di Fabio --- besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java | 3 ++- .../besu/cli/subcommands/blocks/BlocksSubCommandTest.java | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) 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 0d22f801c9f..bbbc9a4916b 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -2292,7 +2292,8 @@ public BesuControllerBuilder getControllerBuilder() { new PrunerConfiguration(pruningBlockConfirmations, pruningBlocksRetained)) .genesisConfigOverrides(genesisConfigOverrides) .gasLimitCalculator( - miningParameters.getDynamic().getTargetGasLimit().isPresent() + miningParameters != null + && miningParameters.getDynamic().getTargetGasLimit().isPresent() ? new FrontierTargetingGasLimitCalculator() : GasLimitCalculator.constant()) .requiredBlocks(requiredBlocks) diff --git a/besu/src/test/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommandTest.java b/besu/src/test/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommandTest.java index 6a0b5592d27..5c62076e692 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommandTest.java @@ -174,7 +174,8 @@ public void callingBlockImportSubCommandWithJSONAndSkipPOWFails() { @Test public void callingBlockImportSubCommandHelpMustDisplayUsage() { parseCommand(BLOCK_SUBCOMMAND_NAME, BLOCK_IMPORT_SUBCOMMAND_NAME, "--help"); - assertThat(commandOutput.toString(UTF_8)).isEqualTo(EXPECTED_BLOCK_IMPORT_USAGE); + assertThat(commandOutput.toString(UTF_8)) + .isEqualToNormalizingNewlines(EXPECTED_BLOCK_IMPORT_USAGE); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } From 7684d7edef24951700013d3097c4d78ef5c9f6df Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 10 Oct 2023 19:52:06 +0200 Subject: [PATCH 04/24] uncomment code Signed-off-by: Fabio Di Fabio --- .../org/hyperledger/besu/cli/BesuCommand.java | 50 +++++++++---------- .../MergeBesuControllerBuilderTest.java | 7 ++- 2 files changed, 31 insertions(+), 26 deletions(-) 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 bbbc9a4916b..61aa92b6c9d 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -1489,6 +1489,7 @@ public void run() { // Need to create vertx after cmdline has been parsed, such that metricsSystem is configurable vertx = createVertx(createVertxOptions(metricsSystem.get())); + miningParameters = buildMininingParameters(); validateOptions(); configure(); @@ -2076,30 +2077,30 @@ private void issueOptionWarnings() { "--p2p-port", "--remote-connections-max-percentage")); - // // Check that block producer options work - // if (!isMergeEnabled() && getActualGenesisConfigOptions().isEthHash()) { - // CommandLineUtils.checkOptionDependencies( - // logger, - // commandLine, - // "--miner-enabled", - // !minerOptionGroup.isMiningEnabled, - // asList( - // "--miner-coinbase", - // "--min-gas-price", - // "--min-block-occupancy-ratio", - // "--miner-extra-data")); - // - // // Check that mining options are able to work - // CommandLineUtils.checkOptionDependencies( - // logger, - // commandLine, - // "--miner-enabled", - // !minerOptionGroup.isMiningEnabled, - // asList( - // "--miner-stratum-enabled", - // "--Xminer-remote-sealers-limit", - // "--Xminer-remote-sealers-hashrate-ttl")); - // } + // Check that block producer options work + if (!isMergeEnabled() && getActualGenesisConfigOptions().isEthHash()) { + CommandLineUtils.checkOptionDependencies( + logger, + commandLine, + "--miner-enabled", + !miningParameters.isMiningEnabled(), + asList( + "--miner-coinbase", + "--min-gas-price", + "--min-block-occupancy-ratio", + "--miner-extra-data")); + + // Check that mining options are able to work + CommandLineUtils.checkOptionDependencies( + logger, + commandLine, + "--miner-enabled", + !miningParameters.isMiningEnabled(), + asList( + "--miner-stratum-enabled", + "--Xminer-remote-sealers-limit", + "--Xminer-remote-sealers-hashrate-ttl")); + } CommandLineUtils.failIfOptionDoesntMeetRequirement( commandLine, @@ -2138,7 +2139,6 @@ private void issueOptionWarnings() { } private void configure() throws Exception { - miningParameters = buildMininingParameters(); checkPortClash(); checkIfRequiredPortsAreAvailable(); syncMode = getDefaultSyncModeIfNotSet(); diff --git a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java index b1f59554af3..275edcf64f7 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java @@ -75,6 +75,7 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; import org.junit.runner.RunWith; +import org.mockito.Answers; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; @@ -89,7 +90,10 @@ public class MergeBesuControllerBuilderTest { @Mock SynchronizerConfiguration synchronizerConfiguration; @Mock EthProtocolConfiguration ethProtocolConfiguration; @Mock CheckpointConfigOptions checkpointConfigOptions; - @Mock MiningParameters miningParameters; + + @Mock(answer = Answers.RETURNS_DEEP_STUBS) + MiningParameters miningParameters; + @Mock PrivacyParameters privacyParameters; @Mock Clock clock; @Mock StorageProvider storageProvider; @@ -143,6 +147,7 @@ public void setup() { when(worldStatePreimageStorage.updater()) .thenReturn(mock(WorldStatePreimageStorage.Updater.class)); when(worldStateStorage.updater()).thenReturn(mock(WorldStateStorage.Updater.class)); + when(miningParameters.getDynamic().getTargetGasLimit()).thenReturn(OptionalLong.empty()); besuControllerBuilder = visitWithMockConfigs(new MergeBesuControllerBuilder()); } From 78741da750a5d5ffa2faa358b6ae5b33a5df5bad Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Wed, 11 Oct 2023 17:55:19 +0200 Subject: [PATCH 05/24] Move miner options tests Signed-off-by: Fabio Di Fabio --- .../org/hyperledger/besu/cli/BesuCommand.java | 93 ++-- .../cli/options/stable/MiningOptions.java | 132 ++++- .../hyperledger/besu/cli/BesuCommandTest.java | 381 +------------ .../besu/cli/CommandTestAbstract.java | 39 ++ .../cli/options/AbstractCLIOptionsTest.java | 34 ++ .../cli/options/stable/MiningOptionsTest.java | 503 ++++++++++++++++++ 6 files changed, 751 insertions(+), 431 deletions(-) create mode 100644 besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java 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 61aa92b6c9d..fce760dc3f0 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -56,6 +56,7 @@ import org.hyperledger.besu.cli.options.stable.DataStorageOptions; import org.hyperledger.besu.cli.options.stable.EthstatsOptions; import org.hyperledger.besu.cli.options.stable.LoggingLevelOption; +import org.hyperledger.besu.cli.options.stable.MiningOptions; import org.hyperledger.besu.cli.options.stable.NodePrivateKeyFileOption; import org.hyperledger.besu.cli.options.stable.P2PTLSConfigOptions; import org.hyperledger.besu.cli.options.stable.TransactionPoolOptions; @@ -65,7 +66,6 @@ import org.hyperledger.besu.cli.options.unstable.EvmOptions; import org.hyperledger.besu.cli.options.unstable.IpcOptions; import org.hyperledger.besu.cli.options.unstable.MetricsCLIOptions; -import org.hyperledger.besu.cli.options.unstable.MiningOptions; import org.hyperledger.besu.cli.options.unstable.NatOptions; import org.hyperledger.besu.cli.options.unstable.NativeLibraryOptions; import org.hyperledger.besu.cli.options.unstable.NetworkingOptions; @@ -287,7 +287,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable { unstableTransactionPoolOptions = org.hyperledger.besu.cli.options.unstable.TransactionPoolOptions.create(); private final DnsOptions unstableDnsOptions = DnsOptions.create(); - private final MiningOptions unstableMiningOptions = MiningOptions.create(); +// private final MiningOptions unstableMiningOptions = MiningOptions.create(); private final NatOptions unstableNatOptions = NatOptions.create(); private final NativeLibraryOptions unstableNativeLibraryOptions = NativeLibraryOptions.create(); private final RPCOptions unstableRPCOptions = RPCOptions.create(); @@ -308,8 +308,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable { stableTransactionPoolOptions = TransactionPoolOptions.create(); @CommandLine.ArgGroup(validate = false, heading = "@|bold Miner Options|@%n") - final org.hyperledger.besu.cli.options.stable.MiningOptions stableMiningOptions = - org.hyperledger.besu.cli.options.stable.MiningOptions.create(); + final MiningOptions miningOptions = MiningOptions.create(); private final RunnerBuilder runnerBuilder; private final BesuController.Builder controllerBuilderFactory; @@ -1489,7 +1488,7 @@ public void run() { // Need to create vertx after cmdline has been parsed, such that metricsSystem is configurable vertx = createVertx(createVertxOptions(metricsSystem.get())); - miningParameters = buildMininingParameters(); + miningParameters = buildMiningParameters(); validateOptions(); configure(); @@ -1587,7 +1586,7 @@ private void handleUnstableOptions() { .put("Privacy Plugin Configuration", unstablePrivacyPluginOptions) .put("Synchronizer", unstableSynchronizerOptions) .put("TransactionPool", unstableTransactionPoolOptions) - .put("Mining", unstableMiningOptions) +// .put("Mining", unstableMiningOptions) .put("Native Library", unstableNativeLibraryOptions) .put("EVM Options", unstableEvmOptions) .put("IPC Options", unstableIpcOptions) @@ -1872,9 +1871,9 @@ private void validateRequiredOptions() { }); } - @SuppressWarnings("ConstantConditions") +// @SuppressWarnings("ConstantConditions") private void validateMiningParams() { - stableMiningOptions.validate( + miningOptions.validate( commandLine, logger, isMergeEnabled(), getActualGenesisConfigOptions().isEthHash()); // if (Boolean.TRUE.equals(minerOptionGroup.isMiningEnabled) // && minerOptionGroup.coinbase == null) { @@ -1892,19 +1891,19 @@ private void validateMiningParams() { // (remove --miner-stratum-enabled) " // + "or specify mining is enabled (--miner-enabled)"); // } - if (unstableMiningOptions.getPosBlockCreationMaxTime() <= 0 - || unstableMiningOptions.getPosBlockCreationMaxTime() - > MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { - throw new ParameterException( - this.commandLine, "--Xpos-block-creation-max-time must be positive and ≤ 12000"); - } - - if (unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() <= 0 - || unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() > 2000) { - throw new ParameterException( - this.commandLine, - "--Xpos-block-creation-repetition-min-duration must be positive and ≤ 2000"); - } +// if (unstableMiningOptions.getPosBlockCreationMaxTime() <= 0 +// || unstableMiningOptions.getPosBlockCreationMaxTime() +// > MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { +// throw new ParameterException( +// this.commandLine, "--Xpos-block-creation-max-time must be positive and ≤ 12000"); +// } +// +// if (unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() <= 0 +// || unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() > 2000) { +// throw new ParameterException( +// this.commandLine, +// "--Xpos-block-creation-repetition-min-duration must be positive and ≤ 2000"); +// } } /** @@ -2077,30 +2076,30 @@ private void issueOptionWarnings() { "--p2p-port", "--remote-connections-max-percentage")); - // Check that block producer options work - if (!isMergeEnabled() && getActualGenesisConfigOptions().isEthHash()) { - CommandLineUtils.checkOptionDependencies( - logger, - commandLine, - "--miner-enabled", - !miningParameters.isMiningEnabled(), - asList( - "--miner-coinbase", - "--min-gas-price", - "--min-block-occupancy-ratio", - "--miner-extra-data")); - - // Check that mining options are able to work - CommandLineUtils.checkOptionDependencies( - logger, - commandLine, - "--miner-enabled", - !miningParameters.isMiningEnabled(), - asList( - "--miner-stratum-enabled", - "--Xminer-remote-sealers-limit", - "--Xminer-remote-sealers-hashrate-ttl")); - } +// // Check that block producer options work +// if (!isMergeEnabled() && getActualGenesisConfigOptions().isEthHash()) { +// CommandLineUtils.checkOptionDependencies( +// logger, +// commandLine, +// "--miner-enabled", +// !miningParameters.isMiningEnabled(), +// asList( +// "--miner-coinbase", +// "--min-gas-price", +// "--min-block-occupancy-ratio", +// "--miner-extra-data")); +// +// // Check that mining options are able to work +// CommandLineUtils.checkOptionDependencies( +// logger, +// commandLine, +// "--miner-enabled", +// !miningParameters.isMiningEnabled(), +// asList( +// "--miner-stratum-enabled", +// "--Xminer-remote-sealers-limit", +// "--Xminer-remote-sealers-hashrate-ttl")); +// } CommandLineUtils.failIfOptionDoesntMeetRequirement( commandLine, @@ -2959,8 +2958,8 @@ private TransactionPoolConfiguration buildTransactionPoolConfiguration() { .build(); } - private MiningParameters buildMininingParameters() { - return stableMiningOptions.toDomainObject(); + private MiningParameters buildMiningParameters() { + return miningOptions.toDomainObject(); } private boolean isPruningEnabled() { diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java index 1ee477e01c3..3ba7daedea2 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java @@ -15,6 +15,12 @@ package org.hyperledger.besu.cli.options.stable; import static java.util.Arrays.asList; +import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_MAX_OMMERS_DEPTH; +import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; +import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; +import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POW_JOB_TTL; +import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_LIMIT; +import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_TTL; import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_EXTRA_DATA; import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE; @@ -32,6 +38,7 @@ import org.slf4j.Logger; import picocli.CommandLine; import picocli.CommandLine.Option; +import picocli.CommandLine.ParameterException; /** The Mining CLI options. */ public class MiningOptions implements CLIOptions { @@ -39,12 +46,12 @@ public class MiningOptions implements CLIOptions { @Option( names = {"--miner-enabled"}, description = "Set if node will perform mining (default: ${DEFAULT-VALUE})") - private final Boolean isMiningEnabled = false; + private Boolean isMiningEnabled = false; @Option( names = {"--miner-stratum-enabled"}, description = "Set if node will perform Stratum mining (default: ${DEFAULT-VALUE})") - private final Boolean iStratumMiningEnabled = false; + private Boolean iStratumMiningEnabled = false; @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings. @Option( @@ -55,7 +62,7 @@ public class MiningOptions implements CLIOptions { @Option( names = {"--miner-stratum-port"}, description = "Stratum port binding (default: ${DEFAULT-VALUE})") - private final Integer stratumPort = 8008; + private Integer stratumPort = 8008; @Option( names = {"--miner-coinbase"}, @@ -63,7 +70,7 @@ public class MiningOptions implements CLIOptions { "Account to which mining rewards are paid. You must specify a valid coinbase if " + "mining is enabled using --miner-enabled option", arity = "1") - private final Address coinbase = null; + private Address coinbase = null; @Option( names = {"--miner-extra-data"}, @@ -71,13 +78,13 @@ public class MiningOptions implements CLIOptions { "A hex string representing the (32) bytes to be included in the extra data " + "field of a mined block (default: ${DEFAULT-VALUE})", arity = "1") - private final Bytes extraData = DEFAULT_EXTRA_DATA; + private Bytes extraData = DEFAULT_EXTRA_DATA; @Option( names = {"--min-block-occupancy-ratio"}, description = "Minimum occupancy ratio for a mined block (default: ${DEFAULT-VALUE})", arity = "1") - private final Double minBlockOccupancyRatio = DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; + private Double minBlockOccupancyRatio = DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; @Option( names = {"--min-gas-price"}, @@ -85,15 +92,73 @@ public class MiningOptions implements CLIOptions { "Minimum price (in Wei) offered by a transaction for it to be included in a mined " + "block (default: ${DEFAULT-VALUE})", arity = "1") - private final Wei minTransactionGasPrice = DEFAULT_MIN_TRANSACTION_GAS_PRICE; + private Wei minTransactionGasPrice = DEFAULT_MIN_TRANSACTION_GAS_PRICE; @Option( names = {"--target-gas-limit"}, description = "Sets target gas limit per block. If set, each block's gas limit will approach this setting over time if the current gas limit is different.") - private final Long targetGasLimit = null; + private Long targetGasLimit = null; - private MiningOptions() {} + @CommandLine.ArgGroup( + validate = false) + private final Unstable unstableOptions = new Unstable(); + + static class Unstable { + @CommandLine.Option( + hidden = true, + names = {"--Xminer-remote-sealers-limit"}, + description = + "Limits the number of remote sealers that can submit their hashrates (default: ${DEFAULT-VALUE})") + private Integer remoteSealersLimit = DEFAULT_REMOTE_SEALERS_LIMIT; + + @CommandLine.Option( + hidden = true, + names = {"--Xminer-remote-sealers-hashrate-ttl"}, + description = + "Specifies the lifetime of each entry in the cache. An entry will be automatically deleted if no update has been received before the deadline (default: ${DEFAULT-VALUE} minutes)") + private Long remoteSealersTimeToLive = DEFAULT_REMOTE_SEALERS_TTL; + + @CommandLine.Option( + hidden = true, + names = {"--Xminer-pow-job-ttl"}, + description = + "Specifies the time PoW jobs are kept in cache and will accept a solution from miners (default: ${DEFAULT-VALUE} milliseconds)") + private Long powJobTimeToLive = DEFAULT_POW_JOB_TTL; + + @CommandLine.Option( + hidden = true, + names = {"--Xmax-ommers-depth"}, + description = + "Specifies the depth of ommer blocks to accept when receiving solutions (default: ${DEFAULT-VALUE})") + private Integer maxOmmersDepth = DEFAULT_MAX_OMMERS_DEPTH; + + @CommandLine.Option( + hidden = true, + names = {"--Xminer-stratum-extranonce"}, + description = "Extranonce for Stratum network miners (default: ${DEFAULT-VALUE})") + private String stratumExtranonce = "080c"; + + @CommandLine.Option( + hidden = true, + names = {"--Xpos-block-creation-max-time"}, + description = + "Specifies the maximum time, in milliseconds, a PoS block creation jobs is allowed to run. Must be positive and ≤ 12000 (default: ${DEFAULT-VALUE} milliseconds)") + private Long posBlockCreationMaxTime = DEFAULT_POS_BLOCK_CREATION_MAX_TIME; + + @CommandLine.Option( + hidden = true, + names = {"--Xpos-block-creation-repetition-min-duration"}, + description = + "If a PoS block creation repetition takes less than this duration, in milliseconds," + + " then it waits before next repetition. Must be positive and ≤ 2000 (default: ${DEFAULT-VALUE} milliseconds)") + private Long posBlockCreationRepetitionMinDuration = + DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; + } + + private MiningOptions() { + + } /** * Create mining options. @@ -119,13 +184,13 @@ public void validate( final boolean isMergeEnabled, final boolean isEthHash) { if (Boolean.TRUE.equals(isMiningEnabled) && coinbase == null) { - throw new CommandLine.ParameterException( + throw new ParameterException( commandLine, "Unable to mine without a valid coinbase. Either disable mining (remove --miner-enabled) " + "or specify the beneficiary of mining (via --miner-coinbase
)"); } if (Boolean.FALSE.equals(isMiningEnabled) && Boolean.TRUE.equals(iStratumMiningEnabled)) { - throw new CommandLine.ParameterException( + throw new ParameterException( commandLine, "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) " + "or specify mining is enabled (--miner-enabled)"); @@ -155,6 +220,42 @@ public void validate( "--Xminer-remote-sealers-limit", "--Xminer-remote-sealers-hashrate-ttl")); } + + if (unstableOptions.posBlockCreationMaxTime <= 0 + || unstableOptions.posBlockCreationMaxTime + > MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { + throw new ParameterException( + commandLine, "--Xpos-block-creation-max-time must be positive and ≤ 12000"); + } + + if (unstableOptions.posBlockCreationRepetitionMinDuration <= 0 + || unstableOptions.posBlockCreationRepetitionMinDuration > 2000) { + throw new ParameterException( + commandLine, + "--Xpos-block-creation-repetition-min-duration must be positive and ≤ 2000"); + } + } + + static MiningOptions fromConfig(final MiningParameters miningParameters) { + final MiningOptions miningOptions = MiningOptions.create(); + miningOptions.isMiningEnabled = miningParameters.isMiningEnabled(); + miningOptions.iStratumMiningEnabled = miningParameters.isStratumMiningEnabled(); + miningOptions.stratumNetworkInterface = miningParameters.getStratumNetworkInterface(); + miningOptions.stratumPort = miningParameters.getStratumPort(); + miningOptions.extraData = miningParameters.getDynamic().getExtraData(); + miningOptions.minTransactionGasPrice = miningParameters.getDynamic().getMinTransactionGasPrice(); + miningOptions.minBlockOccupancyRatio = miningParameters.getDynamic().getMinBlockOccupancyRatio(); + miningOptions.unstableOptions.remoteSealersLimit = miningParameters.getRemoteSealersLimit(); + miningOptions.unstableOptions.remoteSealersTimeToLive = miningParameters.getRemoteSealersTimeToLive(); + miningOptions.unstableOptions.powJobTimeToLive = miningParameters.getPowJobTimeToLive(); + miningOptions.unstableOptions.maxOmmersDepth = miningParameters.getMaxOmmerDepth(); + miningOptions.unstableOptions.stratumExtranonce = miningParameters.getStratumExtranonce(); + miningOptions.unstableOptions.posBlockCreationMaxTime = miningParameters.getPosBlockCreationMaxTime(); + miningOptions.unstableOptions.posBlockCreationRepetitionMinDuration = miningParameters.getPosBlockCreationRepetitionMinDuration(); + + miningParameters.getCoinbase().ifPresent(coinbase -> miningOptions.coinbase = coinbase); + miningParameters.getDynamic().getTargetGasLimit().ifPresent(tgl -> miningOptions.targetGasLimit = tgl); + return miningOptions; } @Override @@ -164,7 +265,14 @@ public MiningParameters toDomainObject() { .isMiningEnabled(isMiningEnabled) .isStratumMiningEnabled(iStratumMiningEnabled) .stratumNetworkInterface(stratumNetworkInterface) - .stratumPort(stratumPort); + .stratumPort(stratumPort) + .remoteSealersLimit(unstableOptions.remoteSealersLimit) + .remoteSealersTimeToLive(unstableOptions.remoteSealersTimeToLive) + .powJobTimeToLive(unstableOptions.powJobTimeToLive) + .maxOmmerDepth(unstableOptions.maxOmmersDepth) + .stratumExtranonce(unstableOptions.stratumExtranonce) + .posBlockCreationMaxTime(unstableOptions.posBlockCreationMaxTime) + .posBlockCreationRepetitionMinDuration(unstableOptions.posBlockCreationRepetitionMinDuration); if (coinbase != null) { miningParametersBuilder.coinbase(coinbase); 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 787e9e60733..a10806eb3d5 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -35,7 +35,7 @@ import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.NET; import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.PERM; import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.WEB3; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; +//import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.GOERLI_BOOTSTRAP_NODES; import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.GOERLI_DISCOVERY_URL; import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.MAINNET_BOOTSTRAP_NODES; @@ -48,7 +48,6 @@ import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNotNull; import static org.mockito.Mockito.atLeast; -import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.times; @@ -162,20 +161,6 @@ public class BesuCommandTest extends CommandTestAbstract { (new JsonObject()).put("config", new JsonObject().put("ecCurve", "secp256k1")); private static final String ENCLAVE_PUBLIC_KEY_PATH = BesuCommand.class.getResource("/orion_publickey.pub").getPath(); - private static final JsonObject VALID_GENESIS_QBFT_POST_LONDON = - (new JsonObject()) - .put( - "config", - new JsonObject() - .put("londonBlock", 0) - .put("qbft", new JsonObject().put("blockperiodseconds", 5))); - private static final JsonObject VALID_GENESIS_IBFT2_POST_LONDON = - (new JsonObject()) - .put( - "config", - new JsonObject() - .put("londonBlock", 0) - .put("ibft2", new JsonObject().put("blockperiodseconds", 5))); private static final String[] VALID_ENODE_STRINGS = { "enode://" + VALID_NODE_ID + "@192.168.0.1:4567", @@ -927,14 +912,14 @@ public void envVariableOverridesValueFromConfigFile() { MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE) .setExtraData(MiningParameters.Dynamic.DEFAULT_EXTRA_DATA) .toParameters()); - - // new MiningParameters.Builder() - // .coinbase(Address.fromHexString(expectedCoinbase)) - // - // .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) - // .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) - // .miningEnabled(false) - // .build()); +// +// new MiningParameters.Builder() +// .coinbase(Address.fromHexString(expectedCoinbase)) +// +// .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) +// .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) +// .miningEnabled(false) +// .build()); } @Test @@ -3677,261 +3662,6 @@ public void metricsAndMetricsPushMustNotBeUsedTogether() { .startsWith("--metrics-enabled option and --metrics-push-enabled option can't be used"); } - @Test - public void besuDoesNotStartInMiningModeIfCoinbaseNotSet() { - parseCommand("--miner-enabled"); - - Mockito.verifyNoInteractions(mockControllerBuilder); - } - - @Test - public void miningIsEnabledWhenSpecified() throws Exception { - final String coinbaseStr = String.format("%040x", 1); - parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr); - - final ArgumentCaptor miningArg = - ArgumentCaptor.forClass(MiningParameters.class); - - verify(mockControllerBuilder).miningParameters(miningArg.capture()); - verify(mockControllerBuilder).build(); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); - assertThat(miningArg.getValue().getCoinbase()) - .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); - } - - @Test - public void stratumMiningIsEnabledWhenSpecified() throws Exception { - final String coinbaseStr = String.format("%040x", 1); - parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr, "--miner-stratum-enabled"); - - final ArgumentCaptor miningArg = - ArgumentCaptor.forClass(MiningParameters.class); - - verify(mockControllerBuilder).miningParameters(miningArg.capture()); - verify(mockControllerBuilder).build(); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); - assertThat(miningArg.getValue().getCoinbase()) - .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); - assertThat(miningArg.getValue().isStratumMiningEnabled()).isTrue(); - } - - @Test - public void stratumMiningOptionsRequiresServiceToBeEnabled() { - - parseCommand("--network", "dev", "--miner-stratum-enabled"); - - verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)) - .startsWith( - "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); - } - - @Test - public void stratumMiningOptionsRequiresServiceToBeEnabledToml() throws IOException { - final Path toml = createTempFile("toml", "miner-stratum-enabled=true\n"); - - parseCommand("--network", "dev", "--config-file", toml.toString()); - - verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)) - .startsWith( - "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); - } - - @Test - public void blockProducingOptionsWarnsMinerShouldBeEnabled() { - - final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); - parseCommand( - "--network", - "dev", - "--miner-coinbase", - requestedCoinbase.toString(), - "--min-gas-price", - "42", - "--miner-extra-data", - "0x1122334455667788990011223344556677889900112233445566778899001122"); - - verifyOptionsConstraintLoggerCall( - "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - } - - @Test - public void blockProducingOptionsWarnsMinerShouldBeEnabledToml() throws IOException { - - final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); - - final Path toml = - createTempFile( - "toml", - "network=\"dev\"\n" - + "miner-coinbase=\"" - + requestedCoinbase - + "\"\n" - + "min-gas-price=42\n" - + "miner-extra-data=\"0x1122334455667788990011223344556677889900112233445566778899001122\"\n"); - - parseCommand("--config-file", toml.toString()); - - verifyOptionsConstraintLoggerCall( - "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - } - - @Test - public void blockProducingOptionsDoNotWarnWhenPoA() throws IOException { - - final Path genesisFileQBFT = createFakeGenesisFile(VALID_GENESIS_QBFT_POST_LONDON); - parseCommand( - "--genesis-file", - genesisFileQBFT.toString(), - "--min-gas-price", - "42", - "--miner-extra-data", - "0x1122334455667788990011223344556677889900112233445566778899001122"); - - verify(mockLogger, atMost(0)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - - final Path genesisFileIBFT2 = createFakeGenesisFile(VALID_GENESIS_IBFT2_POST_LONDON); - parseCommand( - "--genesis-file", - genesisFileIBFT2.toString(), - "--min-gas-price", - "42", - "--miner-extra-data", - "0x1122334455667788990011223344556677889900112233445566778899001122"); - - verify(mockLogger, atMost(0)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - } - - @Test - public void blockProducingOptionsDoNotWarnWhenMergeEnabled() { - - final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); - // TODO: once we have mainnet TTD, we can remove the TTD override parameter here - // https://github.com/hyperledger/besu/issues/3874 - parseCommand( - "--override-genesis-config", - "terminalTotalDifficulty=1337", - "--miner-coinbase", - requestedCoinbase.toString(), - "--min-gas-price", - "42", - "--miner-extra-data", - "0x1122334455667788990011223344556677889900112233445566778899001122"); - - verify(mockLogger, atMost(0)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - } - - @Test - public void minGasPriceRequiresMainOption() { - parseCommand("--min-gas-price", "0", "--network", "dev"); - - verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - } - - @Test - public void minGasPriceRequiresMainOptionToml() throws IOException { - final Path toml = createTempFile("toml", "min-gas-price=0\nnetwork=\"dev\"\n"); - - parseCommand("--config-file", toml.toString()); - - verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - } - - @Test - public void minGasPriceDoesNotRequireMainOptionWhenPoA() throws IOException { - final Path genesisFileQBFT = createFakeGenesisFile(VALID_GENESIS_QBFT_POST_LONDON); - parseCommand("--genesis-file", genesisFileQBFT.toString(), "--min-gas-price", "0"); - - verify(mockLogger, atMost(0)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - - final Path genesisFileIBFT2 = createFakeGenesisFile(VALID_GENESIS_IBFT2_POST_LONDON); - parseCommand("--genesis-file", genesisFileIBFT2.toString(), "--min-gas-price", "0"); - - verify(mockLogger, atMost(0)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - } - - @Test - public void miningParametersAreCaptured() { - final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); - final String extraDataString = - "0x1122334455667788990011223344556677889900112233445566778899001122"; - parseCommand( - "--miner-enabled", - "--miner-coinbase=" + requestedCoinbase.toString(), - "--min-gas-price=15", - "--miner-extra-data=" + extraDataString); - - final ArgumentCaptor miningArg = - ArgumentCaptor.forClass(MiningParameters.class); - - verify(mockControllerBuilder).miningParameters(miningArg.capture()); - verify(mockControllerBuilder).build(); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - assertThat(miningArg.getValue().getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); - assertThat(miningArg.getValue().getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); - assertThat(miningArg.getValue().getDynamic().getExtraData()) - .isEqualTo(Bytes.fromHexString(extraDataString)); - } @Test public void colorCanBeEnabledOrDisabledExplicitly() { @@ -4497,31 +4227,6 @@ public void canNotUseFlexiblePrivacyWhenPrivacyPluginEnabled() { "No Payload Provider has been provided. You must register one when enabling privacy plugin!"); } - private Path createFakeGenesisFile(final JsonObject jsonGenesis) throws IOException { - final Path genesisFile = Files.createTempFile("genesisFile", ""); - Files.write(genesisFile, encodeJsonGenesis(jsonGenesis).getBytes(UTF_8)); - genesisFile.toFile().deleteOnExit(); - return genesisFile; - } - - private Path createTempFile(final String filename, final String contents) throws IOException { - final Path file = Files.createTempFile(filename, ""); - Files.write(file, contents.getBytes(UTF_8)); - file.toFile().deleteOnExit(); - return file; - } - - private Path createTempFile(final String filename, final byte[] contents) throws IOException { - final Path file = Files.createTempFile(filename, ""); - Files.write(file, contents); - file.toFile().deleteOnExit(); - return file; - } - - private String encodeJsonGenesis(final JsonObject jsonGenesis) { - return jsonGenesis.encodePrettily(); - } - private static String escapeTomlString(final String s) { return StringEscapeUtils.escapeJava(s); } @@ -4645,43 +4350,6 @@ public void tomlThatHasInvalidOptions() throws IOException { .contains("Unknown options in TOML configuration file: invalid_option, invalid_option2"); } - @Test - public void targetGasLimitIsEnabledWhenSpecified() { - parseCommand("--target-gas-limit=10000000"); - - @SuppressWarnings("unchecked") - final ArgumentCaptor miningParametersArgumentCaptor = - ArgumentCaptor.forClass(MiningParameters.class); - - verify(mockControllerBuilder).miningParameters(miningParametersArgumentCaptor.capture()); - verify(mockControllerBuilder).build(); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - - assertThat( - miningParametersArgumentCaptor.getValue().getDynamic().getTargetGasLimit().getAsLong()) - .isEqualTo(10_000_000L); - } - - @Test - public void targetGasLimitIsDisabledWhenNotSpecified() { - parseCommand(); - - @SuppressWarnings("unchecked") - final ArgumentCaptor gasLimitCalculatorArgumentCaptor = - ArgumentCaptor.forClass(GasLimitCalculator.class); - - verify(mockControllerBuilder).gasLimitCalculator(gasLimitCalculatorArgumentCaptor.capture()); - verify(mockControllerBuilder).build(); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - - assertThat(gasLimitCalculatorArgumentCaptor.getValue()) - .isEqualTo(GasLimitCalculator.constant()); - } - @Test public void requiredBlocksSetWhenSpecified() { final long blockNumber = 8675309L; @@ -5302,37 +4970,6 @@ public void logWarnIfFastSyncMinPeersUsedWithFullSync() { .contains("--fast-sync-min-peers can't be used with FULL sync-mode"); } - @Test - public void posBlockCreationMaxTimeDefaultValue() { - parseCommand(); - assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(DEFAULT_POS_BLOCK_CREATION_MAX_TIME); - } - - @Test - public void posBlockCreationMaxTimeOption() { - parseCommand("--Xpos-block-creation-max-time", "7000"); - assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(7000L); - } - - private long getPosBlockCreationMaxTimeValue() { - final ArgumentCaptor miningArg = - ArgumentCaptor.forClass(MiningParameters.class); - - verify(mockControllerBuilder).miningParameters(miningArg.capture()); - verify(mockControllerBuilder).build(); - - assertThat(commandOutput.toString(UTF_8)).isEmpty(); - assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - return miningArg.getValue().getPosBlockCreationMaxTime(); - } - - @Test - public void posBlockCreationMaxTimeOutOfAllowedRange() { - parseCommand("--Xpos-block-creation-max-time", "17000"); - assertThat(commandErrorOutput.toString(UTF_8)) - .contains("--Xpos-block-creation-max-time must be positive and ≤ 12000"); - } - @Test public void portInUseReportsError() throws IOException { final ServerSocket serverSocket = new ServerSocket(8545); 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 126052df0b9..f946496abdc 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java @@ -25,6 +25,7 @@ import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; +import io.vertx.core.json.JsonObject; import org.hyperledger.besu.Runner; import org.hyperledger.besu.RunnerBuilder; import org.hyperledger.besu.chainexport.RlpBlockExporter; @@ -32,6 +33,7 @@ import org.hyperledger.besu.chainimport.RlpBlockImporter; import org.hyperledger.besu.cli.config.EthNetworkConfig; import org.hyperledger.besu.cli.options.stable.EthstatsOptions; +import org.hyperledger.besu.cli.options.stable.MiningOptions; import org.hyperledger.besu.cli.options.unstable.EthProtocolOptions; import org.hyperledger.besu.cli.options.unstable.MetricsCLIOptions; import org.hyperledger.besu.cli.options.unstable.NetworkingOptions; @@ -126,6 +128,20 @@ @RunWith(MockitoJUnitRunner.class) public abstract class CommandTestAbstract { private static final Logger TEST_LOGGER = LoggerFactory.getLogger(CommandTestAbstract.class); + protected static final JsonObject VALID_GENESIS_QBFT_POST_LONDON = + (new JsonObject()) + .put( + "config", + new JsonObject() + .put("londonBlock", 0) + .put("qbft", new JsonObject().put("blockperiodseconds", 5))); + protected static final JsonObject VALID_GENESIS_IBFT2_POST_LONDON = + (new JsonObject()) + .put( + "config", + new JsonObject() + .put("londonBlock", 0) + .put("ibft2", new JsonObject().put("blockperiodseconds", 5))); protected final PrintStream originalOut = System.out; protected final PrintStream originalErr = System.err; protected final ByteArrayOutputStream commandOutput = new ByteArrayOutputStream(); @@ -458,6 +474,25 @@ private TestBesuCommand getTestBesuCommand(final TestType testType) { } } + protected Path createTempFile(final String filename, final byte[] contents) throws IOException { + final Path file = Files.createTempFile(filename, ""); + Files.write(file, contents); + file.toFile().deleteOnExit(); + return file; + } + + protected Path createFakeGenesisFile(final JsonObject jsonGenesis) throws IOException { + return createTempFile("genesisFile", encodeJsonGenesis(jsonGenesis).getBytes(UTF_8)); + } + + protected String encodeJsonGenesis(final JsonObject jsonGenesis) { + return jsonGenesis.encodePrettily(); + } + + protected Path createTempFile(final String filename, final String contents) throws IOException { + return createTempFile(filename, contents.getBytes(UTF_8)); + } + @CommandLine.Command public static class TestBesuCommand extends BesuCommand { @@ -528,6 +563,10 @@ public EthProtocolOptions getEthProtocolOptions() { return stableTransactionPoolOptions; } + public MiningOptions getMiningOptions() { + return miningOptions; + } + public TransactionPoolOptions getUnstableTransactionPoolOptions() { return unstableTransactionPoolOptions; } diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/AbstractCLIOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/AbstractCLIOptionsTest.java index ef7da0c7669..4fb9d9f51ad 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/AbstractCLIOptionsTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/AbstractCLIOptionsTest.java @@ -16,9 +16,16 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; +import static org.hyperledger.besu.cli.util.CommandLineUtils.DEPENDENCY_WARNING_MSG; +import static org.mockito.Mockito.atLeast; +import static org.mockito.Mockito.verify; +import io.vertx.core.json.JsonObject; import org.hyperledger.besu.cli.CommandTestAbstract; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.function.Consumer; @@ -113,6 +120,7 @@ protected void internalTestSuccess(final Consumer assertion, final String... assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + verify(mockControllerBuilder).build(); } protected void internalTestFailure(final String errorMsg, final String... args) { @@ -121,4 +129,30 @@ protected void internalTestFailure(final String errorMsg, final String... args) assertThat(commandOutput.toString(UTF_8)).isEmpty(); assertThat(commandErrorOutput.toString(UTF_8)).contains(errorMsg); } + + /** + * Check logger calls + * + *

Here we check the calls to logger and not the result of the log line as we don't test the + * logger itself but the fact that we call it. + * + * @param dependentOptions the string representing the list of dependent options names + * @param mainOption the main option name + */ + protected void verifyOptionsConstraintLoggerCall( + final String mainOption, final String... dependentOptions) { + verify(mockLogger, atLeast(1)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()); + assertThat(stringArgumentCaptor.getAllValues().get(0)).isEqualTo(DEPENDENCY_WARNING_MSG); + + for (final String option : dependentOptions) { + assertThat(stringArgumentCaptor.getAllValues().get(1)).contains(option); + } + + assertThat(stringArgumentCaptor.getAllValues().get(2)).isEqualTo(mainOption); + } + } diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java new file mode 100644 index 00000000000..92e2a02b60c --- /dev/null +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java @@ -0,0 +1,503 @@ +/* + * Copyright Hyperledger Besu Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.cli.options.stable; + +import org.apache.tuweni.bytes.Bytes; +import org.hyperledger.besu.cli.options.AbstractCLIOptionsTest; +import org.hyperledger.besu.datatypes.Address; +import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.MiningParameters; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; + +import java.io.IOException; +import java.nio.file.Path; +import java.util.Optional; + +import static java.nio.charset.StandardCharsets.UTF_8; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; +import static org.mockito.Mockito.atMost; +import static org.mockito.Mockito.verify; + +@RunWith(MockitoJUnitRunner.class) +public class MiningOptionsTest + extends AbstractCLIOptionsTest { + + + @Test + public void besuDoesNotStartInMiningModeIfCoinbaseNotSet() { + internalTestFailure("Unable to mine without a valid coinbase. Either disable mining (remove --miner-enabled) or specify the beneficiary of mining (via --miner-coinbase

)", "--miner-enabled"); +// parseCommand("--miner-enabled"); +// +// Mockito.verifyNoInteractions(mockControllerBuilder); + } + + @Test + public void miningIsEnabledWhenSpecified() { + final String coinbaseStr = String.format("%040x", 1); +// parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr); + internalTestSuccess(miningOpts -> { + assertThat(miningOpts.isMiningEnabled()).isTrue(); + assertThat(miningOpts.getCoinbase()) + .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); + }, "--miner-enabled", "--miner-coinbase=" + coinbaseStr); +// final ArgumentCaptor miningArg = +// ArgumentCaptor.forClass(MiningParameters.class); +// +// verify(mockControllerBuilder).miningParameters(miningArg.capture()); +// verify(mockControllerBuilder).build(); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); +// assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); +// assertThat(miningArg.getValue().getCoinbase()) +// .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); + } + + @Test + public void stratumMiningIsEnabledWhenSpecified() { + final String coinbaseStr = String.format("%040x", 1); +// parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr, "--miner-stratum-enabled"); +// + internalTestSuccess(miningOpts -> { + assertThat(miningOpts.isMiningEnabled()).isTrue(); + assertThat(miningOpts.getCoinbase()) + .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); + assertThat(miningOpts.isStratumMiningEnabled()).isTrue(); + }, "--miner-enabled", "--miner-coinbase=" + coinbaseStr, "--miner-stratum-enabled"); + +// +// final ArgumentCaptor miningArg = +// ArgumentCaptor.forClass(MiningParameters.class); +// +// verify(mockControllerBuilder).miningParameters(miningArg.capture()); +// verify(mockControllerBuilder).build(); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); +// assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); +// assertThat(miningArg.getValue().getCoinbase()) +// .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); +// assertThat(miningArg.getValue().isStratumMiningEnabled()).isTrue(); + } + + @Test + public void stratumMiningOptionsRequiresServiceToBeEnabled() { +internalTestFailure("Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)", + "--network", "dev", "--miner-stratum-enabled"); +// parseCommand("--network", "dev", "--miner-stratum-enabled"); + +// verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); + +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)) +// .startsWith( +// "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); + } + + @Test + public void stratumMiningOptionsRequiresServiceToBeEnabledToml() throws IOException { + final Path toml = createTempFile("toml", "miner-stratum-enabled=true\n"); + internalTestFailure("Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)", + "--network", "dev", "--config-file", toml.toString()); +// parseCommand("--network", "dev", "--config-file", toml.toString()); +// +// verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)) +// .startsWith( +// "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); + } + + @Test + public void blockProducingOptionsWarnsMinerShouldBeEnabled() { + final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); + internalTestSuccess(miningOpts -> verifyOptionsConstraintLoggerCall( + "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"), + "--network", + "dev", + "--miner-coinbase", + requestedCoinbase.toString(), + "--min-gas-price", + "42", + "--miner-extra-data", + "0x1122334455667788990011223344556677889900112233445566778899001122" ); +// parseCommand( +// "--network", +// "dev", +// "--miner-coinbase", +// requestedCoinbase.toString(), +// "--min-gas-price", +// "42", +// "--miner-extra-data", +// "0x1122334455667788990011223344556677889900112233445566778899001122"); +// +// verifyOptionsConstraintLoggerCall( +// "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + } + + @Test + public void blockProducingOptionsWarnsMinerShouldBeEnabledToml() throws IOException { + + final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); + + final Path toml = + createTempFile( + "toml", + "network=\"dev\"\n" + + "miner-coinbase=\"" + + requestedCoinbase + + "\"\n" + + "min-gas-price=42\n" + + "miner-extra-data=\"0x1122334455667788990011223344556677889900112233445566778899001122\"\n"); + + internalTestSuccess(miningOpts -> verifyOptionsConstraintLoggerCall( + "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"), + "--config-file", toml.toString() ); + +// parseCommand("--config-file", toml.toString()); +// +// verifyOptionsConstraintLoggerCall( +// "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + } + + @Test + public void blockProducingOptionsDoNotWarnWhenPoAQBFT() throws IOException { + + final Path genesisFileQBFT = createFakeGenesisFile(VALID_GENESIS_QBFT_POST_LONDON); +// parseCommand( +// "--genesis-file", +// genesisFileQBFT.toString(), +// "--min-gas-price", +// "42", +// "--miner-extra-data", +// "0x1122334455667788990011223344556677889900112233445566778899001122"); + + internalTestSuccess(miningOpts -> verify(mockLogger, atMost(0)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()), + "--genesis-file", + genesisFileQBFT.toString(), + "--min-gas-price", + "42", + "--miner-extra-data", + "0x1122334455667788990011223344556677889900112233445566778899001122"); + } +// verify(mockLogger, atMost(0)) +// .warn( +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture()); +//// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + + @Test + public void blockProducingOptionsDoNotWarnWhenPoAIBFT2() throws IOException { + + final Path genesisFileIBFT2 = createFakeGenesisFile(VALID_GENESIS_IBFT2_POST_LONDON); + internalTestSuccess(miningOpts -> verify(mockLogger, atMost(0)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()), + "--genesis-file", + genesisFileIBFT2.toString(), + "--min-gas-price", + "42", + "--miner-extra-data", + "0x1122334455667788990011223344556677889900112233445566778899001122"); +// +// parseCommand( +// "--genesis-file", +// genesisFileIBFT2.toString(), +// "--min-gas-price", +// "42", +// "--miner-extra-data", +// "0x1122334455667788990011223344556677889900112233445566778899001122"); +// +// verify(mockLogger, atMost(0)) +// .warn( +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture()); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + } + + @Test + public void blockProducingOptionsDoNotWarnWhenMergeEnabled() { + + final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); + internalTestSuccess(miningOpt -> verify(mockLogger, atMost(0)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()), + "--miner-coinbase", + requestedCoinbase.toString(), + "--min-gas-price", + "42", + "--miner-extra-data", + "0x1122334455667788990011223344556677889900112233445566778899001122" +); +// parseCommand( +// "--miner-coinbase", +// requestedCoinbase.toString(), +// "--min-gas-price", +// "42", +// "--miner-extra-data", +// "0x1122334455667788990011223344556677889900112233445566778899001122"); +// +// verify(mockLogger, atMost(0)) +// .warn( +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture()); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + } + + @Test + public void minGasPriceRequiresMainOption() { + internalTestSuccess(miningOpt -> verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"), + "--min-gas-price", "0", "--network", "dev" + ); +// +// parseCommand("--min-gas-price", "0", "--network", "dev"); +// +// verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + } + + @Test + public void minGasPriceRequiresMainOptionToml() throws IOException { + final Path toml = createTempFile("toml", "min-gas-price=0\nnetwork=\"dev\"\n"); + internalTestSuccess(miningOpt -> verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"), + "--config-file", toml.toString() + ); +// +// parseCommand("--config-file", toml.toString()); +// +// verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + } + + @Test + public void minGasPriceDoesNotRequireMainOptionWhenPoAQBFT() throws IOException { + final Path genesisFileQBFT = createFakeGenesisFile(VALID_GENESIS_QBFT_POST_LONDON); + internalTestSuccess(miningOpt -> verify(mockLogger, atMost(0)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()), + "--genesis-file", genesisFileQBFT.toString(), "--min-gas-price", "0" + ); + } +// +// parseCommand("--genesis-file", genesisFileQBFT.toString(), "--min-gas-price", "0"); +// +// verify(mockLogger, atMost(0)) +// .warn( +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture()); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); +@Test +public void minGasPriceDoesNotRequireMainOptionWhenPoAIBFT2() throws IOException { + final Path genesisFileIBFT2 = createFakeGenesisFile(VALID_GENESIS_IBFT2_POST_LONDON); + + internalTestSuccess(miningOpt -> verify(mockLogger, atMost(0)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()), + "--genesis-file", genesisFileIBFT2.toString(), "--min-gas-price", "0" + ); +// parseCommand("--genesis-file", genesisFileIBFT2.toString(), "--min-gas-price", "0"); +// +// verify(mockLogger, atMost(0)) +// .warn( +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture(), +// stringArgumentCaptor.capture()); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + } + + @Test + public void miningParametersAreCaptured() { + final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); + final String extraDataString = + "0x1122334455667788990011223344556677889900112233445566778899001122"; + internalTestSuccess(miningParams -> { + assertThat(miningParams.getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); + assertThat(miningParams.getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); + assertThat(miningParams.getDynamic().getExtraData()) + .isEqualTo(Bytes.fromHexString(extraDataString)); + }, "--miner-enabled", + "--miner-coinbase=" + requestedCoinbase.toString(), + "--min-gas-price=15", + "--miner-extra-data=" + extraDataString); +// parseCommand( +// "--miner-enabled", +// "--miner-coinbase=" + requestedCoinbase.toString(), +// "--min-gas-price=15", +// "--miner-extra-data=" + extraDataString); +// +// final ArgumentCaptor miningArg = +// ArgumentCaptor.forClass(MiningParameters.class); +// +// verify(mockControllerBuilder).miningParameters(miningArg.capture()); +// verify(mockControllerBuilder).build(); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); +// assertThat(miningArg.getValue().getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); +// assertThat(miningArg.getValue().getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); +// assertThat(miningArg.getValue().getDynamic().getExtraData()) +// .isEqualTo(Bytes.fromHexString(extraDataString)); + } + + @Test + public void targetGasLimitIsEnabledWhenSpecified() { + internalTestSuccess(miningParams -> assertThat( + miningParams.getDynamic().getTargetGasLimit().getAsLong()) + .isEqualTo(10_000_000L), "--target-gas-limit=10000000"); +// parseCommand("--target-gas-limit=10000000"); +// +// @SuppressWarnings("unchecked") +// final ArgumentCaptor miningParametersArgumentCaptor = +// ArgumentCaptor.forClass(MiningParameters.class); +// +// verify(mockControllerBuilder).miningParameters(miningParametersArgumentCaptor.capture()); +// verify(mockControllerBuilder).build(); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); +// +// assertThat( +// miningParametersArgumentCaptor.getValue().getDynamic().getTargetGasLimit().getAsLong()) +// .isEqualTo(10_000_000L); + } + + @Test + public void targetGasLimitIsDisabledWhenNotSpecified() { + internalTestSuccess(miningParams -> { + final ArgumentCaptor gasLimitCalculatorArgumentCaptor = + ArgumentCaptor.forClass(GasLimitCalculator.class); + + verify(mockControllerBuilder).gasLimitCalculator(gasLimitCalculatorArgumentCaptor.capture()); + assertThat(gasLimitCalculatorArgumentCaptor.getValue()) + .isEqualTo(GasLimitCalculator.constant()); + }); +// parseCommand(); +// +// @SuppressWarnings("unchecked") +// final ArgumentCaptor gasLimitCalculatorArgumentCaptor = +// ArgumentCaptor.forClass(GasLimitCalculator.class); +// +// verify(mockControllerBuilder).gasLimitCalculator(gasLimitCalculatorArgumentCaptor.capture()); +// verify(mockControllerBuilder).build(); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); +// +// assertThat(gasLimitCalculatorArgumentCaptor.getValue()) +// .isEqualTo(GasLimitCalculator.constant()); + } + + + @Test + public void posBlockCreationMaxTimeDefaultValue() { + internalTestSuccess(miningParams -> assertThat(miningParams. + getPosBlockCreationMaxTime()).isEqualTo(DEFAULT_POS_BLOCK_CREATION_MAX_TIME)); +// parseCommand(); +// assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(DEFAULT_POS_BLOCK_CREATION_MAX_TIME); + } + + @Test + public void posBlockCreationMaxTimeOption() { + internalTestSuccess(miningParams -> assertThat(miningParams. + getPosBlockCreationMaxTime()).isEqualTo(7000L), "--Xpos-block-creation-max-time", "7000"); +// parseCommand("--Xpos-block-creation-max-time", "7000"); +// assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(7000L); + } + +// private long getPosBlockCreationMaxTimeValue() { +// final ArgumentCaptor miningArg = +// ArgumentCaptor.forClass(MiningParameters.class); +// +// verify(mockControllerBuilder).miningParameters(miningArg.capture()); +// verify(mockControllerBuilder).build(); +// +// assertThat(commandOutput.toString(UTF_8)).isEmpty(); +// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); +// return miningArg.getValue().getPosBlockCreationMaxTime(); +// } + + @Test + public void posBlockCreationMaxTimeOutOfAllowedRange() { + internalTestFailure("--Xpos-block-creation-max-time must be positive and ≤ 12000", "--Xpos-block-creation-max-time", "17000"); +// +// parseCommand("--Xpos-block-creation-max-time", "17000"); +// assertThat(commandErrorOutput.toString(UTF_8)) +// .contains("--Xpos-block-creation-max-time must be positive and ≤ 12000"); + } + + @Override + protected MiningParameters createDefaultDomainObject() { + return ImmutableMiningParameters.builder().build(); + } + + @Override + protected MiningParameters createCustomizedDomainObject() { + return null; + } + + @Override + protected MiningOptions optionsFromDomainObject(final MiningParameters domainObject) { + return MiningOptions.fromConfig(domainObject); + } + + @Override + protected MiningOptions getOptionsFromBesuCommand(final TestBesuCommand besuCommand) { + return besuCommand.getMiningOptions(); + } +} From 18bcce3432bd024225c37ccad4c22c8687207694 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Thu, 12 Oct 2023 14:00:41 +0200 Subject: [PATCH 06/24] Unit test fixes Signed-off-by: Fabio Di Fabio --- .../org/hyperledger/besu/cli/BesuCommand.java | 80 +- .../cli/options/stable/MiningOptions.java | 112 +-- .../besu/cli/util/CommandLineUtils.java | 3 +- .../hyperledger/besu/cli/BesuCommandTest.java | 18 +- .../besu/cli/CommandTestAbstract.java | 2 +- .../cli/options/AbstractCLIOptionsTest.java | 15 +- .../cli/options/stable/MiningOptionsTest.java | 757 ++++++++++-------- .../merge/blockcreation/MergeCoordinator.java | 9 +- .../blockcreation/MergeCoordinatorTest.java | 9 +- .../AbstractBlockTransactionSelectorTest.java | 18 +- .../besu/ethereum/core/MiningParameters.java | 32 + plugin-api/build.gradle | 2 +- 12 files changed, 578 insertions(+), 479 deletions(-) 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 fce760dc3f0..906a7cca9db 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -287,7 +287,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable { unstableTransactionPoolOptions = org.hyperledger.besu.cli.options.unstable.TransactionPoolOptions.create(); private final DnsOptions unstableDnsOptions = DnsOptions.create(); -// private final MiningOptions unstableMiningOptions = MiningOptions.create(); + // private final MiningOptions unstableMiningOptions = MiningOptions.create(); private final NatOptions unstableNatOptions = NatOptions.create(); private final NativeLibraryOptions unstableNativeLibraryOptions = NativeLibraryOptions.create(); private final RPCOptions unstableRPCOptions = RPCOptions.create(); @@ -1586,7 +1586,7 @@ private void handleUnstableOptions() { .put("Privacy Plugin Configuration", unstablePrivacyPluginOptions) .put("Synchronizer", unstableSynchronizerOptions) .put("TransactionPool", unstableTransactionPoolOptions) -// .put("Mining", unstableMiningOptions) + // .put("Mining", unstableMiningOptions) .put("Native Library", unstableNativeLibraryOptions) .put("EVM Options", unstableEvmOptions) .put("IPC Options", unstableIpcOptions) @@ -1871,7 +1871,7 @@ private void validateRequiredOptions() { }); } -// @SuppressWarnings("ConstantConditions") + // @SuppressWarnings("ConstantConditions") private void validateMiningParams() { miningOptions.validate( commandLine, logger, isMergeEnabled(), getActualGenesisConfigOptions().isEthHash()); @@ -1891,19 +1891,19 @@ private void validateMiningParams() { // (remove --miner-stratum-enabled) " // + "or specify mining is enabled (--miner-enabled)"); // } -// if (unstableMiningOptions.getPosBlockCreationMaxTime() <= 0 -// || unstableMiningOptions.getPosBlockCreationMaxTime() -// > MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { -// throw new ParameterException( -// this.commandLine, "--Xpos-block-creation-max-time must be positive and ≤ 12000"); -// } -// -// if (unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() <= 0 -// || unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() > 2000) { -// throw new ParameterException( -// this.commandLine, -// "--Xpos-block-creation-repetition-min-duration must be positive and ≤ 2000"); -// } + // if (unstableMiningOptions.getPosBlockCreationMaxTime() <= 0 + // || unstableMiningOptions.getPosBlockCreationMaxTime() + // > MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { + // throw new ParameterException( + // this.commandLine, "--Xpos-block-creation-max-time must be positive and ≤ 12000"); + // } + // + // if (unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() <= 0 + // || unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() > 2000) { + // throw new ParameterException( + // this.commandLine, + // "--Xpos-block-creation-repetition-min-duration must be positive and ≤ 2000"); + // } } /** @@ -2076,30 +2076,30 @@ private void issueOptionWarnings() { "--p2p-port", "--remote-connections-max-percentage")); -// // Check that block producer options work -// if (!isMergeEnabled() && getActualGenesisConfigOptions().isEthHash()) { -// CommandLineUtils.checkOptionDependencies( -// logger, -// commandLine, -// "--miner-enabled", -// !miningParameters.isMiningEnabled(), -// asList( -// "--miner-coinbase", -// "--min-gas-price", -// "--min-block-occupancy-ratio", -// "--miner-extra-data")); -// -// // Check that mining options are able to work -// CommandLineUtils.checkOptionDependencies( -// logger, -// commandLine, -// "--miner-enabled", -// !miningParameters.isMiningEnabled(), -// asList( -// "--miner-stratum-enabled", -// "--Xminer-remote-sealers-limit", -// "--Xminer-remote-sealers-hashrate-ttl")); -// } + // // Check that block producer options work + // if (!isMergeEnabled() && getActualGenesisConfigOptions().isEthHash()) { + // CommandLineUtils.checkOptionDependencies( + // logger, + // commandLine, + // "--miner-enabled", + // !miningParameters.isMiningEnabled(), + // asList( + // "--miner-coinbase", + // "--min-gas-price", + // "--min-block-occupancy-ratio", + // "--miner-extra-data")); + // + // // Check that mining options are able to work + // CommandLineUtils.checkOptionDependencies( + // logger, + // commandLine, + // "--miner-enabled", + // !miningParameters.isMiningEnabled(), + // asList( + // "--miner-stratum-enabled", + // "--Xminer-remote-sealers-limit", + // "--Xminer-remote-sealers-hashrate-ttl")); + // } CommandLineUtils.failIfOptionDoesntMeetRequirement( commandLine, diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java index 3ba7daedea2..0e73901ea41 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java @@ -53,7 +53,6 @@ public class MiningOptions implements CLIOptions { description = "Set if node will perform Stratum mining (default: ${DEFAULT-VALUE})") private Boolean iStratumMiningEnabled = false; - @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings. @Option( names = {"--miner-stratum-host"}, description = "Host for Stratum network mining service (default: ${DEFAULT-VALUE})") @@ -100,65 +99,62 @@ public class MiningOptions implements CLIOptions { "Sets target gas limit per block. If set, each block's gas limit will approach this setting over time if the current gas limit is different.") private Long targetGasLimit = null; - @CommandLine.ArgGroup( - validate = false) + @CommandLine.ArgGroup(validate = false) private final Unstable unstableOptions = new Unstable(); static class Unstable { @CommandLine.Option( - hidden = true, - names = {"--Xminer-remote-sealers-limit"}, - description = - "Limits the number of remote sealers that can submit their hashrates (default: ${DEFAULT-VALUE})") + hidden = true, + names = {"--Xminer-remote-sealers-limit"}, + description = + "Limits the number of remote sealers that can submit their hashrates (default: ${DEFAULT-VALUE})") private Integer remoteSealersLimit = DEFAULT_REMOTE_SEALERS_LIMIT; @CommandLine.Option( - hidden = true, - names = {"--Xminer-remote-sealers-hashrate-ttl"}, - description = - "Specifies the lifetime of each entry in the cache. An entry will be automatically deleted if no update has been received before the deadline (default: ${DEFAULT-VALUE} minutes)") + hidden = true, + names = {"--Xminer-remote-sealers-hashrate-ttl"}, + description = + "Specifies the lifetime of each entry in the cache. An entry will be automatically deleted if no update has been received before the deadline (default: ${DEFAULT-VALUE} minutes)") private Long remoteSealersTimeToLive = DEFAULT_REMOTE_SEALERS_TTL; @CommandLine.Option( - hidden = true, - names = {"--Xminer-pow-job-ttl"}, - description = - "Specifies the time PoW jobs are kept in cache and will accept a solution from miners (default: ${DEFAULT-VALUE} milliseconds)") + hidden = true, + names = {"--Xminer-pow-job-ttl"}, + description = + "Specifies the time PoW jobs are kept in cache and will accept a solution from miners (default: ${DEFAULT-VALUE} milliseconds)") private Long powJobTimeToLive = DEFAULT_POW_JOB_TTL; @CommandLine.Option( - hidden = true, - names = {"--Xmax-ommers-depth"}, - description = - "Specifies the depth of ommer blocks to accept when receiving solutions (default: ${DEFAULT-VALUE})") + hidden = true, + names = {"--Xmax-ommers-depth"}, + description = + "Specifies the depth of ommer blocks to accept when receiving solutions (default: ${DEFAULT-VALUE})") private Integer maxOmmersDepth = DEFAULT_MAX_OMMERS_DEPTH; @CommandLine.Option( - hidden = true, - names = {"--Xminer-stratum-extranonce"}, - description = "Extranonce for Stratum network miners (default: ${DEFAULT-VALUE})") + hidden = true, + names = {"--Xminer-stratum-extranonce"}, + description = "Extranonce for Stratum network miners (default: ${DEFAULT-VALUE})") private String stratumExtranonce = "080c"; @CommandLine.Option( - hidden = true, - names = {"--Xpos-block-creation-max-time"}, - description = - "Specifies the maximum time, in milliseconds, a PoS block creation jobs is allowed to run. Must be positive and ≤ 12000 (default: ${DEFAULT-VALUE} milliseconds)") + hidden = true, + names = {"--Xpos-block-creation-max-time"}, + description = + "Specifies the maximum time, in milliseconds, a PoS block creation jobs is allowed to run. Must be positive and ≤ 12000 (default: ${DEFAULT-VALUE} milliseconds)") private Long posBlockCreationMaxTime = DEFAULT_POS_BLOCK_CREATION_MAX_TIME; @CommandLine.Option( - hidden = true, - names = {"--Xpos-block-creation-repetition-min-duration"}, - description = - "If a PoS block creation repetition takes less than this duration, in milliseconds," - + " then it waits before next repetition. Must be positive and ≤ 2000 (default: ${DEFAULT-VALUE} milliseconds)") + hidden = true, + names = {"--Xpos-block-creation-repetition-min-duration"}, + description = + "If a PoS block creation repetition takes less than this duration, in milliseconds," + + " then it waits before next repetition. Must be positive and ≤ 2000 (default: ${DEFAULT-VALUE} milliseconds)") private Long posBlockCreationRepetitionMinDuration = - DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; + DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; } - private MiningOptions() { - - } + private MiningOptions() {} /** * Create mining options. @@ -222,17 +218,16 @@ public void validate( } if (unstableOptions.posBlockCreationMaxTime <= 0 - || unstableOptions.posBlockCreationMaxTime + || unstableOptions.posBlockCreationMaxTime > MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { throw new ParameterException( - commandLine, "--Xpos-block-creation-max-time must be positive and ≤ 12000"); + commandLine, "--Xpos-block-creation-max-time must be positive and ≤ 12000"); } if (unstableOptions.posBlockCreationRepetitionMinDuration <= 0 - || unstableOptions.posBlockCreationRepetitionMinDuration > 2000) { + || unstableOptions.posBlockCreationRepetitionMinDuration > 2000) { throw new ParameterException( - commandLine, - "--Xpos-block-creation-repetition-min-duration must be positive and ≤ 2000"); + commandLine, "--Xpos-block-creation-repetition-min-duration must be positive and ≤ 2000"); } } @@ -243,18 +238,26 @@ static MiningOptions fromConfig(final MiningParameters miningParameters) { miningOptions.stratumNetworkInterface = miningParameters.getStratumNetworkInterface(); miningOptions.stratumPort = miningParameters.getStratumPort(); miningOptions.extraData = miningParameters.getDynamic().getExtraData(); - miningOptions.minTransactionGasPrice = miningParameters.getDynamic().getMinTransactionGasPrice(); - miningOptions.minBlockOccupancyRatio = miningParameters.getDynamic().getMinBlockOccupancyRatio(); + miningOptions.minTransactionGasPrice = + miningParameters.getDynamic().getMinTransactionGasPrice(); + miningOptions.minBlockOccupancyRatio = + miningParameters.getDynamic().getMinBlockOccupancyRatio(); miningOptions.unstableOptions.remoteSealersLimit = miningParameters.getRemoteSealersLimit(); - miningOptions.unstableOptions.remoteSealersTimeToLive = miningParameters.getRemoteSealersTimeToLive(); + miningOptions.unstableOptions.remoteSealersTimeToLive = + miningParameters.getRemoteSealersTimeToLive(); miningOptions.unstableOptions.powJobTimeToLive = miningParameters.getPowJobTimeToLive(); miningOptions.unstableOptions.maxOmmersDepth = miningParameters.getMaxOmmerDepth(); miningOptions.unstableOptions.stratumExtranonce = miningParameters.getStratumExtranonce(); - miningOptions.unstableOptions.posBlockCreationMaxTime = miningParameters.getPosBlockCreationMaxTime(); - miningOptions.unstableOptions.posBlockCreationRepetitionMinDuration = miningParameters.getPosBlockCreationRepetitionMinDuration(); + miningOptions.unstableOptions.posBlockCreationMaxTime = + miningParameters.getPosBlockCreationMaxTime(); + miningOptions.unstableOptions.posBlockCreationRepetitionMinDuration = + miningParameters.getPosBlockCreationRepetitionMinDuration(); miningParameters.getCoinbase().ifPresent(coinbase -> miningOptions.coinbase = coinbase); - miningParameters.getDynamic().getTargetGasLimit().ifPresent(tgl -> miningOptions.targetGasLimit = tgl); + miningParameters + .getDynamic() + .getTargetGasLimit() + .ifPresent(tgl -> miningOptions.targetGasLimit = tgl); return miningOptions; } @@ -266,13 +269,14 @@ public MiningParameters toDomainObject() { .isStratumMiningEnabled(iStratumMiningEnabled) .stratumNetworkInterface(stratumNetworkInterface) .stratumPort(stratumPort) - .remoteSealersLimit(unstableOptions.remoteSealersLimit) - .remoteSealersTimeToLive(unstableOptions.remoteSealersTimeToLive) - .powJobTimeToLive(unstableOptions.powJobTimeToLive) - .maxOmmerDepth(unstableOptions.maxOmmersDepth) - .stratumExtranonce(unstableOptions.stratumExtranonce) - .posBlockCreationMaxTime(unstableOptions.posBlockCreationMaxTime) - .posBlockCreationRepetitionMinDuration(unstableOptions.posBlockCreationRepetitionMinDuration); + .remoteSealersLimit(unstableOptions.remoteSealersLimit) + .remoteSealersTimeToLive(unstableOptions.remoteSealersTimeToLive) + .powJobTimeToLive(unstableOptions.powJobTimeToLive) + .maxOmmerDepth(unstableOptions.maxOmmersDepth) + .stratumExtranonce(unstableOptions.stratumExtranonce) + .posBlockCreationMaxTime(unstableOptions.posBlockCreationMaxTime) + .posBlockCreationRepetitionMinDuration( + unstableOptions.posBlockCreationRepetitionMinDuration); if (coinbase != null) { miningParametersBuilder.coinbase(coinbase); @@ -294,6 +298,6 @@ public MiningParameters toDomainObject() { @Override public List getCLIOptions() { - return null; + return CommandLineUtils.getCLIOptions(this, new MiningOptions()); } } diff --git a/besu/src/main/java/org/hyperledger/besu/cli/util/CommandLineUtils.java b/besu/src/main/java/org/hyperledger/besu/cli/util/CommandLineUtils.java index 0115420005e..958ada9b8dc 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/util/CommandLineUtils.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/util/CommandLineUtils.java @@ -177,9 +177,8 @@ public static List getCLIOptions(final Object currOptions, final Object var optVal = field.get(currOptions); if (!Objects.equals(optVal, field.get(defaults))) { var optAnn = CommandLine.Option.class.cast(ann); - cliOpts.add(optAnn.names()[0]); final var optConverter = optAnn.converter(); - cliOpts.add(formatValue(optConverter, optVal)); + cliOpts.add(optAnn.names()[0] + "=" + formatValue(optConverter, optVal)); } } catch (IllegalAccessException e) { throw new RuntimeException(e); 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 a10806eb3d5..426fa71794f 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -35,7 +35,6 @@ import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.NET; import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.PERM; import static org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis.WEB3; -//import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.GOERLI_BOOTSTRAP_NODES; import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.GOERLI_DISCOVERY_URL; import static org.hyperledger.besu.ethereum.p2p.config.DefaultDiscoveryConfiguration.MAINNET_BOOTSTRAP_NODES; @@ -912,14 +911,14 @@ public void envVariableOverridesValueFromConfigFile() { MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE) .setExtraData(MiningParameters.Dynamic.DEFAULT_EXTRA_DATA) .toParameters()); -// -// new MiningParameters.Builder() -// .coinbase(Address.fromHexString(expectedCoinbase)) -// -// .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) -// .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) -// .miningEnabled(false) -// .build()); + // + // new MiningParameters.Builder() + // .coinbase(Address.fromHexString(expectedCoinbase)) + // + // .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) + // .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) + // .miningEnabled(false) + // .build()); } @Test @@ -3662,7 +3661,6 @@ public void metricsAndMetricsPushMustNotBeUsedTogether() { .startsWith("--metrics-enabled option and --metrics-push-enabled option can't be used"); } - @Test public void colorCanBeEnabledOrDisabledExplicitly() { Stream.of(true, false) 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 f946496abdc..7d398da3bea 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java @@ -25,7 +25,6 @@ import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.when; -import io.vertx.core.json.JsonObject; import org.hyperledger.besu.Runner; import org.hyperledger.besu.RunnerBuilder; import org.hyperledger.besu.chainexport.RlpBlockExporter; @@ -107,6 +106,7 @@ import io.opentelemetry.api.GlobalOpenTelemetry; import io.vertx.core.Vertx; import io.vertx.core.VertxOptions; +import io.vertx.core.json.JsonObject; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; import org.awaitility.Awaitility; diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/AbstractCLIOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/AbstractCLIOptionsTest.java index 4fb9d9f51ad..09b4e3b1365 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/AbstractCLIOptionsTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/AbstractCLIOptionsTest.java @@ -20,12 +20,8 @@ import static org.mockito.Mockito.atLeast; import static org.mockito.Mockito.verify; -import io.vertx.core.json.JsonObject; import org.hyperledger.besu.cli.CommandTestAbstract; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; import java.util.Collections; import java.util.List; import java.util.function.Consumer; @@ -140,12 +136,12 @@ protected void internalTestFailure(final String errorMsg, final String... args) * @param mainOption the main option name */ protected void verifyOptionsConstraintLoggerCall( - final String mainOption, final String... dependentOptions) { + final String mainOption, final String... dependentOptions) { verify(mockLogger, atLeast(1)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()); + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()); assertThat(stringArgumentCaptor.getAllValues().get(0)).isEqualTo(DEPENDENCY_WARNING_MSG); for (final String option : dependentOptions) { @@ -154,5 +150,4 @@ protected void verifyOptionsConstraintLoggerCall( assertThat(stringArgumentCaptor.getAllValues().get(2)).isEqualTo(mainOption); } - } diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java index 92e2a02b60c..a3a4b2cc32d 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java @@ -14,148 +14,166 @@ */ package org.hyperledger.besu.cli.options.stable; -import org.apache.tuweni.bytes.Bytes; +import static org.assertj.core.api.Assertions.assertThat; +import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; +import static org.mockito.Mockito.atMost; +import static org.mockito.Mockito.verify; + import org.hyperledger.besu.cli.options.AbstractCLIOptionsTest; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.ArgumentCaptor; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; import java.io.IOException; import java.nio.file.Path; import java.util.Optional; -import static java.nio.charset.StandardCharsets.UTF_8; -import static org.assertj.core.api.Assertions.assertThat; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; -import static org.mockito.Mockito.atMost; -import static org.mockito.Mockito.verify; +import org.apache.tuweni.bytes.Bytes; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.ArgumentCaptor; +import org.mockito.junit.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) -public class MiningOptionsTest - extends AbstractCLIOptionsTest { - +public class MiningOptionsTest extends AbstractCLIOptionsTest { @Test public void besuDoesNotStartInMiningModeIfCoinbaseNotSet() { - internalTestFailure("Unable to mine without a valid coinbase. Either disable mining (remove --miner-enabled) or specify the beneficiary of mining (via --miner-coinbase
)", "--miner-enabled"); -// parseCommand("--miner-enabled"); -// -// Mockito.verifyNoInteractions(mockControllerBuilder); + internalTestFailure( + "Unable to mine without a valid coinbase. Either disable mining (remove --miner-enabled) or specify the beneficiary of mining (via --miner-coinbase
)", + "--miner-enabled"); + // parseCommand("--miner-enabled"); + // + // Mockito.verifyNoInteractions(mockControllerBuilder); } @Test public void miningIsEnabledWhenSpecified() { final String coinbaseStr = String.format("%040x", 1); -// parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr); - internalTestSuccess(miningOpts -> { - assertThat(miningOpts.isMiningEnabled()).isTrue(); - assertThat(miningOpts.getCoinbase()) + // parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr); + internalTestSuccess( + miningOpts -> { + assertThat(miningOpts.isMiningEnabled()).isTrue(); + assertThat(miningOpts.getCoinbase()) .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); - }, "--miner-enabled", "--miner-coinbase=" + coinbaseStr); -// final ArgumentCaptor miningArg = -// ArgumentCaptor.forClass(MiningParameters.class); -// -// verify(mockControllerBuilder).miningParameters(miningArg.capture()); -// verify(mockControllerBuilder).build(); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); -// assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); -// assertThat(miningArg.getValue().getCoinbase()) -// .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); + }, + "--miner-enabled", + "--miner-coinbase=" + coinbaseStr); + // final ArgumentCaptor miningArg = + // ArgumentCaptor.forClass(MiningParameters.class); + // + // verify(mockControllerBuilder).miningParameters(miningArg.capture()); + // verify(mockControllerBuilder).build(); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + // assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); + // assertThat(miningArg.getValue().getCoinbase()) + // .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); } @Test public void stratumMiningIsEnabledWhenSpecified() { final String coinbaseStr = String.format("%040x", 1); -// parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr, "--miner-stratum-enabled"); -// - internalTestSuccess(miningOpts -> { - assertThat(miningOpts.isMiningEnabled()).isTrue(); - assertThat(miningOpts.getCoinbase()) + // parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr, + // "--miner-stratum-enabled"); + // + internalTestSuccess( + miningOpts -> { + assertThat(miningOpts.isMiningEnabled()).isTrue(); + assertThat(miningOpts.getCoinbase()) .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); - assertThat(miningOpts.isStratumMiningEnabled()).isTrue(); - }, "--miner-enabled", "--miner-coinbase=" + coinbaseStr, "--miner-stratum-enabled"); - -// -// final ArgumentCaptor miningArg = -// ArgumentCaptor.forClass(MiningParameters.class); -// -// verify(mockControllerBuilder).miningParameters(miningArg.capture()); -// verify(mockControllerBuilder).build(); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); -// assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); -// assertThat(miningArg.getValue().getCoinbase()) -// .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); -// assertThat(miningArg.getValue().isStratumMiningEnabled()).isTrue(); + assertThat(miningOpts.isStratumMiningEnabled()).isTrue(); + }, + "--miner-enabled", + "--miner-coinbase=" + coinbaseStr, + "--miner-stratum-enabled"); + + // + // final ArgumentCaptor miningArg = + // ArgumentCaptor.forClass(MiningParameters.class); + // + // verify(mockControllerBuilder).miningParameters(miningArg.capture()); + // verify(mockControllerBuilder).build(); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + // assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); + // assertThat(miningArg.getValue().getCoinbase()) + // .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); + // assertThat(miningArg.getValue().isStratumMiningEnabled()).isTrue(); } @Test public void stratumMiningOptionsRequiresServiceToBeEnabled() { -internalTestFailure("Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)", - "--network", "dev", "--miner-stratum-enabled"); -// parseCommand("--network", "dev", "--miner-stratum-enabled"); - -// verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); - -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)) -// .startsWith( -// "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); + internalTestFailure( + "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)", + "--network", + "dev", + "--miner-stratum-enabled"); + // parseCommand("--network", "dev", "--miner-stratum-enabled"); + + // verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); + + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)) + // .startsWith( + // "Unable to mine with Stratum if mining is disabled. Either disable Stratum + // mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); } @Test public void stratumMiningOptionsRequiresServiceToBeEnabledToml() throws IOException { final Path toml = createTempFile("toml", "miner-stratum-enabled=true\n"); - internalTestFailure("Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)", - "--network", "dev", "--config-file", toml.toString()); -// parseCommand("--network", "dev", "--config-file", toml.toString()); -// -// verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)) -// .startsWith( -// "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); + internalTestFailure( + "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)", + "--network", + "dev", + "--config-file", + toml.toString()); + // parseCommand("--network", "dev", "--config-file", toml.toString()); + // + // verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)) + // .startsWith( + // "Unable to mine with Stratum if mining is disabled. Either disable Stratum + // mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); } @Test public void blockProducingOptionsWarnsMinerShouldBeEnabled() { final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); - internalTestSuccess(miningOpts -> verifyOptionsConstraintLoggerCall( - "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"), - "--network", - "dev", - "--miner-coinbase", - requestedCoinbase.toString(), - "--min-gas-price", - "42", - "--miner-extra-data", - "0x1122334455667788990011223344556677889900112233445566778899001122" ); -// parseCommand( -// "--network", -// "dev", -// "--miner-coinbase", -// requestedCoinbase.toString(), -// "--min-gas-price", -// "42", -// "--miner-extra-data", -// "0x1122334455667788990011223344556677889900112233445566778899001122"); -// -// verifyOptionsConstraintLoggerCall( -// "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + internalTestSuccess( + miningOpts -> + verifyOptionsConstraintLoggerCall( + "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"), + "--network", + "dev", + "--miner-coinbase", + requestedCoinbase.toString(), + "--min-gas-price", + "42", + "--miner-extra-data", + "0x1122334455667788990011223344556677889900112233445566778899001122"); + // parseCommand( + // "--network", + // "dev", + // "--miner-coinbase", + // requestedCoinbase.toString(), + // "--min-gas-price", + // "42", + // "--miner-extra-data", + // "0x1122334455667788990011223344556677889900112233445566778899001122"); + // + // verifyOptionsConstraintLoggerCall( + // "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test @@ -164,321 +182,357 @@ public void blockProducingOptionsWarnsMinerShouldBeEnabledToml() throws IOExcept final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); final Path toml = - createTempFile( - "toml", - "network=\"dev\"\n" - + "miner-coinbase=\"" - + requestedCoinbase - + "\"\n" - + "min-gas-price=42\n" - + "miner-extra-data=\"0x1122334455667788990011223344556677889900112233445566778899001122\"\n"); - - internalTestSuccess(miningOpts -> verifyOptionsConstraintLoggerCall( - "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"), - "--config-file", toml.toString() ); - -// parseCommand("--config-file", toml.toString()); -// -// verifyOptionsConstraintLoggerCall( -// "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + createTempFile( + "toml", + "network=\"dev\"\n" + + "miner-coinbase=\"" + + requestedCoinbase + + "\"\n" + + "min-gas-price=42\n" + + "miner-extra-data=\"0x1122334455667788990011223344556677889900112233445566778899001122\"\n"); + + internalTestSuccess( + miningOpts -> + verifyOptionsConstraintLoggerCall( + "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"), + "--config-file", + toml.toString()); + + // parseCommand("--config-file", toml.toString()); + // + // verifyOptionsConstraintLoggerCall( + // "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test public void blockProducingOptionsDoNotWarnWhenPoAQBFT() throws IOException { final Path genesisFileQBFT = createFakeGenesisFile(VALID_GENESIS_QBFT_POST_LONDON); -// parseCommand( -// "--genesis-file", -// genesisFileQBFT.toString(), -// "--min-gas-price", -// "42", -// "--miner-extra-data", -// "0x1122334455667788990011223344556677889900112233445566778899001122"); - - internalTestSuccess(miningOpts -> verify(mockLogger, atMost(0)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()), - "--genesis-file", - genesisFileQBFT.toString(), - "--min-gas-price", - "42", - "--miner-extra-data", - "0x1122334455667788990011223344556677889900112233445566778899001122"); + // parseCommand( + // "--genesis-file", + // genesisFileQBFT.toString(), + // "--min-gas-price", + // "42", + // "--miner-extra-data", + // "0x1122334455667788990011223344556677889900112233445566778899001122"); + + internalTestSuccess( + miningOpts -> + verify(mockLogger, atMost(0)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()), + "--genesis-file", + genesisFileQBFT.toString(), + "--min-gas-price", + "42", + "--miner-extra-data", + "0x1122334455667788990011223344556677889900112233445566778899001122"); } -// verify(mockLogger, atMost(0)) -// .warn( -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture()); -//// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + // verify(mockLogger, atMost(0)) + // .warn( + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture()); + //// + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @Test public void blockProducingOptionsDoNotWarnWhenPoAIBFT2() throws IOException { final Path genesisFileIBFT2 = createFakeGenesisFile(VALID_GENESIS_IBFT2_POST_LONDON); - internalTestSuccess(miningOpts -> verify(mockLogger, atMost(0)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()), - "--genesis-file", - genesisFileIBFT2.toString(), - "--min-gas-price", - "42", - "--miner-extra-data", - "0x1122334455667788990011223344556677889900112233445566778899001122"); -// -// parseCommand( -// "--genesis-file", -// genesisFileIBFT2.toString(), -// "--min-gas-price", -// "42", -// "--miner-extra-data", -// "0x1122334455667788990011223344556677889900112233445566778899001122"); -// -// verify(mockLogger, atMost(0)) -// .warn( -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture()); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + internalTestSuccess( + miningOpts -> + verify(mockLogger, atMost(0)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()), + "--genesis-file", + genesisFileIBFT2.toString(), + "--min-gas-price", + "42", + "--miner-extra-data", + "0x1122334455667788990011223344556677889900112233445566778899001122"); + // + // parseCommand( + // "--genesis-file", + // genesisFileIBFT2.toString(), + // "--min-gas-price", + // "42", + // "--miner-extra-data", + // "0x1122334455667788990011223344556677889900112233445566778899001122"); + // + // verify(mockLogger, atMost(0)) + // .warn( + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture()); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test public void blockProducingOptionsDoNotWarnWhenMergeEnabled() { final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); - internalTestSuccess(miningOpt -> verify(mockLogger, atMost(0)) - .warn( + internalTestSuccess( + miningOpt -> + verify(mockLogger, atMost(0)) + .warn( stringArgumentCaptor.capture(), stringArgumentCaptor.capture(), stringArgumentCaptor.capture()), - "--miner-coinbase", - requestedCoinbase.toString(), - "--min-gas-price", - "42", - "--miner-extra-data", - "0x1122334455667788990011223344556677889900112233445566778899001122" -); -// parseCommand( -// "--miner-coinbase", -// requestedCoinbase.toString(), -// "--min-gas-price", -// "42", -// "--miner-extra-data", -// "0x1122334455667788990011223344556677889900112233445566778899001122"); -// -// verify(mockLogger, atMost(0)) -// .warn( -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture()); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + "--miner-coinbase", + requestedCoinbase.toString(), + "--min-gas-price", + "42", + "--miner-extra-data", + "0x1122334455667788990011223344556677889900112233445566778899001122"); + // parseCommand( + // "--miner-coinbase", + // requestedCoinbase.toString(), + // "--min-gas-price", + // "42", + // "--miner-extra-data", + // "0x1122334455667788990011223344556677889900112233445566778899001122"); + // + // verify(mockLogger, atMost(0)) + // .warn( + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture()); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test public void minGasPriceRequiresMainOption() { - internalTestSuccess(miningOpt -> verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"), - "--min-gas-price", "0", "--network", "dev" - ); -// -// parseCommand("--min-gas-price", "0", "--network", "dev"); -// -// verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + internalTestSuccess( + miningOpt -> verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"), + "--min-gas-price", + "0", + "--network", + "dev"); + // + // parseCommand("--min-gas-price", "0", "--network", "dev"); + // + // verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test public void minGasPriceRequiresMainOptionToml() throws IOException { final Path toml = createTempFile("toml", "min-gas-price=0\nnetwork=\"dev\"\n"); - internalTestSuccess(miningOpt -> verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"), - "--config-file", toml.toString() - ); -// -// parseCommand("--config-file", toml.toString()); -// -// verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + internalTestSuccess( + miningOpt -> verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"), + "--config-file", + toml.toString()); + // + // parseCommand("--config-file", toml.toString()); + // + // verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test public void minGasPriceDoesNotRequireMainOptionWhenPoAQBFT() throws IOException { final Path genesisFileQBFT = createFakeGenesisFile(VALID_GENESIS_QBFT_POST_LONDON); - internalTestSuccess(miningOpt -> verify(mockLogger, atMost(0)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()), - "--genesis-file", genesisFileQBFT.toString(), "--min-gas-price", "0" - ); + internalTestSuccess( + miningOpt -> + verify(mockLogger, atMost(0)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()), + "--genesis-file", + genesisFileQBFT.toString(), + "--min-gas-price", + "0"); } -// -// parseCommand("--genesis-file", genesisFileQBFT.toString(), "--min-gas-price", "0"); -// -// verify(mockLogger, atMost(0)) -// .warn( -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture()); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); -@Test -public void minGasPriceDoesNotRequireMainOptionWhenPoAIBFT2() throws IOException { + // + // parseCommand("--genesis-file", genesisFileQBFT.toString(), "--min-gas-price", "0"); + // + // verify(mockLogger, atMost(0)) + // .warn( + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture()); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + @Test + public void minGasPriceDoesNotRequireMainOptionWhenPoAIBFT2() throws IOException { final Path genesisFileIBFT2 = createFakeGenesisFile(VALID_GENESIS_IBFT2_POST_LONDON); - internalTestSuccess(miningOpt -> verify(mockLogger, atMost(0)) - .warn( - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture(), - stringArgumentCaptor.capture()), - "--genesis-file", genesisFileIBFT2.toString(), "--min-gas-price", "0" - ); -// parseCommand("--genesis-file", genesisFileIBFT2.toString(), "--min-gas-price", "0"); -// -// verify(mockLogger, atMost(0)) -// .warn( -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture(), -// stringArgumentCaptor.capture()); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + internalTestSuccess( + miningOpt -> + verify(mockLogger, atMost(0)) + .warn( + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture(), + stringArgumentCaptor.capture()), + "--genesis-file", + genesisFileIBFT2.toString(), + "--min-gas-price", + "0"); + // parseCommand("--genesis-file", genesisFileIBFT2.toString(), "--min-gas-price", "0"); + // + // verify(mockLogger, atMost(0)) + // .warn( + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture(), + // stringArgumentCaptor.capture()); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test public void miningParametersAreCaptured() { final Address requestedCoinbase = Address.fromHexString("0000011111222223333344444"); final String extraDataString = - "0x1122334455667788990011223344556677889900112233445566778899001122"; - internalTestSuccess(miningParams -> { - assertThat(miningParams.getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); - assertThat(miningParams.getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); - assertThat(miningParams.getDynamic().getExtraData()) + "0x1122334455667788990011223344556677889900112233445566778899001122"; + internalTestSuccess( + miningParams -> { + assertThat(miningParams.getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); + assertThat(miningParams.getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); + assertThat(miningParams.getDynamic().getExtraData()) .isEqualTo(Bytes.fromHexString(extraDataString)); - }, "--miner-enabled", - "--miner-coinbase=" + requestedCoinbase.toString(), - "--min-gas-price=15", - "--miner-extra-data=" + extraDataString); -// parseCommand( -// "--miner-enabled", -// "--miner-coinbase=" + requestedCoinbase.toString(), -// "--min-gas-price=15", -// "--miner-extra-data=" + extraDataString); -// -// final ArgumentCaptor miningArg = -// ArgumentCaptor.forClass(MiningParameters.class); -// -// verify(mockControllerBuilder).miningParameters(miningArg.capture()); -// verify(mockControllerBuilder).build(); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); -// assertThat(miningArg.getValue().getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); -// assertThat(miningArg.getValue().getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); -// assertThat(miningArg.getValue().getDynamic().getExtraData()) -// .isEqualTo(Bytes.fromHexString(extraDataString)); + }, + "--miner-enabled", + "--miner-coinbase=" + requestedCoinbase.toString(), + "--min-gas-price=15", + "--miner-extra-data=" + extraDataString); + // parseCommand( + // "--miner-enabled", + // "--miner-coinbase=" + requestedCoinbase.toString(), + // "--min-gas-price=15", + // "--miner-extra-data=" + extraDataString); + // + // final ArgumentCaptor miningArg = + // ArgumentCaptor.forClass(MiningParameters.class); + // + // verify(mockControllerBuilder).miningParameters(miningArg.capture()); + // verify(mockControllerBuilder).build(); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + // assertThat(miningArg.getValue().getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); + // + // assertThat(miningArg.getValue().getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); + // assertThat(miningArg.getValue().getDynamic().getExtraData()) + // .isEqualTo(Bytes.fromHexString(extraDataString)); } @Test public void targetGasLimitIsEnabledWhenSpecified() { - internalTestSuccess(miningParams -> assertThat( - miningParams.getDynamic().getTargetGasLimit().getAsLong()) - .isEqualTo(10_000_000L), "--target-gas-limit=10000000"); -// parseCommand("--target-gas-limit=10000000"); -// -// @SuppressWarnings("unchecked") -// final ArgumentCaptor miningParametersArgumentCaptor = -// ArgumentCaptor.forClass(MiningParameters.class); -// -// verify(mockControllerBuilder).miningParameters(miningParametersArgumentCaptor.capture()); -// verify(mockControllerBuilder).build(); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); -// -// assertThat( -// miningParametersArgumentCaptor.getValue().getDynamic().getTargetGasLimit().getAsLong()) -// .isEqualTo(10_000_000L); + internalTestSuccess( + miningParams -> + assertThat(miningParams.getDynamic().getTargetGasLimit().getAsLong()) + .isEqualTo(10_000_000L), + "--target-gas-limit=10000000"); + // parseCommand("--target-gas-limit=10000000"); + // + // @SuppressWarnings("unchecked") + // final ArgumentCaptor miningParametersArgumentCaptor = + // ArgumentCaptor.forClass(MiningParameters.class); + // + // verify(mockControllerBuilder).miningParameters(miningParametersArgumentCaptor.capture()); + // verify(mockControllerBuilder).build(); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + // + // assertThat( + // + // miningParametersArgumentCaptor.getValue().getDynamic().getTargetGasLimit().getAsLong()) + // .isEqualTo(10_000_000L); } @Test public void targetGasLimitIsDisabledWhenNotSpecified() { - internalTestSuccess(miningParams -> { - final ArgumentCaptor gasLimitCalculatorArgumentCaptor = + internalTestSuccess( + miningParams -> { + final ArgumentCaptor gasLimitCalculatorArgumentCaptor = ArgumentCaptor.forClass(GasLimitCalculator.class); - verify(mockControllerBuilder).gasLimitCalculator(gasLimitCalculatorArgumentCaptor.capture()); - assertThat(gasLimitCalculatorArgumentCaptor.getValue()) + verify(mockControllerBuilder) + .gasLimitCalculator(gasLimitCalculatorArgumentCaptor.capture()); + assertThat(gasLimitCalculatorArgumentCaptor.getValue()) .isEqualTo(GasLimitCalculator.constant()); - }); -// parseCommand(); -// -// @SuppressWarnings("unchecked") -// final ArgumentCaptor gasLimitCalculatorArgumentCaptor = -// ArgumentCaptor.forClass(GasLimitCalculator.class); -// -// verify(mockControllerBuilder).gasLimitCalculator(gasLimitCalculatorArgumentCaptor.capture()); -// verify(mockControllerBuilder).build(); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); -// -// assertThat(gasLimitCalculatorArgumentCaptor.getValue()) -// .isEqualTo(GasLimitCalculator.constant()); + }); + // parseCommand(); + // + // @SuppressWarnings("unchecked") + // final ArgumentCaptor gasLimitCalculatorArgumentCaptor = + // ArgumentCaptor.forClass(GasLimitCalculator.class); + // + // + // verify(mockControllerBuilder).gasLimitCalculator(gasLimitCalculatorArgumentCaptor.capture()); + // verify(mockControllerBuilder).build(); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + // + // assertThat(gasLimitCalculatorArgumentCaptor.getValue()) + // .isEqualTo(GasLimitCalculator.constant()); } - @Test public void posBlockCreationMaxTimeDefaultValue() { - internalTestSuccess(miningParams -> assertThat(miningParams. - getPosBlockCreationMaxTime()).isEqualTo(DEFAULT_POS_BLOCK_CREATION_MAX_TIME)); -// parseCommand(); -// assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(DEFAULT_POS_BLOCK_CREATION_MAX_TIME); + internalTestSuccess( + miningParams -> + assertThat(miningParams.getPosBlockCreationMaxTime()) + .isEqualTo(DEFAULT_POS_BLOCK_CREATION_MAX_TIME)); + // parseCommand(); + // + // assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(DEFAULT_POS_BLOCK_CREATION_MAX_TIME); } @Test public void posBlockCreationMaxTimeOption() { - internalTestSuccess(miningParams -> assertThat(miningParams. - getPosBlockCreationMaxTime()).isEqualTo(7000L), "--Xpos-block-creation-max-time", "7000"); -// parseCommand("--Xpos-block-creation-max-time", "7000"); -// assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(7000L); + internalTestSuccess( + miningParams -> assertThat(miningParams.getPosBlockCreationMaxTime()).isEqualTo(7000L), + "--Xpos-block-creation-max-time", + "7000"); + // parseCommand("--Xpos-block-creation-max-time", "7000"); + // assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(7000L); } -// private long getPosBlockCreationMaxTimeValue() { -// final ArgumentCaptor miningArg = -// ArgumentCaptor.forClass(MiningParameters.class); -// -// verify(mockControllerBuilder).miningParameters(miningArg.capture()); -// verify(mockControllerBuilder).build(); -// -// assertThat(commandOutput.toString(UTF_8)).isEmpty(); -// assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); -// return miningArg.getValue().getPosBlockCreationMaxTime(); -// } + // private long getPosBlockCreationMaxTimeValue() { + // final ArgumentCaptor miningArg = + // ArgumentCaptor.forClass(MiningParameters.class); + // + // verify(mockControllerBuilder).miningParameters(miningArg.capture()); + // verify(mockControllerBuilder).build(); + // + // assertThat(commandOutput.toString(UTF_8)).isEmpty(); + // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + // return miningArg.getValue().getPosBlockCreationMaxTime(); + // } @Test public void posBlockCreationMaxTimeOutOfAllowedRange() { - internalTestFailure("--Xpos-block-creation-max-time must be positive and ≤ 12000", "--Xpos-block-creation-max-time", "17000"); -// -// parseCommand("--Xpos-block-creation-max-time", "17000"); -// assertThat(commandErrorOutput.toString(UTF_8)) -// .contains("--Xpos-block-creation-max-time must be positive and ≤ 12000"); + internalTestFailure( + "--Xpos-block-creation-max-time must be positive and ≤ 12000", + "--Xpos-block-creation-max-time", + "17000"); + // + // parseCommand("--Xpos-block-creation-max-time", "17000"); + // assertThat(commandErrorOutput.toString(UTF_8)) + // .contains("--Xpos-block-creation-max-time must be positive and ≤ 12000"); } @Override @@ -488,7 +542,16 @@ protected MiningParameters createDefaultDomainObject() { @Override protected MiningParameters createCustomizedDomainObject() { - return null; + return ImmutableMiningParameters.builder() + .coinbase(Address.ZERO) + .isMiningEnabled(true) + .isStratumMiningEnabled(true) + .posBlockCreationMaxTime(1000) + .build() + .getDynamic() + .setExtraData(Bytes.fromHexString("0xabc321")) + .setMinBlockOccupancyRatio(0.5) + .toParameters(); } @Override diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java index bb98d273e00..3dfb74129b5 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java @@ -56,7 +56,6 @@ import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicReference; import java.util.function.Supplier; import com.google.common.annotations.VisibleForTesting; @@ -83,8 +82,8 @@ public class MergeCoordinator implements MergeMiningCoordinator, BadChainListene /** The Merge block creator factory. */ protected final MergeBlockCreatorFactory mergeBlockCreatorFactory; /** The Extra data. */ - protected final AtomicReference extraData = - new AtomicReference<>(Bytes.fromHexString("0x")); + // protected final AtomicReference extraData = + // new AtomicReference<>(Bytes.fromHexString("0x")); /** The Merge miningParameters. */ protected final MergeContext mergeContext; /** The Protocol miningParameters. */ @@ -144,7 +143,7 @@ public MergeCoordinator( miningParameters, // address.or(miningParameters::getCoinbase).orElse(Address.ZERO), // () -> Optional.of(targetGasLimit.longValue()), - parent -> extraData.get(), + parent -> miningParameters.getDynamic().getExtraData(), transactionPool, protocolContext, protocolSchedule, @@ -229,7 +228,7 @@ public Wei getMinTransactionGasPrice() { @Override public void setExtraData(final Bytes extraData) { - this.extraData.set(extraData); + this.miningParameters.getDynamic().setExtraData(extraData); } @Override diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java index c2aed4b10ac..431201a604a 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java @@ -25,7 +25,6 @@ import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doCallRealMethod; -import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; import static org.mockito.Mockito.spy; @@ -99,7 +98,6 @@ import org.mockito.Answers; import org.mockito.ArgumentCaptor; import org.mockito.Mock; -import org.mockito.Spy; import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; @@ -133,7 +131,6 @@ public class MergeCoordinatorTest implements MergeGenesisConfigHelper { @Mock ProposalBuilderExecutor proposalBuilderExecutor; private final Address coinbase = genesisAllocations(getPosGenesisConfigFile()).findFirst().get(); - @Spy MiningParameters miningParameters = ImmutableMiningParameters.builder() .coinbase(coinbase) @@ -551,7 +548,11 @@ public void shouldRetryBlockCreationOnRecoverableError() @Test public void shouldStopRetryBlockCreationIfTimeExpired() throws InterruptedException { final AtomicLong retries = new AtomicLong(0); - doReturn(100L).when(miningParameters).getPosBlockCreationMaxTime(); + miningParameters = + ImmutableMiningParameters.builder() + .from(miningParameters) + .posBlockCreationMaxTime(100) + .build(); doAnswer( invocation -> { retries.incrementAndGet(); 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 96d8d5cf7f7..83107e1ce4c 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 @@ -42,6 +42,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; @@ -106,15 +107,13 @@ public abstract class AbstractBlockTransactionSelectorTest { protected TransactionPool transactionPool; protected MutableWorldState worldState; protected ProtocolSchedule protocolSchedule; + protected MiningParameters miningParameters; @Mock(answer = Answers.RETURNS_DEEP_STUBS) protected ProtocolContext protocolContext; @Mock protected MainnetTransactionProcessor transactionProcessor; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) - protected MiningParameters miningParameters; - @Mock(answer = Answers.RETURNS_DEEP_STUBS) protected EthContext ethContext; @@ -145,7 +144,12 @@ public void setup() { when(protocolContext.getWorldStateArchive().getMutable(any(), anyBoolean())) .thenReturn(Optional.of(worldState)); when(ethContext.getEthPeers().subscribeConnect(any())).thenReturn(1L); - when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.ONE); + miningParameters = + ImmutableMiningParameters.builder() + .build() + .getDynamic() + .setMinTransactionGasPrice(Wei.ONE) + .toParameters(); transactionPool = createTransactionPool(); } @@ -701,7 +705,11 @@ protected BlockTransactionSelector createBlockSelector( final double minBlockOccupancyRatio) { final BlockTransactionSelector selector = new BlockTransactionSelector( - miningParameters, + miningParameters + .getDynamic() + .setMinTransactionGasPrice(minGasPrice) + .setMinBlockOccupancyRatio(minBlockOccupancyRatio) + .toParameters(), transactionProcessor, blockchain, worldState, diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java index 386a74d4656..9f1ba9e5af1 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java @@ -18,6 +18,7 @@ import org.hyperledger.besu.datatypes.Wei; import java.time.Duration; +import java.util.Objects; import java.util.Optional; import java.util.OptionalLong; @@ -82,6 +83,37 @@ public Dynamic setTargetGasLimit(final long targetGasLimit) { this.targetGasLimit = OptionalLong.of(targetGasLimit); return this; } + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + final Dynamic dynamic = (Dynamic) o; + return Double.compare(minBlockOccupancyRatio, dynamic.minBlockOccupancyRatio) == 0 + && Objects.equals(extraData, dynamic.extraData) + && Objects.equals(minTransactionGasPrice, dynamic.minTransactionGasPrice) + && Objects.equals(targetGasLimit, dynamic.targetGasLimit); + } + + @Override + public int hashCode() { + return Objects.hash( + extraData, minTransactionGasPrice, minBlockOccupancyRatio, targetGasLimit); + } + + @Override + public String toString() { + return "Dynamic{" + + "extraData=" + + extraData + + ", minTransactionGasPrice=" + + minTransactionGasPrice + + ", minBlockOccupancyRatio=" + + minBlockOccupancyRatio + + ", targetGasLimit=" + + targetGasLimit + + '}'; + } } // Double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; diff --git a/plugin-api/build.gradle b/plugin-api/build.gradle index c4111a633d1..f768971188a 100644 --- a/plugin-api/build.gradle +++ b/plugin-api/build.gradle @@ -69,7 +69,7 @@ Calculated : ${currentHash} tasks.register('checkAPIChanges', FileStateChecker) { description = "Checks that the API for the Plugin-API project does not change without deliberate thought" files = sourceSets.main.allJava.files - knownHash = '8NVdDoCnMQiibEZUsZuemZU+wm3W1LPklcQkiKsriKs=' + knownHash = 'YJdAgciFlYdXDw7/UuK6bG5KQwqF5SQ08h/Aub7VkV0=' } check.dependsOn('checkAPIChanges') From 59fbe8eabc2f4174d6f1acb3c0a0014a39ec8b26 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Thu, 12 Oct 2023 18:10:00 +0200 Subject: [PATCH 07/24] Removed the commented code Signed-off-by: Fabio Di Fabio --- .../dsl/node/ProcessBesuNodeRunner.java | 6 +- .../BesuNodeConfigurationBuilder.java | 10 - .../node/configuration/BesuNodeFactory.java | 5 - .../bft/BftMiningAcceptanceTest.java | 5 - .../org/hyperledger/besu/RunnerBuilder.java | 2 +- .../org/hyperledger/besu/cli/BesuCommand.java | 142 ------ .../besu/cli/DefaultCommandValues.java | 7 - .../cli/options/stable/MiningOptions.java | 52 +- .../cli/options/unstable/MiningOptions.java | 151 ------ .../subcommands/blocks/BlocksSubCommand.java | 17 - .../MainnetBesuControllerBuilder.java | 8 +- .../hyperledger/besu/PrivacyReorgTest.java | 9 +- .../hyperledger/besu/cli/BesuCommandTest.java | 23 +- .../cli/options/stable/MiningOptionsTest.java | 239 +-------- .../besu/services/BesuEventsImplTest.java | 1 - .../blockcreation/CliqueBlockCreator.java | 8 +- .../blockcreation/CliqueMinerExecutor.java | 4 - .../blockcreation/CliqueBlockCreatorTest.java | 9 - .../CliqueMinerExecutorTest.java | 19 - .../bft/blockcreation/BftBlockCreator.java | 8 +- .../blockcreation/BftBlockCreatorFactory.java | 18 +- .../ibft/support/TestContextBuilder.java | 7 - .../blockcreation/BftBlockCreatorTest.java | 3 - .../blockcreation/MergeBlockCreator.java | 8 +- .../merge/blockcreation/MergeCoordinator.java | 46 +- .../blockcreation/MergeCoordinatorTest.java | 12 +- .../merge/blockcreation/MergeReorgTest.java | 1 - .../qbft/support/TestContextBuilder.java | 7 - .../QbftBlockCreatorFactoryTest.java | 1 - .../EthGetFilterChangesIntegrationTest.java | 1 - .../EthGetFilterChangesIntegrationTest.java | 1 - .../blockcreation/AbstractBlockCreator.java | 12 - .../blockcreation/AbstractMinerExecutor.java | 15 - .../blockcreation/PoWBlockCreator.java | 6 - .../blockcreation/PoWMinerExecutor.java | 3 - .../txselection/BlockSelectionContext.java | 2 - .../txselection/BlockTransactionSelector.java | 7 - .../AbstractBlockCreatorTest.java | 9 - .../AbstractBlockTransactionSelectorTest.java | 8 - .../blockcreation/PoWBlockCreatorTest.java | 12 - .../blockcreation/PoWMinerExecutorTest.java | 2 - .../PoWMiningCoordinatorTest.java | 4 +- .../besu/ethereum/core/MiningParameters.java | 466 +++--------------- .../bonsai/AbstractIsolationTests.java | 9 - .../eth/manager/EthProtocolManagerTest.java | 2 - .../ethtaskutils/AbstractMessageTaskTest.java | 1 - .../ethereum/eth/transactions/TestNode.java | 1 - .../TransactionPoolFactoryTest.java | 2 - .../retesteth/methods/TestMineBlocks.java | 3 - 49 files changed, 155 insertions(+), 1239 deletions(-) delete mode 100644 besu/src/main/java/org/hyperledger/besu/cli/options/unstable/MiningOptions.java diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java index f0f2faf9087..aa8a93d27b7 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java @@ -111,9 +111,11 @@ public void startNode(final BesuNode node) { Integer.toString( node.getMiningParameters().getDynamic().getMinTransactionGasPrice().intValue())); params.add("--Xminer-remote-sealers-limit"); - params.add(Integer.toString(node.getMiningParameters().getRemoteSealersLimit())); + params.add( + Integer.toString(node.getMiningParameters().getUnstable().getRemoteSealersLimit())); params.add("--Xminer-remote-sealers-hashrate-ttl"); - params.add(Long.toString(node.getMiningParameters().getRemoteSealersTimeToLive())); + params.add( + Long.toString(node.getMiningParameters().getUnstable().getRemoteSealersTimeToLive())); } if (node.getMiningParameters().isStratumMiningEnabled()) { params.add("--miner-stratum-enabled"); diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java index 1689e2d22e3..88ba6f24861 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java @@ -65,11 +65,6 @@ public class BesuNodeConfigurationBuilder { .setMinTransactionGasPrice(Wei.of(1000)) .toParameters(); - // new MiningParameters.Builder() - // .miningEnabled(false) - // .coinbase(AddressHelpers.ofValue(1)) - // .minTransactionGasPrice(Wei.of(1000)) - // .build(); private JsonRpcConfiguration jsonRpcConfiguration = JsonRpcConfiguration.createDefault(); private JsonRpcConfiguration engineRpcConfiguration = JsonRpcConfiguration.createEngineDefault(); private WebSocketConfiguration webSocketConfiguration = WebSocketConfiguration.createDefault(); @@ -130,11 +125,6 @@ public BesuNodeConfigurationBuilder miningEnabled(final boolean enabled) { .getDynamic() .setMinTransactionGasPrice(Wei.of(1000)) .toParameters(); - // new MiningParameters.Builder() - // .miningEnabled(enabled) - // .minTransactionGasPrice(Wei.of(1000)) - // .coinbase(AddressHelpers.ofValue(1)) - // .build(); this.jsonRpcConfiguration.addRpcApi(RpcApis.MINER.name()); return this; } diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java index 6af79637e07..d0bf27c0478 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java @@ -311,11 +311,6 @@ public BesuNode createNodeWithMultiTenantedPrivacy( .getDynamic() .setMinTransactionGasPrice(Wei.ZERO) .toParameters(); - // new MiningParameters.Builder() - // .minTransactionGasPrice(Wei.ZERO) - // .coinbase(AddressHelpers.ofValue(1)) - // .miningEnabled(true) - // .build(); return create( new BesuNodeConfigurationBuilder() diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java index 1b0e2bfe595..45a93da92b1 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java @@ -67,11 +67,6 @@ public void shouldMineOnSingleNodeWithFreeGas_Berlin() throws Exception { .getDynamic() .setMinTransactionGasPrice(Wei.ZERO) .toParameters(); - // new MiningParameters.Builder() - // .miningEnabled(true) - // .minTransactionGasPrice(Wei.ZERO) - // .coinbase(AddressHelpers.ofValue(1)) - // .build(); minerNode.setMiningParameters(zeroGasMiningParams); cluster.start(minerNode); diff --git a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java index 857fd4e093e..4dc137fe3c7 100644 --- a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java @@ -768,7 +768,7 @@ public Runner build() { powMiningCoordinator, miningParameters.getStratumPort(), miningParameters.getStratumNetworkInterface(), - miningParameters.getStratumExtranonce(), + miningParameters.getUnstable().getStratumExtranonce(), metricsSystem)); miningCoordinator.addEthHashObserver(stratumServer.get()); LOG.debug("added ethash observer: {}", stratumServer.get()); 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 906a7cca9db..7fb15664c21 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -287,7 +287,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable { unstableTransactionPoolOptions = org.hyperledger.besu.cli.options.unstable.TransactionPoolOptions.create(); private final DnsOptions unstableDnsOptions = DnsOptions.create(); - // private final MiningOptions unstableMiningOptions = MiningOptions.create(); private final NatOptions unstableNatOptions = NatOptions.create(); private final NativeLibraryOptions unstableNativeLibraryOptions = NativeLibraryOptions.create(); private final RPCOptions unstableRPCOptions = RPCOptions.create(); @@ -1071,62 +1070,6 @@ static class MetricsOptionGroup { "How deep a chain reorganization must be in order for it to be logged (default: ${DEFAULT-VALUE})") private final Long reorgLoggingThreshold = 6L; - // Miner options group - - // static class MinerOptionGroup { - // @Option( - // names = {"--miner-enabled"}, - // description = "Set if node will perform mining (default: ${DEFAULT-VALUE})") - // private final Boolean isMiningEnabled = false; - // - // @Option( - // names = {"--miner-stratum-enabled"}, - // description = "Set if node will perform Stratum mining (default: ${DEFAULT-VALUE})") - // private final Boolean iStratumMiningEnabled = false; - // - // @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final - // Strings. - // @Option( - // names = {"--miner-stratum-host"}, - // description = "Host for Stratum network mining service (default: ${DEFAULT-VALUE})") - // private String stratumNetworkInterface = "0.0.0.0"; - // - // @Option( - // names = {"--miner-stratum-port"}, - // description = "Stratum port binding (default: ${DEFAULT-VALUE})") - // private final Integer stratumPort = 8008; - // - // @Option( - // names = {"--miner-coinbase"}, - // description = - // "Account to which mining rewards are paid. You must specify a valid coinbase if " - // + "mining is enabled using --miner-enabled option", - // arity = "1") - // private final Address coinbase = null; - // - // @Option( - // names = {"--miner-extra-data"}, - // description = - // "A hex string representing the (32) bytes to be included in the extra data " - // + "field of a mined block (default: ${DEFAULT-VALUE})", - // arity = "1") - // private final Bytes extraData = DEFAULT_EXTRA_DATA; - // } - - // @Option( - // names = {"--min-gas-price"}, - // description = - // "Minimum price (in Wei) offered by a transaction for it to be included in a mined " - // + "block (default: ${DEFAULT-VALUE})", - // arity = "1") - // private final Wei minTransactionGasPrice = DEFAULT_MIN_TRANSACTION_GAS_PRICE; - - // @Option( - // names = {"--min-block-occupancy-ratio"}, - // description = "Minimum occupancy ratio for a mined block (default: ${DEFAULT-VALUE})", - // arity = "1") - // private final Double minBlockOccupancyRatio = DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; - @Option( names = {"--pruning-enabled"}, description = @@ -1205,13 +1148,6 @@ static class PermissionsOptionGroup { arity = "*", split = ",") private final Map requiredBlocks = new HashMap<>(); - // - // @Option( - // names = {"--target-gas-limit"}, - // description = - // "Sets target gas limit per block. If set, each block's gas limit will approach this - // setting over time if the current gas limit is different.") - // private final Long targetGasLimit = null; @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings. @Option( @@ -1586,7 +1522,6 @@ private void handleUnstableOptions() { .put("Privacy Plugin Configuration", unstablePrivacyPluginOptions) .put("Synchronizer", unstableSynchronizerOptions) .put("TransactionPool", unstableTransactionPoolOptions) - // .put("Mining", unstableMiningOptions) .put("Native Library", unstableNativeLibraryOptions) .put("EVM Options", unstableEvmOptions) .put("IPC Options", unstableIpcOptions) @@ -1871,39 +1806,9 @@ private void validateRequiredOptions() { }); } - // @SuppressWarnings("ConstantConditions") private void validateMiningParams() { miningOptions.validate( commandLine, logger, isMergeEnabled(), getActualGenesisConfigOptions().isEthHash()); - // if (Boolean.TRUE.equals(minerOptionGroup.isMiningEnabled) - // && minerOptionGroup.coinbase == null) { - // throw new ParameterException( - // this.commandLine, - // "Unable to mine without a valid coinbase. Either disable mining (remove - // --miner-enabled) " - // + "or specify the beneficiary of mining (via --miner-coinbase
)"); - // } - // if (Boolean.FALSE.equals(minerOptionGroup.isMiningEnabled) - // && Boolean.TRUE.equals(minerOptionGroup.iStratumMiningEnabled)) { - // throw new ParameterException( - // this.commandLine, - // "Unable to mine with Stratum if mining is disabled. Either disable Stratum mining - // (remove --miner-stratum-enabled) " - // + "or specify mining is enabled (--miner-enabled)"); - // } - // if (unstableMiningOptions.getPosBlockCreationMaxTime() <= 0 - // || unstableMiningOptions.getPosBlockCreationMaxTime() - // > MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { - // throw new ParameterException( - // this.commandLine, "--Xpos-block-creation-max-time must be positive and ≤ 12000"); - // } - // - // if (unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() <= 0 - // || unstableMiningOptions.getPosBlockCreationRepetitionMinDuration() > 2000) { - // throw new ParameterException( - // this.commandLine, - // "--Xpos-block-creation-repetition-min-duration must be positive and ≤ 2000"); - // } } /** @@ -2076,31 +1981,6 @@ private void issueOptionWarnings() { "--p2p-port", "--remote-connections-max-percentage")); - // // Check that block producer options work - // if (!isMergeEnabled() && getActualGenesisConfigOptions().isEthHash()) { - // CommandLineUtils.checkOptionDependencies( - // logger, - // commandLine, - // "--miner-enabled", - // !miningParameters.isMiningEnabled(), - // asList( - // "--miner-coinbase", - // "--min-gas-price", - // "--min-block-occupancy-ratio", - // "--miner-extra-data")); - // - // // Check that mining options are able to work - // CommandLineUtils.checkOptionDependencies( - // logger, - // commandLine, - // "--miner-enabled", - // !miningParameters.isMiningEnabled(), - // asList( - // "--miner-stratum-enabled", - // "--Xminer-remote-sealers-limit", - // "--Xminer-remote-sealers-hashrate-ttl")); - // } - CommandLineUtils.failIfOptionDoesntMeetRequirement( commandLine, "--fast-sync-min-peers can't be used with FULL sync-mode", @@ -2254,28 +2134,6 @@ public BesuControllerBuilder getControllerBuilder() { .transactionSelectorFactory(getTransactionSelectorFactory()) .pluginTransactionValidatorFactory(getPluginTransactionValidatorFactory()) .dataDirectory(dataDir()) - // .miningParameters( - // new MiningParameters.Builder() - // .coinbase(minerOptionGroup.coinbase) - // .targetGasLimit(targetGasLimit) - // .minTransactionGasPrice(minTransactionGasPrice) - // .extraData(minerOptionGroup.extraData) - // .miningEnabled(minerOptionGroup.isMiningEnabled) - // .stratumMiningEnabled(minerOptionGroup.iStratumMiningEnabled) - // .stratumNetworkInterface(minerOptionGroup.stratumNetworkInterface) - // .stratumPort(minerOptionGroup.stratumPort) - // .stratumExtranonce(unstableMiningOptions.getStratumExtranonce()) - // .minBlockOccupancyRatio(minBlockOccupancyRatio) - // .remoteSealersLimit(unstableMiningOptions.getRemoteSealersLimit()) - // - // .remoteSealersTimeToLive(unstableMiningOptions.getRemoteSealersTimeToLive()) - // .powJobTimeToLive(unstableMiningOptions.getPowJobTimeToLive()) - // .maxOmmerDepth(unstableMiningOptions.getMaxOmmersDepth()) - // - // .posBlockCreationMaxTime(unstableMiningOptions.getPosBlockCreationMaxTime()) - // .posBlockCreationRepetitionMinDuration( - // unstableMiningOptions.getPosBlockCreationRepetitionMinDuration()) - // .build()) .miningParameters(miningParameters) .transactionPoolConfiguration(buildTransactionPoolConfiguration()) .nodeKey(new NodeKey(securityModule())) diff --git a/besu/src/main/java/org/hyperledger/besu/cli/DefaultCommandValues.java b/besu/src/main/java/org/hyperledger/besu/cli/DefaultCommandValues.java index f15dc412412..b7d603b8caa 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/DefaultCommandValues.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/DefaultCommandValues.java @@ -27,7 +27,6 @@ import java.nio.file.Paths; import java.util.List; -import org.apache.tuweni.bytes.Bytes; import picocli.CommandLine; /** The interface Default command values. */ @@ -57,12 +56,6 @@ public interface DefaultCommandValues { String MANDATORY_NETWORK_FORMAT_HELP = ""; /** The constant MANDATORY_NODE_ID_FORMAT_HELP. */ String MANDATORY_NODE_ID_FORMAT_HELP = ""; - /** The constant DEFAULT_MIN_TRANSACTION_GAS_PRICE. */ - // Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); - /** The constant DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO. */ - // Double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; - /** The constant DEFAULT_EXTRA_DATA. */ - Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY; /** The constant PERMISSIONING_CONFIG_LOCATION. */ String PERMISSIONING_CONFIG_LOCATION = "permissions_config.toml"; /** The constant MANDATORY_HOST_FORMAT_HELP. */ diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java index 0e73901ea41..ad027521066 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java @@ -15,15 +15,15 @@ package org.hyperledger.besu.cli.options.stable; import static java.util.Arrays.asList; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_MAX_OMMERS_DEPTH; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POW_JOB_TTL; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_LIMIT; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_TTL; import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_EXTRA_DATA; import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_MAX_OMMERS_DEPTH; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POW_JOB_TTL; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_REMOTE_SEALERS_LIMIT; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_REMOTE_SEALERS_TTL; import org.hyperledger.besu.cli.options.CLIOptions; import org.hyperledger.besu.cli.util.CommandLineUtils; @@ -218,8 +218,7 @@ public void validate( } if (unstableOptions.posBlockCreationMaxTime <= 0 - || unstableOptions.posBlockCreationMaxTime - > MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { + || unstableOptions.posBlockCreationMaxTime > DEFAULT_POS_BLOCK_CREATION_MAX_TIME) { throw new ParameterException( commandLine, "--Xpos-block-creation-max-time must be positive and ≤ 12000"); } @@ -242,16 +241,20 @@ static MiningOptions fromConfig(final MiningParameters miningParameters) { miningParameters.getDynamic().getMinTransactionGasPrice(); miningOptions.minBlockOccupancyRatio = miningParameters.getDynamic().getMinBlockOccupancyRatio(); - miningOptions.unstableOptions.remoteSealersLimit = miningParameters.getRemoteSealersLimit(); + miningOptions.unstableOptions.remoteSealersLimit = + miningParameters.getUnstable().getRemoteSealersLimit(); miningOptions.unstableOptions.remoteSealersTimeToLive = - miningParameters.getRemoteSealersTimeToLive(); - miningOptions.unstableOptions.powJobTimeToLive = miningParameters.getPowJobTimeToLive(); - miningOptions.unstableOptions.maxOmmersDepth = miningParameters.getMaxOmmerDepth(); - miningOptions.unstableOptions.stratumExtranonce = miningParameters.getStratumExtranonce(); + miningParameters.getUnstable().getRemoteSealersTimeToLive(); + miningOptions.unstableOptions.powJobTimeToLive = + miningParameters.getUnstable().getPowJobTimeToLive(); + miningOptions.unstableOptions.maxOmmersDepth = + miningParameters.getUnstable().getMaxOmmerDepth(); + miningOptions.unstableOptions.stratumExtranonce = + miningParameters.getUnstable().getStratumExtranonce(); miningOptions.unstableOptions.posBlockCreationMaxTime = - miningParameters.getPosBlockCreationMaxTime(); + miningParameters.getUnstable().getPosBlockCreationMaxTime(); miningOptions.unstableOptions.posBlockCreationRepetitionMinDuration = - miningParameters.getPosBlockCreationRepetitionMinDuration(); + miningParameters.getUnstable().getPosBlockCreationRepetitionMinDuration(); miningParameters.getCoinbase().ifPresent(coinbase -> miningOptions.coinbase = coinbase); miningParameters @@ -269,14 +272,17 @@ public MiningParameters toDomainObject() { .isStratumMiningEnabled(iStratumMiningEnabled) .stratumNetworkInterface(stratumNetworkInterface) .stratumPort(stratumPort) - .remoteSealersLimit(unstableOptions.remoteSealersLimit) - .remoteSealersTimeToLive(unstableOptions.remoteSealersTimeToLive) - .powJobTimeToLive(unstableOptions.powJobTimeToLive) - .maxOmmerDepth(unstableOptions.maxOmmersDepth) - .stratumExtranonce(unstableOptions.stratumExtranonce) - .posBlockCreationMaxTime(unstableOptions.posBlockCreationMaxTime) - .posBlockCreationRepetitionMinDuration( - unstableOptions.posBlockCreationRepetitionMinDuration); + .unstable( + ImmutableMiningParameters.Unstable.builder() + .remoteSealersLimit(unstableOptions.remoteSealersLimit) + .remoteSealersTimeToLive(unstableOptions.remoteSealersTimeToLive) + .powJobTimeToLive(unstableOptions.powJobTimeToLive) + .maxOmmerDepth(unstableOptions.maxOmmersDepth) + .stratumExtranonce(unstableOptions.stratumExtranonce) + .posBlockCreationMaxTime(unstableOptions.posBlockCreationMaxTime) + .posBlockCreationRepetitionMinDuration( + unstableOptions.posBlockCreationRepetitionMinDuration) + .build()); if (coinbase != null) { miningParametersBuilder.coinbase(coinbase); diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/unstable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/unstable/MiningOptions.java deleted file mode 100644 index 232554722e2..00000000000 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/unstable/MiningOptions.java +++ /dev/null @@ -1,151 +0,0 @@ -/* - * Copyright ConsenSys AG. - * - * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on - * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the - * specific language governing permissions and limitations under the License. - * - * SPDX-License-Identifier: Apache-2.0 - */ -package org.hyperledger.besu.cli.options.unstable; - -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_MAX_OMMERS_DEPTH; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POW_JOB_TTL; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_LIMIT; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_TTL; - -import picocli.CommandLine; - -/** The Mining CLI options. */ -public class MiningOptions { - - @CommandLine.Option( - hidden = true, - names = {"--Xminer-remote-sealers-limit"}, - description = - "Limits the number of remote sealers that can submit their hashrates (default: ${DEFAULT-VALUE})") - private final Integer remoteSealersLimit = DEFAULT_REMOTE_SEALERS_LIMIT; - - @CommandLine.Option( - hidden = true, - names = {"--Xminer-remote-sealers-hashrate-ttl"}, - description = - "Specifies the lifetime of each entry in the cache. An entry will be automatically deleted if no update has been received before the deadline (default: ${DEFAULT-VALUE} minutes)") - private final Long remoteSealersTimeToLive = DEFAULT_REMOTE_SEALERS_TTL; - - @CommandLine.Option( - hidden = true, - names = {"--Xminer-pow-job-ttl"}, - description = - "Specifies the time PoW jobs are kept in cache and will accept a solution from miners (default: ${DEFAULT-VALUE} milliseconds)") - private final Long powJobTimeToLive = DEFAULT_POW_JOB_TTL; - - @CommandLine.Option( - hidden = true, - names = {"--Xmax-ommers-depth"}, - description = - "Specifies the depth of ommer blocks to accept when receiving solutions (default: ${DEFAULT-VALUE})") - private final Integer maxOmmersDepth = DEFAULT_MAX_OMMERS_DEPTH; - - @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings. - @CommandLine.Option( - hidden = true, - names = {"--Xminer-stratum-extranonce"}, - description = "Extranonce for Stratum network miners (default: ${DEFAULT-VALUE})") - private String stratumExtranonce = "080c"; - - @CommandLine.Option( - hidden = true, - names = {"--Xpos-block-creation-max-time"}, - description = - "Specifies the maximum time, in milliseconds, a PoS block creation jobs is allowed to run. Must be positive and ≤ 12000 (default: ${DEFAULT-VALUE} milliseconds)") - private final Long posBlockCreationMaxTime = DEFAULT_POS_BLOCK_CREATION_MAX_TIME; - - @CommandLine.Option( - hidden = true, - names = {"--Xpos-block-creation-repetition-min-duration"}, - description = - "If a PoS block creation repetition takes less than this duration, in milliseconds," - + " then it waits before next repetition. Must be positive and ≤ 2000 (default: ${DEFAULT-VALUE} milliseconds)") - private final Long posBlockCreationRepetitionMinDuration = - DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; - - /** - * Create mining options. - * - * @return the mining options - */ - public static MiningOptions create() { - return new MiningOptions(); - } - - /** - * Gets remote sealers limit. - * - * @return the remote sealers limit - */ - public Integer getRemoteSealersLimit() { - return remoteSealersLimit; - } - - /** - * Gets remote sealers time to live. - * - * @return the remote sealers time to live - */ - public Long getRemoteSealersTimeToLive() { - return remoteSealersTimeToLive; - } - - /** - * Gets stratum extra nonce. - * - * @return the stratum extra nonce - */ - public String getStratumExtranonce() { - return stratumExtranonce; - } - - /** - * Gets pow job time to live. - * - * @return the pow job time to live - */ - public Long getPowJobTimeToLive() { - return powJobTimeToLive; - } - - /** - * Gets max ommers depth. - * - * @return the max ommers depth - */ - public int getMaxOmmersDepth() { - return maxOmmersDepth; - } - - /** - * Gets pos block creation max time. - * - * @return the pos block creation max time - */ - public Long getPosBlockCreationMaxTime() { - return posBlockCreationMaxTime; - } - - /** - * Gets pos block creation repetition min duration. - * - * @return the pos block creation repetition min duration. - */ - public Long getPosBlockCreationRepetitionMinDuration() { - return posBlockCreationRepetitionMinDuration; - } -} diff --git a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java index 3a1a65981a4..6198154887a 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java @@ -276,23 +276,6 @@ private MiningParameters getMiningParameters() { .setExtraData(extraData) .setMinTransactionGasPrice(minTransactionGasPrice) .toParameters(); - - // return new MiningParameters.Builder() - // .coinbase(coinbase) - // .minTransactionGasPrice(minTransactionGasPrice) - // .extraData(extraData) - // .miningEnabled(false) - // .stratumMiningEnabled(false) - // .stratumNetworkInterface("0.0.0.0") - // .stratumPort(8008) - // .stratumExtranonce("080c") - // .maybeNonceGenerator(new IncrementingNonceGenerator(0)) - // .minBlockOccupancyRatio(0.0) - // .remoteSealersLimit(DEFAULT_REMOTE_SEALERS_LIMIT) - // .remoteSealersTimeToLive(DEFAULT_REMOTE_SEALERS_TTL) - // .powJobTimeToLive(DEFAULT_POW_JOB_TTL) - // .maxOmmerDepth(DEFAULT_MAX_OMMERS_DEPTH) - // .build(); } private void importJsonBlocks(final BesuController controller, final Path path) 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 0fce7f484ce..1b352fcddfc 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java @@ -56,16 +56,16 @@ protected MiningCoordinator createMiningCoordinator( MainnetBlockHeaderValidator.TIMESTAMP_TOLERANCE_S, clock), epochCalculator, - miningParameters.getPowJobTimeToLive(), - miningParameters.getMaxOmmerDepth()); + miningParameters.getUnstable().getPowJobTimeToLive(), + miningParameters.getUnstable().getMaxOmmerDepth()); final PoWMiningCoordinator miningCoordinator = new PoWMiningCoordinator( protocolContext.getBlockchain(), executor, syncState, - miningParameters.getRemoteSealersLimit(), - miningParameters.getRemoteSealersTimeToLive()); + miningParameters.getUnstable().getRemoteSealersLimit(), + miningParameters.getUnstable().getRemoteSealersTimeToLive()); miningCoordinator.addMinedBlockObserver(ethProtocolManager); miningCoordinator.setStratumMiningEnabled(miningParameters.isStratumMiningEnabled()); if (miningParameters.isMiningEnabled()) { diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java index 2889ffefb13..97aa8ff44f7 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java @@ -187,14 +187,7 @@ public void setUp() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters( - ImmutableMiningParameters.builder().isMiningEnabled(false).build() - - // new MiningParameters.Builder() - // .minTransactionGasPrice(Wei.of(1000)) - // .miningEnabled(false) - // .build() - ) + .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .dataDirectory(folder) 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 426fa71794f..a2401fd2b27 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -911,14 +911,6 @@ public void envVariableOverridesValueFromConfigFile() { MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE) .setExtraData(MiningParameters.Dynamic.DEFAULT_EXTRA_DATA) .toParameters()); - // - // new MiningParameters.Builder() - // .coinbase(Address.fromHexString(expectedCoinbase)) - // - // .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) - // .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) - // .miningEnabled(false) - // .build()); } @Test @@ -938,16 +930,7 @@ public void cliOptionOverridesEnvVariableAndConfig() { .setMinTransactionGasPrice( MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE) .setExtraData(MiningParameters.Dynamic.DEFAULT_EXTRA_DATA) - .toParameters() - - // new MiningParameters.Builder() - // .coinbase(Address.fromHexString(expectedCoinbase)) - // - // .minTransactionGasPrice(DefaultCommandValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE) - // .extraData(DefaultCommandValues.DEFAULT_EXTRA_DATA) - // .miningEnabled(false) - // .build() - ); + .toParameters()); } @Test @@ -4762,11 +4745,7 @@ public void assertThatCheckPortClashRejectsAsExpected() throws Exception { public void assertThatCheckPortClashRejectsAsExpectedForEngineApi() throws Exception { // use WS port for HTTP final int port = 8545; - // TODO: once we have mainnet TTD, we can remove the TTD override parameter here - // https://github.com/hyperledger/besu/issues/3874 parseCommand( - "--override-genesis-config", - "terminalTotalDifficulty=1337", "--rpc-http-enabled", "--rpc-http-port", String.valueOf(port), diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java index a3a4b2cc32d..bb50310d596 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java @@ -15,7 +15,7 @@ package org.hyperledger.besu.cli.options.stable; import static org.assertj.core.api.Assertions.assertThat; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.verify; @@ -44,15 +44,11 @@ public void besuDoesNotStartInMiningModeIfCoinbaseNotSet() { internalTestFailure( "Unable to mine without a valid coinbase. Either disable mining (remove --miner-enabled) or specify the beneficiary of mining (via --miner-coinbase
)", "--miner-enabled"); - // parseCommand("--miner-enabled"); - // - // Mockito.verifyNoInteractions(mockControllerBuilder); } @Test public void miningIsEnabledWhenSpecified() { final String coinbaseStr = String.format("%040x", 1); - // parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr); internalTestSuccess( miningOpts -> { assertThat(miningOpts.isMiningEnabled()).isTrue(); @@ -61,25 +57,11 @@ public void miningIsEnabledWhenSpecified() { }, "--miner-enabled", "--miner-coinbase=" + coinbaseStr); - // final ArgumentCaptor miningArg = - // ArgumentCaptor.forClass(MiningParameters.class); - // - // verify(mockControllerBuilder).miningParameters(miningArg.capture()); - // verify(mockControllerBuilder).build(); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - // assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); - // assertThat(miningArg.getValue().getCoinbase()) - // .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); } @Test public void stratumMiningIsEnabledWhenSpecified() { final String coinbaseStr = String.format("%040x", 1); - // parseCommand("--miner-enabled", "--miner-coinbase=" + coinbaseStr, - // "--miner-stratum-enabled"); - // internalTestSuccess( miningOpts -> { assertThat(miningOpts.isMiningEnabled()).isTrue(); @@ -90,20 +72,6 @@ public void stratumMiningIsEnabledWhenSpecified() { "--miner-enabled", "--miner-coinbase=" + coinbaseStr, "--miner-stratum-enabled"); - - // - // final ArgumentCaptor miningArg = - // ArgumentCaptor.forClass(MiningParameters.class); - // - // verify(mockControllerBuilder).miningParameters(miningArg.capture()); - // verify(mockControllerBuilder).build(); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - // assertThat(miningArg.getValue().isMiningEnabled()).isTrue(); - // assertThat(miningArg.getValue().getCoinbase()) - // .isEqualTo(Optional.of(Address.fromHexString(coinbaseStr))); - // assertThat(miningArg.getValue().isStratumMiningEnabled()).isTrue(); } @Test @@ -113,15 +81,6 @@ public void stratumMiningOptionsRequiresServiceToBeEnabled() { "--network", "dev", "--miner-stratum-enabled"); - // parseCommand("--network", "dev", "--miner-stratum-enabled"); - - // verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); - - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)) - // .startsWith( - // "Unable to mine with Stratum if mining is disabled. Either disable Stratum - // mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); } @Test @@ -133,15 +92,6 @@ public void stratumMiningOptionsRequiresServiceToBeEnabledToml() throws IOExcept "dev", "--config-file", toml.toString()); - // parseCommand("--network", "dev", "--config-file", toml.toString()); - // - // verifyOptionsConstraintLoggerCall("--miner-enabled", "--miner-stratum-enabled"); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)) - // .startsWith( - // "Unable to mine with Stratum if mining is disabled. Either disable Stratum - // mining (remove --miner-stratum-enabled) or specify mining is enabled (--miner-enabled)"); } @Test @@ -159,21 +109,6 @@ public void blockProducingOptionsWarnsMinerShouldBeEnabled() { "42", "--miner-extra-data", "0x1122334455667788990011223344556677889900112233445566778899001122"); - // parseCommand( - // "--network", - // "dev", - // "--miner-coinbase", - // requestedCoinbase.toString(), - // "--min-gas-price", - // "42", - // "--miner-extra-data", - // "0x1122334455667788990011223344556677889900112233445566778899001122"); - // - // verifyOptionsConstraintLoggerCall( - // "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test @@ -197,28 +132,12 @@ public void blockProducingOptionsWarnsMinerShouldBeEnabledToml() throws IOExcept "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"), "--config-file", toml.toString()); - - // parseCommand("--config-file", toml.toString()); - // - // verifyOptionsConstraintLoggerCall( - // "--miner-enabled", "--miner-coinbase", "--min-gas-price", "--miner-extra-data"); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test public void blockProducingOptionsDoNotWarnWhenPoAQBFT() throws IOException { final Path genesisFileQBFT = createFakeGenesisFile(VALID_GENESIS_QBFT_POST_LONDON); - // parseCommand( - // "--genesis-file", - // genesisFileQBFT.toString(), - // "--min-gas-price", - // "42", - // "--miner-extra-data", - // "0x1122334455667788990011223344556677889900112233445566778899001122"); - internalTestSuccess( miningOpts -> verify(mockLogger, atMost(0)) @@ -233,14 +152,6 @@ public void blockProducingOptionsDoNotWarnWhenPoAQBFT() throws IOException { "--miner-extra-data", "0x1122334455667788990011223344556677889900112233445566778899001122"); } - // verify(mockLogger, atMost(0)) - // .warn( - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture()); - //// - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); @Test public void blockProducingOptionsDoNotWarnWhenPoAIBFT2() throws IOException { @@ -259,23 +170,6 @@ public void blockProducingOptionsDoNotWarnWhenPoAIBFT2() throws IOException { "42", "--miner-extra-data", "0x1122334455667788990011223344556677889900112233445566778899001122"); - // - // parseCommand( - // "--genesis-file", - // genesisFileIBFT2.toString(), - // "--min-gas-price", - // "42", - // "--miner-extra-data", - // "0x1122334455667788990011223344556677889900112233445566778899001122"); - // - // verify(mockLogger, atMost(0)) - // .warn( - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture()); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test @@ -295,22 +189,6 @@ public void blockProducingOptionsDoNotWarnWhenMergeEnabled() { "42", "--miner-extra-data", "0x1122334455667788990011223344556677889900112233445566778899001122"); - // parseCommand( - // "--miner-coinbase", - // requestedCoinbase.toString(), - // "--min-gas-price", - // "42", - // "--miner-extra-data", - // "0x1122334455667788990011223344556677889900112233445566778899001122"); - // - // verify(mockLogger, atMost(0)) - // .warn( - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture()); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test @@ -321,13 +199,6 @@ public void minGasPriceRequiresMainOption() { "0", "--network", "dev"); - // - // parseCommand("--min-gas-price", "0", "--network", "dev"); - // - // verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test @@ -337,13 +208,6 @@ public void minGasPriceRequiresMainOptionToml() throws IOException { miningOpt -> verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"), "--config-file", toml.toString()); - // - // parseCommand("--config-file", toml.toString()); - // - // verifyOptionsConstraintLoggerCall("--miner-enabled", "--min-gas-price"); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test @@ -361,17 +225,7 @@ public void minGasPriceDoesNotRequireMainOptionWhenPoAQBFT() throws IOException "--min-gas-price", "0"); } - // - // parseCommand("--genesis-file", genesisFileQBFT.toString(), "--min-gas-price", "0"); - // - // verify(mockLogger, atMost(0)) - // .warn( - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture()); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + @Test public void minGasPriceDoesNotRequireMainOptionWhenPoAIBFT2() throws IOException { final Path genesisFileIBFT2 = createFakeGenesisFile(VALID_GENESIS_IBFT2_POST_LONDON); @@ -387,16 +241,6 @@ public void minGasPriceDoesNotRequireMainOptionWhenPoAIBFT2() throws IOException genesisFileIBFT2.toString(), "--min-gas-price", "0"); - // parseCommand("--genesis-file", genesisFileIBFT2.toString(), "--min-gas-price", "0"); - // - // verify(mockLogger, atMost(0)) - // .warn( - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture(), - // stringArgumentCaptor.capture()); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); } @Test @@ -415,25 +259,6 @@ public void miningParametersAreCaptured() { "--miner-coinbase=" + requestedCoinbase.toString(), "--min-gas-price=15", "--miner-extra-data=" + extraDataString); - // parseCommand( - // "--miner-enabled", - // "--miner-coinbase=" + requestedCoinbase.toString(), - // "--min-gas-price=15", - // "--miner-extra-data=" + extraDataString); - // - // final ArgumentCaptor miningArg = - // ArgumentCaptor.forClass(MiningParameters.class); - // - // verify(mockControllerBuilder).miningParameters(miningArg.capture()); - // verify(mockControllerBuilder).build(); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - // assertThat(miningArg.getValue().getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); - // - // assertThat(miningArg.getValue().getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); - // assertThat(miningArg.getValue().getDynamic().getExtraData()) - // .isEqualTo(Bytes.fromHexString(extraDataString)); } @Test @@ -443,22 +268,6 @@ public void targetGasLimitIsEnabledWhenSpecified() { assertThat(miningParams.getDynamic().getTargetGasLimit().getAsLong()) .isEqualTo(10_000_000L), "--target-gas-limit=10000000"); - // parseCommand("--target-gas-limit=10000000"); - // - // @SuppressWarnings("unchecked") - // final ArgumentCaptor miningParametersArgumentCaptor = - // ArgumentCaptor.forClass(MiningParameters.class); - // - // verify(mockControllerBuilder).miningParameters(miningParametersArgumentCaptor.capture()); - // verify(mockControllerBuilder).build(); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - // - // assertThat( - // - // miningParametersArgumentCaptor.getValue().getDynamic().getTargetGasLimit().getAsLong()) - // .isEqualTo(10_000_000L); } @Test @@ -473,66 +282,31 @@ public void targetGasLimitIsDisabledWhenNotSpecified() { assertThat(gasLimitCalculatorArgumentCaptor.getValue()) .isEqualTo(GasLimitCalculator.constant()); }); - // parseCommand(); - // - // @SuppressWarnings("unchecked") - // final ArgumentCaptor gasLimitCalculatorArgumentCaptor = - // ArgumentCaptor.forClass(GasLimitCalculator.class); - // - // - // verify(mockControllerBuilder).gasLimitCalculator(gasLimitCalculatorArgumentCaptor.capture()); - // verify(mockControllerBuilder).build(); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - // - // assertThat(gasLimitCalculatorArgumentCaptor.getValue()) - // .isEqualTo(GasLimitCalculator.constant()); } @Test public void posBlockCreationMaxTimeDefaultValue() { internalTestSuccess( miningParams -> - assertThat(miningParams.getPosBlockCreationMaxTime()) + assertThat(miningParams.getUnstable().getPosBlockCreationMaxTime()) .isEqualTo(DEFAULT_POS_BLOCK_CREATION_MAX_TIME)); - // parseCommand(); - // - // assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(DEFAULT_POS_BLOCK_CREATION_MAX_TIME); } @Test public void posBlockCreationMaxTimeOption() { internalTestSuccess( - miningParams -> assertThat(miningParams.getPosBlockCreationMaxTime()).isEqualTo(7000L), + miningParams -> + assertThat(miningParams.getUnstable().getPosBlockCreationMaxTime()).isEqualTo(7000L), "--Xpos-block-creation-max-time", "7000"); - // parseCommand("--Xpos-block-creation-max-time", "7000"); - // assertThat(getPosBlockCreationMaxTimeValue()).isEqualTo(7000L); } - // private long getPosBlockCreationMaxTimeValue() { - // final ArgumentCaptor miningArg = - // ArgumentCaptor.forClass(MiningParameters.class); - // - // verify(mockControllerBuilder).miningParameters(miningArg.capture()); - // verify(mockControllerBuilder).build(); - // - // assertThat(commandOutput.toString(UTF_8)).isEmpty(); - // assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); - // return miningArg.getValue().getPosBlockCreationMaxTime(); - // } - @Test public void posBlockCreationMaxTimeOutOfAllowedRange() { internalTestFailure( "--Xpos-block-creation-max-time must be positive and ≤ 12000", "--Xpos-block-creation-max-time", "17000"); - // - // parseCommand("--Xpos-block-creation-max-time", "17000"); - // assertThat(commandErrorOutput.toString(UTF_8)) - // .contains("--Xpos-block-creation-max-time must be positive and ≤ 12000"); } @Override @@ -546,7 +320,8 @@ protected MiningParameters createCustomizedDomainObject() { .coinbase(Address.ZERO) .isMiningEnabled(true) .isStratumMiningEnabled(true) - .posBlockCreationMaxTime(1000) + .unstable( + ImmutableMiningParameters.Unstable.builder().posBlockCreationMaxTime(1000).build()) .build() .getDynamic() .setExtraData(Bytes.fromHexString("0xabc321")) diff --git a/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java b/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java index aed4b9c3f26..978b9b19764 100644 --- a/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java +++ b/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java @@ -160,7 +160,6 @@ public void setUp() { .getDynamic() .setMinTransactionGasPrice(Wei.ZERO) .toParameters(), - // new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), txPoolConfig, null); diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java index 63eb9cacdd6..1f4206b7ec8 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java @@ -52,7 +52,7 @@ public class CliqueBlockCreator extends AbstractBlockCreator { * @param coinbase the coinbase * @param extraDataCalculator the extra data calculator * @param transactionPool the pending transactions - * @param protocolContext the protocol miningParameters + * @param protocolContext the protocol context * @param protocolSchedule the protocol schedule * @param nodeKey the node key * @param parentHeader the parent header @@ -61,27 +61,21 @@ public class CliqueBlockCreator extends AbstractBlockCreator { public CliqueBlockCreator( final MiningParameters miningParameters, final Address coinbase, - // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, final NodeKey nodeKey, - // final Wei minTransactionGasPrice, - // final Double minBlockOccupancyRatio, final BlockHeader parentHeader, final EpochManager epochManager) { super( miningParameters, coinbase, __ -> Util.publicKeyToAddress(nodeKey.getPublicKey()), - // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - // minTransactionGasPrice, - // minBlockOccupancyRatio, parentHeader, Optional.empty()); this.nodeKey = nodeKey; diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java index 1f194349522..dab2c02f39a 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java @@ -83,15 +83,11 @@ public CliqueBlockMiner createMiner( new CliqueBlockCreator( miningParameters, localAddress, // TOOD(tmm): This can be removed (used for voting not coinbase). - // () -> - // miningContext.getTargetGasLimit().map(AtomicLong::longValue), this::calculateExtraData, transactionPool, protocolContext, protocolSchedule, nodeKey, - // miningContext.getMinTransactionGasPrice(), - // miningContext.getMinBlockOccupancyRatio(), header, epochManager); diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java index ad6c15b2f17..85cecc97a8a 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java @@ -151,14 +151,11 @@ public void proposerAddressCanBeExtractFromAConstructedBlock() { new CliqueBlockCreator( miningParameters, coinbase, - // () -> Optional.of(10_000_000L), parent -> extraData, createTransactionPool(), protocolContext, protocolSchedule, proposerNodeKey, - // Wei.ZERO, - // 0.8, blockchain.getChainHeadHeader(), epochManager); @@ -192,14 +189,11 @@ public void insertsValidVoteIntoConstructedBlock() { new CliqueBlockCreator( miningParameters, coinbase, - // () -> Optional.of(10_000_000L), parent -> extraData, createTransactionPool(), protocolContext, protocolSchedule, proposerNodeKey, - // Wei.ZERO, - // 0.8, blockchain.getChainHeadHeader(), epochManager); @@ -238,14 +232,11 @@ public void insertsNoVoteWhenAtEpoch() { new CliqueBlockCreator( miningParameters, coinbase, - // () -> Optional.of(10_000_000L), parent -> extraData, createTransactionPool(), protocolContext, protocolSchedule, proposerNodeKey, - // Wei.ZERO, - // 0.8, blockchain.getChainHeadHeader(), epochManager); diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java index 13c5ebbe7ba..8a6b49f31ed 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java @@ -120,13 +120,6 @@ public void extraDataCreatedOnEpochBlocksContainsValidators() { createTransactionPool(), proposerNodeKey, miningParameters, - - // new MiningParameters.Builder() - // .coinbase(AddressHelpers.ofValue(1)) - // .minTransactionGasPrice(Wei.ZERO) - // .extraData(vanityData) - // .miningEnabled(false) - // .build(), mock(CliqueBlockScheduler.class), new EpochManager(EPOCH_LENGTH)); @@ -170,12 +163,6 @@ public void extraDataForNonEpochBlocksDoesNotContainValidaors() { createTransactionPool(), proposerNodeKey, miningParameters, - // new MiningParameters.Builder() - // .coinbase(AddressHelpers.ofValue(1)) - // .minTransactionGasPrice(Wei.ZERO) - // .extraData(vanityData) - // .miningEnabled(false) - // .build(), mock(CliqueBlockScheduler.class), new EpochManager(EPOCH_LENGTH)); @@ -219,12 +206,6 @@ public void shouldUseLatestVanityData() { createTransactionPool(), proposerNodeKey, miningParameters, - // new MiningParameters.Builder() - // .coinbase(AddressHelpers.ofValue(1)) - // .minTransactionGasPrice(Wei.ZERO) - // .extraData(initialVanityData) - // .miningEnabled(false) - // .build(), mock(CliqueBlockScheduler.class), new EpochManager(EPOCH_LENGTH)); diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java index 3848d38bc77..692d64e7988 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java @@ -46,7 +46,7 @@ public class BftBlockCreator extends AbstractBlockCreator { * @param localAddress the local address * @param extraDataCalculator the extra data calculator * @param transactionPool the pending transactions - * @param protocolContext the protocol miningParameters + * @param protocolContext the protocol context * @param protocolSchedule the protocol schedule * @param parentHeader the parent header * @param bftExtraDataCodec the bft extra data codec @@ -55,26 +55,20 @@ public BftBlockCreator( final MiningParameters miningParameters, final ForksSchedule forksSchedule, final Address localAddress, - // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - // final Wei minTransactionGasPrice, - // final Double minBlockOccupancyRatio, final BlockHeader parentHeader, final BftExtraDataCodec bftExtraDataCodec) { super( miningParameters, localAddress, miningBeneficiaryCalculator(localAddress, forksSchedule), - // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - // minTransactionGasPrice, - // minBlockOccupancyRatio, parentHeader, Optional.empty()); this.bftExtraDataCodec = bftExtraDataCodec; diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java index 5d391bcbda9..b8d07bae4e8 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java @@ -54,7 +54,7 @@ public class BftBlockCreatorFactory { protected final MiningParameters miningParameters; private final TransactionPool transactionPool; - /** The Protocol miningParameters. */ + /** The Protocol context. */ protected final ProtocolContext protocolContext; /** The Protocol schedule. */ protected final ProtocolSchedule protocolSchedule; @@ -63,18 +63,11 @@ public class BftBlockCreatorFactory { private final Address localAddress; - /** The Vanity data. */ - // protected volatile Bytes vanityData; - // - // private volatile Wei minTransactionGasPrice; - // private volatile Double minBlockOccupancyRatio; - // private volatile Optional targetGasLimit; - /** * Instantiates a new Bft block creator factory. * * @param transactionPool the pending transactions - * @param protocolContext the protocol miningParameters + * @param protocolContext the protocol context * @param protocolSchedule the protocol schedule * @param forksSchedule the forks schedule * @param miningParams the mining params @@ -95,11 +88,7 @@ public BftBlockCreatorFactory( this.forksSchedule = forksSchedule; this.localAddress = localAddress; this.miningParameters = miningParams; - // this.minTransactionGasPrice = miningParams.getMinTransactionGasPrice(); - // this.minBlockOccupancyRatio = miningParams.getMinBlockOccupancyRatio(); - // this.vanityData = miningParams.getExtraData(); this.bftExtraDataCodec = bftExtraDataCodec; - // this.targetGasLimit = miningParams.getTargetGasLimit(); } /** @@ -114,13 +103,10 @@ public BlockCreator create(final BlockHeader parentHeader, final int round) { miningParameters, forksSchedule, localAddress, - // () -> targetGasLimit.map(AtomicLong::longValue), ph -> createExtraData(round, ph), transactionPool, protocolContext, protocolSchedule, - // minTransactionGasPrice, - // minBlockOccupancyRatio, parentHeader, bftExtraDataCodec); } diff --git a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java index 839ad0926b2..4892741ab7d 100644 --- a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java +++ b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java @@ -313,13 +313,6 @@ private static ControllerAndState createControllerAndFinalState( .setMinTransactionGasPrice(Wei.ZERO) .setExtraData(Bytes.wrap("Ibft Int tests".getBytes(UTF_8))) .toParameters(); - // - // new MiningParameters.Builder() - // .coinbase(AddressHelpers.ofValue(1)) - // .minTransactionGasPrice(Wei.ZERO) - // .extraData(Bytes.wrap("Ibft Int tests".getBytes(UTF_8))) - // .miningEnabled(true) - // .build(); final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions(); genesisConfigOptions.byzantiumBlock(0); diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java index e7424e11504..5d4fdb06db7 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java @@ -173,7 +173,6 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( miningParameters, forksSchedule, initialValidatorList.get(0), - // () -> Optional.of(10_000_000L), parent -> bftExtraDataEncoder.encode( new BftExtraData( @@ -185,8 +184,6 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( transactionPool, protContext, protocolSchedule, - // Wei.ZERO, - // 0.8, parentHeader, bftExtraDataEncoder); diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java index 27f688dc5ea..294e0943598 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java @@ -42,20 +42,17 @@ class MergeBlockCreator extends AbstractBlockCreator { * @param miningParameters the mining parameters * @param extraDataCalculator the extra data calculator * @param transactionPool the pending transactions - * @param protocolContext the protocol miningParameters + * @param protocolContext the protocol context * @param protocolSchedule the protocol schedule * @param miningBeneficiary the mining beneficiary * @param parentHeader the parent header */ public MergeBlockCreator( final MiningParameters miningParameters, - // final Address coinbase, - // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - // final Wei minTransactionGasPrice, final Address miningBeneficiary, final BlockHeader parentHeader, final Optional
depositContractAddress) { @@ -63,13 +60,10 @@ public MergeBlockCreator( miningParameters, miningBeneficiary, __ -> miningBeneficiary, - // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - // minTransactionGasPrice, - // TRY_FILL_BLOCK, parentHeader, depositContractAddress); } diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java index 3dfb74129b5..085510eb2a7 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java @@ -75,22 +75,17 @@ public class MergeCoordinator implements MergeMiningCoordinator, BadChainListene * to fill 100% of the block. */ private static final double TRY_FILL_BLOCK = 1.0; - /** The Target gas limit. */ - // protected final AtomicLong targetGasLimit; /** The Mining parameters. */ protected final MiningParameters miningParameters; /** The Merge block creator factory. */ protected final MergeBlockCreatorFactory mergeBlockCreatorFactory; - /** The Extra data. */ - // protected final AtomicReference extraData = - // new AtomicReference<>(Bytes.fromHexString("0x")); - /** The Merge miningParameters. */ + /** The Merge context. */ protected final MergeContext mergeContext; - /** The Protocol miningParameters. */ + /** The Protocol context. */ protected final ProtocolContext protocolContext; /** The Block builder executor. */ protected final ProposalBuilderExecutor blockBuilderExecutor; - /** The Backward sync miningParameters. */ + /** The Backward sync context. */ protected final BackwardSyncContext backwardSyncContext; /** The Protocol schedule. */ protected final ProtocolSchedule protocolSchedule; @@ -101,12 +96,12 @@ public class MergeCoordinator implements MergeMiningCoordinator, BadChainListene /** * Instantiates a new Merge coordinator. * - * @param protocolContext the protocol miningParameters + * @param protocolContext the protocol context * @param protocolSchedule the protocol schedule * @param blockBuilderExecutor the block builder executor * @param transactionPool the pending transactions * @param miningParams the mining params - * @param backwardSyncContext the backward sync miningParameters + * @param backwardSyncContext the backward sync context * @param depositContractAddress the address of the deposit contract */ public MergeCoordinator( @@ -130,24 +125,14 @@ public MergeCoordinator( this.miningParameters = miningParams; - // this.targetGasLimit = - // miningParameters - // .getTargetGasLimit() - // // TODO: revisit default target gas limit - // .orElse(new AtomicLong(30000000L)); - // this.extraData.set(miningParams.getExtraData()); - this.mergeBlockCreatorFactory = (parentHeader, address) -> new MergeBlockCreator( miningParameters, - // address.or(miningParameters::getCoinbase).orElse(Address.ZERO), - // () -> Optional.of(targetGasLimit.longValue()), parent -> miningParameters.getDynamic().getExtraData(), transactionPool, protocolContext, protocolSchedule, - // this.miningParameters.getMinTransactionGasPrice(), address.or(miningParameters::getCoinbase).orElse(Address.ZERO), parentHeader, depositContractAddress); @@ -158,11 +143,11 @@ public MergeCoordinator( /** * Instantiates a new Merge coordinator. * - * @param protocolContext the protocol miningParameters + * @param protocolContext the protocol context * @param protocolSchedule the protocol schedule * @param blockBuilderExecutor the block builder executor * @param miningParams the mining params - * @param backwardSyncContext the backward sync miningParameters + * @param backwardSyncContext the backward sync context * @param mergeBlockCreatorFactory the merge block creator factory */ public MergeCoordinator( @@ -177,20 +162,12 @@ public MergeCoordinator( this.protocolSchedule = protocolSchedule; this.blockBuilderExecutor = blockBuilderExecutor; this.mergeContext = protocolContext.getConsensusContext(MergeContext.class); - // this.miningParameters = miningParams; this.backwardSyncContext = backwardSyncContext; if (miningParams.getDynamic().getTargetGasLimit().isEmpty()) { miningParams.getDynamic().setTargetGasLimit(30000000L); } miningParams.getDynamic().setMinBlockOccupancyRatio(TRY_FILL_BLOCK); this.miningParameters = miningParams; - // - // - // this.targetGasLimit = - // miningParameters - // .getTargetGasLimit() - // // TODO: revisit default target gas limit - // .orElse(new AtomicLong(30000000L)); this.mergeBlockCreatorFactory = mergeBlockCreatorFactory; @@ -381,11 +358,12 @@ private void tryToBuildBetterBlock( LOG.debug( "Block creation started for payload id {}, remaining time is {}ms", payloadIdentifier, - miningParameters.getPosBlockCreationMaxTime()); + miningParameters.getUnstable().getPosBlockCreationMaxTime()); blockBuilderExecutor .buildProposal(() -> retryBlockCreationUntilUseful(payloadIdentifier, blockCreator)) - .orTimeout(miningParameters.getPosBlockCreationMaxTime(), TimeUnit.MILLISECONDS) + .orTimeout( + miningParameters.getUnstable().getPosBlockCreationMaxTime(), TimeUnit.MILLISECONDS) .whenComplete( (unused, throwable) -> { if (throwable != null) { @@ -411,7 +389,9 @@ private Void retryBlockCreationUntilUseful( final long lastDuration = System.currentTimeMillis() - lastStartAt; final long waitBeforeRepetition = Math.max( - 100, miningParameters.getPosBlockCreationRepetitionMinDuration() - lastDuration); + 100, + miningParameters.getUnstable().getPosBlockCreationRepetitionMinDuration() + - lastDuration); LOG.debug("Waiting {}ms before repeating block creation", waitBeforeRepetition); Thread.sleep(waitBeforeRepetition); } catch (final CancellationException | InterruptedException ce) { diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java index 431201a604a..aa611817b9c 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java @@ -134,7 +134,10 @@ public class MergeCoordinatorTest implements MergeGenesisConfigHelper { MiningParameters miningParameters = ImmutableMiningParameters.builder() .coinbase(coinbase) - .posBlockCreationRepetitionMinDuration(REPETITION_MIN_DURATION) + .unstable( + ImmutableMiningParameters.Unstable.builder() + .posBlockCreationRepetitionMinDuration(REPETITION_MIN_DURATION) + .build()) .build(); private MergeCoordinator coordinator; @@ -277,14 +280,10 @@ public void exceptionDuringBuildingBlockShouldNotBeInvalid() spy( new MergeBlockCreator( miningParameters, - // - // address.or(miningParameters::getCoinbase).orElse(Address.ZERO), - // () -> Optional.of(30000000L), parent -> Bytes.EMPTY, transactionPool, protocolContext, protocolSchedule, - // miningParameters.getMinTransactionGasPrice(), address.or(miningParameters::getCoinbase).orElse(Address.ZERO), parentHeader, Optional.empty())); @@ -551,7 +550,8 @@ public void shouldStopRetryBlockCreationIfTimeExpired() throws InterruptedExcept miningParameters = ImmutableMiningParameters.builder() .from(miningParameters) - .posBlockCreationMaxTime(100) + .unstable( + ImmutableMiningParameters.Unstable.builder().posBlockCreationMaxTime(100).build()) .build(); doAnswer( invocation -> { diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java index f2305ab83ca..4c9712c9b47 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java @@ -94,7 +94,6 @@ public void setUp() { CompletableFuture::runAsync, mockTransactionPool, ImmutableMiningParameters.builder().coinbase(coinbase).build(), - // new MiningParameters.Builder().coinbase(coinbase).build(), mock(BackwardSyncContext.class), Optional.empty()); mergeContext.setIsPostMerge(genesisState.getBlock().getHeader().getDifficulty()); 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 290dc3d5f5e..639551f3b2d 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 @@ -375,13 +375,6 @@ private static ControllerAndState createControllerAndFinalState( .setExtraData(Bytes.wrap("Qbft Int tests".getBytes(UTF_8))) .toParameters(); - // new MiningParameters.Builder() - // .coinbase(AddressHelpers.ofValue(1)) - // .minTransactionGasPrice(Wei.ZERO) - // .extraData(Bytes.wrap("Qbft Int tests".getBytes(UTF_8))) - // .miningEnabled(true) - // .build(); - final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions(); final Map qbftConfigValues = useValidatorContract diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java index ad4aafc579f..e1a265ae187 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java @@ -54,7 +54,6 @@ public void setUp() { .getDynamic() .setExtraData(Bytes.wrap("Qbft tests".getBytes(UTF_8))) .toParameters(); - // when(miningParams.getExtraData()).thenReturn(Bytes.wrap("Qbft tests".getBytes(UTF_8))); final MutableQbftConfigOptions qbftConfigOptions = new MutableQbftConfigOptions(JsonQbftConfigOptions.DEFAULT); diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java index 7234df9f70d..028e9727c9a 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java @@ -122,7 +122,6 @@ public void setUp() { .getDynamic() .setMinTransactionGasPrice(Wei.ZERO) .toParameters(), - // new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), new TransactionPoolMetrics(metricsSystem), TransactionPoolConfiguration.DEFAULT, null); diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java index af908d5520b..260e3674e6c 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java @@ -122,7 +122,6 @@ public void setUp() { .getDynamic() .setMinTransactionGasPrice(Wei.ZERO) .toParameters(), - // new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), new TransactionPoolMetrics(metricsSystem), TransactionPoolConfiguration.DEFAULT, null); diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java index b623817ae35..aacbc7b1269 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java @@ -81,16 +81,12 @@ public interface ExtraDataCalculator { protected final Address coinbase; private final MiningBeneficiaryCalculator miningBeneficiaryCalculator; - // protected final Supplier> targetGasLimitSupplier; - private final ExtraDataCalculator extraDataCalculator; private final TransactionPool transactionPool; protected final MiningParameters miningParameters; protected final ProtocolContext protocolContext; protected final ProtocolSchedule protocolSchedule; protected final BlockHeaderFunctions blockHeaderFunctions; - // private final Wei minTransactionGasPrice; - // private final Double minBlockOccupancyRatio; protected final BlockHeader parentHeader; private final Optional
depositContractAddress; @@ -100,25 +96,19 @@ protected AbstractBlockCreator( final MiningParameters miningParameters, final Address coinbase, final MiningBeneficiaryCalculator miningBeneficiaryCalculator, - // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - // final Wei minTransactionGasPrice, - // final Double minBlockOccupancyRatio, final BlockHeader parentHeader, final Optional
depositContractAddress) { this.miningParameters = miningParameters; this.coinbase = coinbase; this.miningBeneficiaryCalculator = miningBeneficiaryCalculator; - // this.targetGasLimitSupplier = targetGasLimitSupplier; this.extraDataCalculator = extraDataCalculator; this.transactionPool = transactionPool; this.protocolContext = protocolContext; this.protocolSchedule = protocolSchedule; - // this.minTransactionGasPrice = minTransactionGasPrice; - // this.minBlockOccupancyRatio = minBlockOccupancyRatio; this.parentHeader = parentHeader; this.depositContractAddress = depositContractAddress; blockHeaderFunctions = ScheduleBasedBlockHeaderFunctions.create(protocolSchedule); @@ -351,8 +341,6 @@ private TransactionSelectionResults selectTransactions( transactionPool, processableBlockHeader, transactionReceiptFactory, - // minTransactionGasPrice, - // minBlockOccupancyRatio, isCancelled::get, miningBeneficiary, blobGasPrice, diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java index 80dc651d9c7..08a0485463f 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java @@ -46,14 +46,7 @@ public abstract class AbstractMinerExecutor targetGasLimit; - protected final MiningParameters miningParameters; - private final AtomicBoolean stopped = new AtomicBoolean(false); protected AbstractMinerExecutor( @@ -65,11 +58,7 @@ protected AbstractMinerExecutor( this.protocolContext = protocolContext; this.protocolSchedule = protocolSchedule; this.transactionPool = transactionPool; - // this.extraData = miningParams.getExtraData(); - // this.minTransactionGasPrice = miningParams.getMinTransactionGasPrice(); this.blockScheduler = blockScheduler; - // this.minBlockOccupancyRatio = miningParams.getMinBlockOccupancyRatio(); - // this.targetGasLimit = miningParams.getTargetGasLimit(); this.miningParameters = miningParams; } @@ -120,10 +109,6 @@ public Wei getMinTransactionGasPrice() { public void changeTargetGasLimit(final Long newTargetGasLimit) { if (AbstractGasLimitSpecification.isValidTargetGasLimit(newTargetGasLimit)) { - // miningContext.getTargetGasLimit().ifPresentOrElse( - // existing -> existing.set(newTargetGasLimit), - // () -> miningContext.setTargetGasLimit(Optional.of(new - // AtomicLong(newTargetGasLimit)))); } else { throw new UnsupportedOperationException("Specified target gas limit is invalid"); } diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java index 2a7e4447aac..032ad0b8fed 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java @@ -41,26 +41,20 @@ public class PoWBlockCreator extends AbstractBlockCreator { public PoWBlockCreator( final MiningParameters miningParameters, final Address coinbase, - // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, final PoWSolver nonceSolver, - // final Wei minTransactionGasPrice, - // final Double minBlockOccupancyRatio, final BlockHeader parentHeader) { super( miningParameters, coinbase, __ -> coinbase, - // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - // minTransactionGasPrice, - // minBlockOccupancyRatio, parentHeader, Optional.empty()); diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java index 91a6d0576bb..3495f70504d 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java @@ -90,14 +90,11 @@ public PoWBlockMiner createMiner( new PoWBlockCreator( miningParameters, coinbase.orElse(Address.ZERO), - // () -> miningParameters.getTargetGasLimit()::get, parent -> miningParameters.getDynamic().getExtraData(), transactionPool, protocolContext, protocolSchedule, solver, - // miningParameters.getMinTransactionGasPrice(), - // miningParameters.getMinBlockOccupancyRatio(), parentHeader); return new PoWBlockMiner( diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java index d16952b4390..8204b3d9e43 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java @@ -27,8 +27,6 @@ public record BlockSelectionContext( MiningParameters miningParameters, GasCalculator gasCalculator, GasLimitCalculator gasLimitCalculator, - // Wei minTransactionGasPrice, - // Double minBlockOccupancyRatio, ProcessableBlockHeader processableBlockHeader, FeeMarket feeMarket, Wei blobGasPrice, diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java index bd05ad43f14..d36ba059a42 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java @@ -80,8 +80,6 @@ */ public class BlockTransactionSelector { private static final Logger LOG = LoggerFactory.getLogger(BlockTransactionSelector.class); - - // private final MiningParameters miningParameters; private final Supplier isCancelled; private final MainnetTransactionProcessor transactionProcessor; private final Blockchain blockchain; @@ -102,8 +100,6 @@ public BlockTransactionSelector( final TransactionPool transactionPool, final ProcessableBlockHeader processableBlockHeader, final AbstractBlockProcessor.TransactionReceiptFactory transactionReceiptFactory, - // final Wei minTransactionGasPrice, - // final Double minBlockOccupancyRatio, final Supplier isCancelled, final Address miningBeneficiary, final Wei blobGasPrice, @@ -111,7 +107,6 @@ public BlockTransactionSelector( final GasCalculator gasCalculator, final GasLimitCalculator gasLimitCalculator, final Optional transactionSelectorFactory) { - // this.miningParameters = miningParameters; this.transactionProcessor = transactionProcessor; this.blockchain = blockchain; this.worldState = worldState; @@ -122,8 +117,6 @@ public BlockTransactionSelector( miningParameters, gasCalculator, gasLimitCalculator, - // minTransactionGasPrice, - // minBlockOccupancyRatio, processableBlockHeader, feeMarket, blobGasPrice, diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java index a3a85e7606e..5b3a2836ad1 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java @@ -399,13 +399,10 @@ private AbstractBlockCreator createBlockCreator( miningParameters, Address.ZERO, __ -> Address.ZERO, - // () -> Optional.of(30_000_000L), __ -> Bytes.fromHexString("deadbeef"), transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), - // Wei.of(1L), - // 0d, blockchain.getChainHeadHeader(), depositContractAddress); } @@ -416,26 +413,20 @@ protected TestBlockCreator( final MiningParameters miningParameters, final Address coinbase, final MiningBeneficiaryCalculator miningBeneficiaryCalculator, - // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - // final Wei minTransactionGasPrice, - // final Double minBlockOccupancyRatio, final BlockHeader parentHeader, final Optional
depositContractAddress) { super( miningParameters, coinbase, miningBeneficiaryCalculator, - // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - // minTransactionGasPrice, - // minBlockOccupancyRatio, parentHeader, depositContractAddress); } 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 83107e1ce4c..2bd463ddd72 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 @@ -585,10 +585,8 @@ public TransactionSelectionResult evaluateTransactionPostProcessing( createBlockSelectorWithTxSelPlugin( transactionProcessor, blockHeader, - Wei.ZERO, miningBeneficiary, Wei.ZERO, - MIN_OCCUPANCY_80_PERCENT, transactionSelectorFactory); transactionPool.addRemoteTransactions( @@ -649,10 +647,8 @@ public TransactionSelectionResult evaluateTransactionPostProcessing( createBlockSelectorWithTxSelPlugin( transactionProcessor, blockHeader, - Wei.ZERO, miningBeneficiary, Wei.ZERO, - MIN_OCCUPANCY_80_PERCENT, transactionSelectorFactory); transactionPool.addRemoteTransactions(List.of(selected, notSelected, selected3)); @@ -732,10 +728,8 @@ protected BlockTransactionSelector createBlockSelector( protected BlockTransactionSelector createBlockSelectorWithTxSelPlugin( final MainnetTransactionProcessor transactionProcessor, final ProcessableBlockHeader blockHeader, - final Wei minGasPrice, final Address miningBeneficiary, final Wei blobGasPrice, - final double minBlockOccupancyRatio, final TransactionSelectorFactory transactionSelectorFactory) { final BlockTransactionSelector selector = new BlockTransactionSelector( @@ -746,8 +740,6 @@ protected BlockTransactionSelector createBlockSelectorWithTxSelPlugin( transactionPool, blockHeader, this::createReceipt, - // minGasPrice, - // minBlockOccupancyRatio, this::isCancelled, miningBeneficiary, blobGasPrice, diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java index 37d6fb3ab24..225414cfb8b 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java @@ -120,14 +120,11 @@ void createMainnetBlock1() throws IOException { new PoWBlockCreator( miningParameters, BLOCK_1_COINBASE, - // Optional::empty, parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), solver, - // Wei.ZERO, - // 0.8, executionContextTestFixture.getBlockchain().getChainHeadHeader()); // A Hashrate should not exist in the block creator prior to creating a block @@ -187,14 +184,11 @@ void createMainnetBlock1_fixedDifficulty1() { new PoWBlockCreator( miningParameters, BLOCK_1_COINBASE, - // Optional::empty, parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), solver, - // Wei.ZERO, - // 0.8, executionContextTestFixture.getBlockchain().getChainHeadHeader()); assertThat(blockCreator.createBlock(BLOCK_1_TIMESTAMP)).isNotNull(); @@ -246,14 +240,11 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsFalse() { new PoWBlockCreator( miningParameters, BLOCK_1_COINBASE, - // () -> Optional.of(10_000_000L), parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), solver, - // Wei.ZERO, - // 0.8, executionContextTestFixture.getBlockchain().getChainHeadHeader()); final MutableWorldState mutableWorldState = @@ -327,14 +318,11 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsTrue() { new PoWBlockCreator( miningParameters, BLOCK_1_COINBASE, - // () -> Optional.of(10_000_000L), parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), executionContextTestFixture.getProtocolSchedule(), solver, - // Wei.ZERO, - // 0.8, executionContextTestFixture.getBlockchain().getChainHeadHeader()); final MutableWorldState mutableWorldState = diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java index 0b31b9759c2..9e00bfc64f1 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java @@ -49,8 +49,6 @@ public class PoWMinerExecutorTest { @Test public void startingMiningWithoutCoinbaseThrowsException() { final MiningParameters miningParameters = ImmutableMiningParameters.builder().build(); - // new - // MiningParameters.Builder().coinbase(null).minTransactionGasPrice(Wei.of(1000)).build(); final TransactionPool transactionPool = createTransactionPool(miningParameters); diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMiningCoordinatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMiningCoordinatorTest.java index b60b1f2cd43..6efd63fbaed 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMiningCoordinatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMiningCoordinatorTest.java @@ -15,8 +15,8 @@ package org.hyperledger.besu.ethereum.blockcreation; import static org.assertj.core.api.Assertions.assertThat; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_LIMIT; -import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE_SEALERS_TTL; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_REMOTE_SEALERS_LIMIT; +import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_REMOTE_SEALERS_TTL; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java index 9f1ba9e5af1..9482c5c396c 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java @@ -29,6 +29,88 @@ @Value.Style(allParameters = true) @Value.Enclosing public interface MiningParameters { + + Optional
getCoinbase(); + + @Value.Default + default boolean isMiningEnabled() { + return false; + } + + @Value.Default + default boolean isStratumMiningEnabled() { + return false; + } + + @Value.Default + default String getStratumNetworkInterface() { + return "0.0.0.0"; + } + + @Value.Default + default int getStratumPort() { + return 8008; + } + + Optional> nonceGenerator(); + + @Value.Default + default Dynamic getDynamic() { + return new Dynamic(this); + } + + @Value.Default + default Unstable getUnstable() { + return Unstable.DEFAULT; + } + + @Value.Immutable + interface Unstable { + int DEFAULT_REMOTE_SEALERS_LIMIT = 1000; + long DEFAULT_REMOTE_SEALERS_TTL = Duration.ofMinutes(10).toMinutes(); + long DEFAULT_POW_JOB_TTL = Duration.ofMinutes(5).toMillis(); + int DEFAULT_MAX_OMMERS_DEPTH = 8; + long DEFAULT_POS_BLOCK_CREATION_MAX_TIME = Duration.ofSeconds(12).toMillis(); + long DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION = Duration.ofMillis(500).toMillis(); + + MiningParameters.Unstable DEFAULT = ImmutableMiningParameters.Unstable.builder().build(); + + @Value.Default + default int getRemoteSealersLimit() { + return DEFAULT_REMOTE_SEALERS_LIMIT; + } + + @Value.Default + default long getRemoteSealersTimeToLive() { + return DEFAULT_REMOTE_SEALERS_TTL; + } + + @Value.Default + default long getPowJobTimeToLive() { + return DEFAULT_POW_JOB_TTL; + } + + @Value.Default + default int getMaxOmmerDepth() { + return DEFAULT_MAX_OMMERS_DEPTH; + } + + @Value.Default + default long getPosBlockCreationMaxTime() { + return DEFAULT_POS_BLOCK_CREATION_MAX_TIME; + } + + @Value.Default + default long getPosBlockCreationRepetitionMinDuration() { + return DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; + } + + @Value.Default + default String getStratumExtranonce() { + return "080c"; + } + } + class Dynamic { public static final Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY; public static final Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); @@ -115,388 +197,4 @@ public String toString() { + '}'; } } - - // Double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; - int DEFAULT_REMOTE_SEALERS_LIMIT = 1000; - long DEFAULT_REMOTE_SEALERS_TTL = Duration.ofMinutes(10).toMinutes(); - long DEFAULT_POW_JOB_TTL = Duration.ofMinutes(5).toMillis(); - int DEFAULT_MAX_OMMERS_DEPTH = 8; - long DEFAULT_POS_BLOCK_CREATION_MAX_TIME = Duration.ofSeconds(12).toMillis(); - long DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION = Duration.ofMillis(500).toMillis(); - // private final Optional
coinbase; - // private final Optional targetGasLimit; - // private final Wei minTransactionGasPrice; - // private final Bytes extraData; - // private final boolean miningEnabled; - // private final boolean stratumMiningEnabled; - // private final String stratumNetworkInterface; - // private final int stratumPort; - // private final String stratumExtranonce; - // private final Optional> maybeNonceGenerator; - // private final Double minBlockOccupancyRatio; - // private final int remoteSealersLimit; - // private final long remoteSealersTimeToLive; - // private final long powJobTimeToLive; - // private final int maxOmmerDepth; - // private final long posBlockCreationMaxTime; - // private final long posBlockCreationRepetitionMinDuration; - - // private MiningParameters( - // final Address coinbase, - // final Long targetGasLimit, - // final Wei minTransactionGasPrice, - // final Bytes extraData, - // final boolean miningEnabled, - // final boolean stratumMiningEnabled, - // final String stratumNetworkInterface, - // final int stratumPort, - // final String stratumExtranonce, - // final Optional> maybeNonceGenerator, - // final Double minBlockOccupancyRatio, - // final int remoteSealersLimit, - // final long remoteSealersTimeToLive, - // final long powJobTimeToLive, - // final int maxOmmerDepth, - // final long posBlockCreationMaxTime, - // final long posBlockCreationRepetitionMinDuration) { - // this.coinbase = Optional.ofNullable(coinbase); - // this.targetGasLimit = Optional.ofNullable(targetGasLimit).map(AtomicLong::new); - // this.minTransactionGasPrice = minTransactionGasPrice; - // this.extraData = extraData; - // this.miningEnabled = miningEnabled; - // this.stratumMiningEnabled = stratumMiningEnabled; - // this.stratumNetworkInterface = stratumNetworkInterface; - // this.stratumPort = stratumPort; - // this.stratumExtranonce = stratumExtranonce; - // this.maybeNonceGenerator = maybeNonceGenerator; - // this.minBlockOccupancyRatio = minBlockOccupancyRatio; - // this.remoteSealersLimit = remoteSealersLimit; - // this.remoteSealersTimeToLive = remoteSealersTimeToLive; - // this.powJobTimeToLive = powJobTimeToLive; - // this.maxOmmerDepth = maxOmmerDepth; - // this.posBlockCreationMaxTime = posBlockCreationMaxTime; - // this.posBlockCreationRepetitionMinDuration = posBlockCreationRepetitionMinDuration; - // } - - @Value.Default - default Dynamic getDynamic() { - return new Dynamic(this); - } - - Optional
getCoinbase(); - // - // Optional getTargetGasLimit(); - // - // @Value.Default - // default Wei getMinTransactionGasPrice() { - // return Wei.ZERO; - // } - - // @Value.Default - // default Bytes getExtraData() { - // return DEFAULT_EXTRA_DATA; - // } - - @Value.Default - default boolean isMiningEnabled() { - return false; - } - - @Value.Default - default boolean isStratumMiningEnabled() { - return false; - } - - @Value.Default - default String getStratumNetworkInterface() { - return "0.0.0.0"; - } - - @Value.Default - default int getStratumPort() { - return 8008; - } - - @Value.Default - default String getStratumExtranonce() { - return "080c"; - } - // - // @Value.Default - // default Double getMinBlockOccupancyRatio() { - // return DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; - // } - - @Value.Default - default int getRemoteSealersLimit() { - return DEFAULT_REMOTE_SEALERS_LIMIT; - } - - @Value.Default - default long getRemoteSealersTimeToLive() { - return DEFAULT_REMOTE_SEALERS_TTL; - } - - @Value.Default - default long getPowJobTimeToLive() { - return DEFAULT_POW_JOB_TTL; - } - - @Value.Default - default int getMaxOmmerDepth() { - return DEFAULT_MAX_OMMERS_DEPTH; - } - - @Value.Default - default long getPosBlockCreationMaxTime() { - return DEFAULT_POS_BLOCK_CREATION_MAX_TIME; - } - - @Value.Default - default long getPosBlockCreationRepetitionMinDuration() { - return DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; - } - - Optional> nonceGenerator(); - - // - // @Override - // public boolean equals(final Object o) { - // if (this == o) return true; - // if (o == null || getClass() != o.getClass()) return false; - // MiningParameters that = (MiningParameters) o; - // return stratumPort == that.stratumPort - // && Objects.equals(coinbase, that.coinbase) - // && Objects.equals(targetGasLimit, that.targetGasLimit) - // && Objects.equals(minTransactionGasPrice, that.minTransactionGasPrice) - // && Objects.equals(extraData, that.extraData) - // && miningEnabled == that.miningEnabled - // && stratumMiningEnabled == that.stratumMiningEnabled - // && Objects.equals(stratumNetworkInterface, that.stratumNetworkInterface) - // && Objects.equals(stratumExtranonce, that.stratumExtranonce) - // && Objects.equals(minBlockOccupancyRatio, that.minBlockOccupancyRatio) - // && remoteSealersTimeToLive == that.remoteSealersTimeToLive - // && remoteSealersLimit == that.remoteSealersLimit - // && powJobTimeToLive == that.powJobTimeToLive - // && posBlockCreationMaxTime == that.posBlockCreationMaxTime - // && posBlockCreationRepetitionMinDuration == that.posBlockCreationRepetitionMinDuration; - // } - // - // @Override - // public int hashCode() { - // return Objects.hash( - // coinbase, - // targetGasLimit, - // minTransactionGasPrice, - // extraData, - // miningEnabled, - // stratumMiningEnabled, - // stratumNetworkInterface, - // stratumPort, - // stratumExtranonce, - // minBlockOccupancyRatio, - // remoteSealersLimit, - // remoteSealersTimeToLive, - // powJobTimeToLive, - // posBlockCreationMaxTime, - // posBlockCreationRepetitionMinDuration); - // } - // - // @Override - // public String toString() { - // return "MiningParameters{" - // + "coinbase=" - // + coinbase - // + ", targetGasLimit=" - // + targetGasLimit.map(Object::toString).orElse("null") - // + ", minTransactionGasPrice=" - // + minTransactionGasPrice - // + ", extraData=" - // + extraData - // + ", miningEnabled=" - // + miningEnabled - // + ", stratumMiningEnabled=" - // + stratumMiningEnabled - // + ", stratumNetworkInterface='" - // + stratumNetworkInterface - // + '\'' - // + ", stratumPort=" - // + stratumPort - // + ", stratumExtranonce='" - // + stratumExtranonce - // + '\'' - // + ", maybeNonceGenerator=" - // + maybeNonceGenerator - // + ", minBlockOccupancyRatio=" - // + minBlockOccupancyRatio - // + ", remoteSealersLimit=" - // + remoteSealersLimit - // + ", remoteSealersTimeToLive=" - // + remoteSealersTimeToLive - // + ", powJobTimeToLive=" - // + powJobTimeToLive - // + ", posBlockCreationMaxTime=" - // + posBlockCreationMaxTime - // + ", posBlockCreationRepetitionMinDuration=" - // + posBlockCreationRepetitionMinDuration - // + '}'; - // } - - // public static class Builder { - // - // private Address coinbase = null; - // private Long targetGasLimit = null; - // private Wei minTransactionGasPrice = Wei.ZERO; - // private Bytes extraData = Bytes.EMPTY; - // private boolean miningEnabled = false; - // private boolean stratumMiningEnabled = false; - // private String stratumNetworkInterface = "0.0.0.0"; - // private int stratumPort = 8008; - // private String stratumExtranonce = "080c"; - // private Iterable maybeNonceGenerator; - // private Double minBlockOccupancyRatio = 0.8; - // private int remoteSealersLimit = DEFAULT_REMOTE_SEALERS_LIMIT; - // private long remoteSealersTimeToLive = DEFAULT_REMOTE_SEALERS_TTL; - // private long powJobTimeToLive = DEFAULT_POW_JOB_TTL; - // private int maxOmmerDepth = DEFAULT_MAX_OMMERS_DEPTH; - // private long posBlockCreationMaxTime = DEFAULT_POS_BLOCK_CREATION_MAX_TIME; - // - // private long posBlockCreationRepetitionMinDuration = - // DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; - // - // public Builder() { - // // zero arg - // } - // - // public Builder(final MiningParameters existing) { - // existing.getCoinbase().ifPresent(cb -> this.coinbase = cb); - // existing - // .getTargetGasLimit() - // .map(AtomicLong::longValue) - // .ifPresent(gasLimit -> this.targetGasLimit = gasLimit); - // this.minTransactionGasPrice = existing.getMinTransactionGasPrice(); - // this.extraData = existing.getExtraData(); - // this.miningEnabled = existing.isMiningEnabled(); - // this.stratumMiningEnabled = existing.isStratumMiningEnabled(); - // this.stratumNetworkInterface = existing.getStratumNetworkInterface(); - // this.stratumPort = existing.getStratumPort(); - // this.stratumExtranonce = existing.getStratumExtranonce(); - // existing.getNonceGenerator().ifPresent(ng -> this.maybeNonceGenerator = ng); - // this.minBlockOccupancyRatio = existing.getMinBlockOccupancyRatio(); - // this.remoteSealersLimit = existing.getRemoteSealersLimit(); - // this.remoteSealersTimeToLive = existing.getRemoteSealersTimeToLive(); - // this.powJobTimeToLive = existing.getPowJobTimeToLive(); - // this.maxOmmerDepth = existing.getMaxOmmerDepth(); - // this.posBlockCreationMaxTime = existing.getPosBlockCreationMaxTime(); - // this.posBlockCreationRepetitionMinDuration = - // existing.getPosBlockCreationRepetitionMinDuration(); - // } - // - // public Builder coinbase(final Address address) { - // this.coinbase = address; - // return this; - // } - // - // public Builder targetGasLimit(final Long targetGasLimit) { - // this.targetGasLimit = targetGasLimit; - // return this; - // } - // - // public Builder minTransactionGasPrice(final Wei minTransactionGasPrice) { - // this.minTransactionGasPrice = minTransactionGasPrice; - // return this; - // } - // - // public Builder extraData(final Bytes extraData) { - // this.extraData = extraData; - // return this; - // } - // - // public Builder miningEnabled(final boolean miningEnabled) { - // this.miningEnabled = miningEnabled; - // return this; - // } - // - // public Builder stratumMiningEnabled(final boolean stratumMiningEnabled) { - // this.stratumMiningEnabled = stratumMiningEnabled; - // return this; - // } - // - // public Builder stratumNetworkInterface(final String stratumNetworkInterface) { - // this.stratumNetworkInterface = stratumNetworkInterface; - // return this; - // } - // - // public Builder stratumPort(final int stratumPort) { - // this.stratumPort = stratumPort; - // return this; - // } - // - // public Builder stratumExtranonce(final String stratumExtranonce) { - // this.stratumExtranonce = stratumExtranonce; - // return this; - // } - // - // public Builder maybeNonceGenerator(final Iterable maybeNonceGenerator) { - // this.maybeNonceGenerator = maybeNonceGenerator; - // return this; - // } - // - // public Builder minBlockOccupancyRatio(final Double minBlockOccupancyRatio) { - // this.minBlockOccupancyRatio = minBlockOccupancyRatio; - // return this; - // } - // - // public Builder remoteSealersLimit(final int remoteSealersLimit) { - // this.remoteSealersLimit = remoteSealersLimit; - // return this; - // } - // - // public Builder remoteSealersTimeToLive(final long remoteSealersTimeToLive) { - // this.remoteSealersTimeToLive = remoteSealersTimeToLive; - // return this; - // } - // - // public Builder powJobTimeToLive(final long powJobTimeToLive) { - // this.powJobTimeToLive = powJobTimeToLive; - // return this; - // } - // - // public Builder maxOmmerDepth(final int maxOmmerDepth) { - // this.maxOmmerDepth = maxOmmerDepth; - // return this; - // } - // - // public Builder posBlockCreationMaxTime(final long posBlockCreationMaxTime) { - // this.posBlockCreationMaxTime = posBlockCreationMaxTime; - // return this; - // } - // - // public Builder posBlockCreationRepetitionMinDuration( - // final long posBlockCreationRepetitionMinDuration) { - // this.posBlockCreationRepetitionMinDuration = posBlockCreationRepetitionMinDuration; - // return this; - // } - // - // public MiningParameters build() { - // return new MiningParameters( - // coinbase, - // targetGasLimit, - // minTransactionGasPrice, - // extraData, - // miningEnabled, - // stratumMiningEnabled, - // stratumNetworkInterface, - // stratumPort, - // stratumExtranonce, - // Optional.ofNullable(maybeNonceGenerator), - // minBlockOccupancyRatio, - // remoteSealersLimit, - // remoteSealersTimeToLive, - // powJobTimeToLive, - // maxOmmerDepth, - // posBlockCreationMaxTime, - // posBlockCreationRepetitionMinDuration); - // } - // } } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java index e38cde5c3f6..005348ac338 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java @@ -208,25 +208,19 @@ private TestBlockCreator( final MiningParameters miningParameters, final Address coinbase, final MiningBeneficiaryCalculator miningBeneficiaryCalculator, - // final Supplier> targetGasLimitSupplier, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - // final Wei minTransactionGasPrice, - // final Double minBlockOccupancyRatio, final BlockHeader parentHeader) { super( miningParameters, coinbase, miningBeneficiaryCalculator, - // targetGasLimitSupplier, extraDataCalculator, transactionPool, protocolContext, protocolSchedule, - // minTransactionGasPrice, - // minBlockOccupancyRatio, parentHeader, Optional.empty()); } @@ -252,13 +246,10 @@ static TestBlockCreator forHeader( miningParameters, Address.ZERO, __ -> Address.ZERO, - // () -> Optional.of(30_000_000L), __ -> Bytes.fromHexString("deadbeef"), transactionPool, protocolContext, protocolSchedule, - // Wei.of(1L), - // 0d, parentHeader); } diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java index dd99e0f4bc6..562ea0f939c 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java @@ -1121,8 +1121,6 @@ public void transactionMessagesGoToTheCorrectExecutor() { .getDynamic() .setMinTransactionGasPrice(Wei.ZERO) .toParameters(), - // new - // MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), TransactionPoolConfiguration.DEFAULT, null) .setEnabled(); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java index e05a4925913..1514de256a4 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java @@ -141,7 +141,6 @@ public void setupTest() { .getDynamic() .setMinTransactionGasPrice(Wei.ONE) .toParameters(), - // new MiningParameters.Builder().minTransactionGasPrice(Wei.ONE).build(), TransactionPoolConfiguration.DEFAULT, null); transactionPool.setEnabled(); 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 8480090c201..bbe4891c3d8 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 @@ -168,7 +168,6 @@ public boolean isMessagePermitted(final EnodeURL destinationEnode, final int cod .getDynamic() .setMinTransactionGasPrice(Wei.ZERO) .toParameters(), - // new MiningParameters.Builder().minTransactionGasPrice(Wei.ZERO).build(), TransactionPoolConfiguration.DEFAULT, null); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java index 6fea6dec4d9..afd80bf0adf 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java @@ -246,7 +246,6 @@ private void setupInitialSyncPhase(final boolean hasInitialSyncPhase) { .getDynamic() .setMinTransactionGasPrice(Wei.ONE) .toParameters(), - // new MiningParameters.Builder().minTransactionGasPrice(Wei.ONE).build(), ImmutableTransactionPoolConfiguration.builder() .txPoolMaxSize(1) .pendingTxRetentionPeriod(1) @@ -360,7 +359,6 @@ private TransactionPool createTransactionPool( .getDynamic() .setMinTransactionGasPrice(Wei.ONE) .toParameters(), - // new MiningParameters.Builder().minTransactionGasPrice(Wei.ONE).build(), ImmutableTransactionPoolConfiguration.builder() .txPoolImplementation(implementation) .txPoolMaxSize(1) diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java index 20736c0cde4..0a62de02505 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java @@ -72,14 +72,11 @@ private boolean mineNewBlock() { new PoWBlockCreator( miningParameters, context.getCoinbase(), - // () -> Optional.of(blockchain.getChainHeadHeader().getGasLimit()), header -> context.getExtraData(), context.getTransactionPool(), protocolContext, protocolSchedule, context.getEthHashSolver(), - // Wei.ZERO, - // 0.0, blockchain.getChainHeadHeader()); final Block block = blockCreator.createBlock(retesethClock.instant().getEpochSecond()).getBlock(); From 8f14dd3a3c54feff806efa5bad45ff0f3b00fc3b Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Fri, 13 Oct 2023 09:41:20 +0200 Subject: [PATCH 08/24] WIP Signed-off-by: Fabio Di Fabio --- .../blockcreation/PoWMinerExecutor.java | 14 ++++------- .../besu/ethereum/mainnet/PoWSolver.java | 24 +++++++++---------- 2 files changed, 16 insertions(+), 22 deletions(-) diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java index 3495f70504d..f72592e1194 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java @@ -36,8 +36,6 @@ public class PoWMinerExecutor extends AbstractMinerExecutor { protected boolean stratumMiningEnabled; protected final Iterable nonceGenerator; protected final EpochCalculator epochCalculator; - protected final long powJobTimeToLive; - protected final int maxOmmerDepth; public PoWMinerExecutor( final ProtocolContext protocolContext, @@ -45,15 +43,12 @@ public PoWMinerExecutor( final TransactionPool transactionPool, final MiningParameters miningParams, final AbstractBlockScheduler blockScheduler, - final EpochCalculator epochCalculator, - final long powJobTimeToLive, - final int maxOmmerDepth) { + final EpochCalculator epochCalculator +) { super(protocolContext, protocolSchedule, transactionPool, miningParams, blockScheduler); this.coinbase = miningParams.getCoinbase(); this.nonceGenerator = miningParams.nonceGenerator().orElse(new RandomNonceGenerator()); this.epochCalculator = epochCalculator; - this.powJobTimeToLive = powJobTimeToLive; - this.maxOmmerDepth = maxOmmerDepth; } @Override @@ -78,13 +73,12 @@ public PoWBlockMiner createMiner( protocolSchedule.getForNextBlockHeader(parentHeader, 0); final PoWSolver solver = new PoWSolver( + miningParameters, nonceGenerator, nextBlockProtocolSpec.getPoWHasher().get(), stratumMiningEnabled, ethHashObservers, - epochCalculator, - powJobTimeToLive, - maxOmmerDepth); + epochCalculator); final Function blockCreator = (header) -> new PoWBlockCreator( diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/PoWSolver.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/PoWSolver.java index 3248f304100..db547842413 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/PoWSolver.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/PoWSolver.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.mainnet; import org.hyperledger.besu.ethereum.chain.PoWObserver; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.util.Subscribers; import java.util.Optional; @@ -31,10 +32,11 @@ public class PoWSolver { - private final int maxOmmerDepth; +// private final int maxOmmerDepth; private static final Logger LOG = LoggerFactory.getLogger(PoWSolver.class); - private final long powJobTimeToLive; +// private final long powJobTimeToLive; + private final MiningParameters miningParameters; public static class PoWSolverJob { private final PoWSolverInputs inputs; @@ -86,28 +88,26 @@ PoWSolution getSolution() throws InterruptedException, ExecutionException { private final ExpiringMap currentJobs = new ExpiringMap<>(); public PoWSolver( + final MiningParameters miningParameters, final Iterable nonceGenerator, - final PoWHasher poWHasher, - final Boolean stratumMiningEnabled, - final Subscribers ethHashObservers, - final EpochCalculator epochCalculator, - final long powJobTimeToLive, - final int maxOmmerDepth) { + final PoWHasher poWHasher, + final Boolean stratumMiningEnabled, + final Subscribers ethHashObservers, + final EpochCalculator epochCalculator) { + this.miningParameters = miningParameters; this.nonceGenerator = nonceGenerator; this.poWHasher = poWHasher; this.stratumMiningEnabled = stratumMiningEnabled; this.ethHashObservers = ethHashObservers; ethHashObservers.forEach(observer -> observer.setSubmitWorkCallback(this::submitSolution)); this.epochCalculator = epochCalculator; - this.powJobTimeToLive = powJobTimeToLive; - this.maxOmmerDepth = maxOmmerDepth; } public PoWSolution solveFor(final PoWSolverJob job) throws InterruptedException, ExecutionException { currentJob = Optional.of(job); currentJobs.put( - job.getInputs().getPrePowHash(), job, System.currentTimeMillis() + powJobTimeToLive); + job.getInputs().getPrePowHash(), job, System.currentTimeMillis() + miningParameters.getUnstable().getPowJobTimeToLive()); if (stratumMiningEnabled) { LOG.debug( "solving with stratum miner for {} observers", ethHashObservers.getSubscriberCount()); @@ -183,7 +183,7 @@ public boolean submitSolution(final PoWSolution solution) { solution.getPowHash(), ommerCandidate.getInputs().getBlockNumber(), distanceToHead); - if (distanceToHead <= maxOmmerDepth) { + if (distanceToHead <= miningParameters.getUnstable().getMaxOmmerDepth()) { jobToTestWith = ommerCandidate; } else { LOG.debug("Discarded ommer solution as too far from head {}", distanceToHead); From 65bdabd80a09f94f987ad848adf32c753ce0590a Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Fri, 13 Oct 2023 13:28:34 +0200 Subject: [PATCH 09/24] WIP Signed-off-by: Fabio Di Fabio --- .../dsl/node/ProcessBesuNodeRunner.java | 3 +- .../BesuNodeConfigurationBuilder.java | 18 +- .../node/configuration/BesuNodeFactory.java | 12 +- .../bft/BftMiningAcceptanceTest.java | 12 +- .../org/hyperledger/besu/cli/BesuCommand.java | 23 +- .../cli/options/stable/MiningOptions.java | 45 ++- .../subcommands/blocks/BlocksSubCommand.java | 20 +- .../CliqueBesuControllerBuilder.java | 3 +- .../MainnetBesuControllerBuilder.java | 4 +- .../TransitionBesuControllerBuilder.java | 8 +- .../hyperledger/besu/PrivacyReorgTest.java | 4 +- .../org/hyperledger/besu/PrivacyTest.java | 4 +- .../java/org/hyperledger/besu/RunnerTest.java | 4 +- .../chainexport/RlpBlockExporterTest.java | 4 +- .../chainimport/JsonBlockImporterTest.java | 12 +- .../chainimport/RlpBlockImporterTest.java | 8 +- .../hyperledger/besu/cli/BesuCommandTest.java | 21 +- .../cli/options/stable/MiningOptionsTest.java | 28 +- .../controller/BesuControllerBuilderTest.java | 3 +- .../MergeBesuControllerBuilderTest.java | 2 +- .../TransitionControllerBuilderTest.java | 8 +- .../besu/services/BesuEventsImplTest.java | 8 +- .../blockcreation/CliqueMinerExecutor.java | 2 +- .../blockcreation/CliqueBlockCreatorTest.java | 48 ++-- .../CliqueMinerExecutorTest.java | 45 +-- .../blockcreation/BftBlockCreatorFactory.java | 11 +- .../ibft/support/TestContextBuilder.java | 14 +- .../blockcreation/BftBlockCreatorTest.java | 27 +- .../merge/blockcreation/MergeCoordinator.java | 20 +- .../blockcreation/MergeCoordinatorTest.java | 8 +- .../qbft/support/TestContextBuilder.java | 13 +- .../QbftBlockCreatorFactory.java | 3 +- .../QbftBlockCreatorFactoryTest.java | 9 +- .../EthGetFilterChangesIntegrationTest.java | 8 +- .../EthGetFilterChangesIntegrationTest.java | 8 +- .../blockcreation/AbstractBlockCreator.java | 5 +- .../blockcreation/AbstractMinerExecutor.java | 6 +- .../blockcreation/NoopMiningCoordinator.java | 2 +- .../blockcreation/PoWMinerExecutor.java | 13 +- .../txselection/BlockTransactionSelector.java | 9 +- .../BlockSizeTransactionSelector.java | 4 +- .../selectors/PriceTransactionSelector.java | 3 +- .../AbstractBlockCreatorTest.java | 13 +- .../AbstractBlockTransactionSelectorTest.java | 17 +- .../blockcreation/PoWBlockCreatorTest.java | 90 +++--- .../blockcreation/PoWMinerExecutorTest.java | 13 +- .../besu/ethereum/core/MiningParameters.java | 272 +++++++++++------- .../besu/ethereum/mainnet/PoWSolver.java | 24 +- .../bonsai/AbstractIsolationTests.java | 16 +- .../besu/ethereum/mainnet/PoWSolverTest.java | 77 +++-- .../eth/transactions/TransactionPool.java | 4 +- .../eth/manager/EthProtocolManagerTest.java | 9 +- .../ethtaskutils/AbstractMessageTaskTest.java | 9 +- ...GetPooledTransactionsFromPeerTaskTest.java | 2 +- .../AbstractTransactionPoolTest.java | 10 +- .../ethereum/eth/transactions/TestNode.java | 9 +- .../TransactionPoolFactoryTest.java | 15 +- .../ethereum/retesteth/RetestethContext.java | 26 +- .../retesteth/methods/TestMineBlocks.java | 15 +- plugin-api/build.gradle | 2 +- 60 files changed, 552 insertions(+), 583 deletions(-) diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java index aa8a93d27b7..f01c58549bc 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java @@ -108,8 +108,7 @@ public void startNode(final BesuNode node) { params.add(node.getMiningParameters().getStratumNetworkInterface()); params.add("--min-gas-price"); params.add( - Integer.toString( - node.getMiningParameters().getDynamic().getMinTransactionGasPrice().intValue())); + Integer.toString(node.getMiningParameters().getMinTransactionGasPrice().intValue())); params.add("--Xminer-remote-sealers-limit"); params.add( Integer.toString(node.getMiningParameters().getUnstable().getRemoteSealersLimit())); diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java index 88ba6f24861..287f4fe6cfe 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java @@ -22,7 +22,6 @@ import org.hyperledger.besu.cli.config.NetworkName; import org.hyperledger.besu.crypto.KeyPair; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration; import org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis; import org.hyperledger.besu.ethereum.api.jsonrpc.authentication.JwtAlgorithm; @@ -57,13 +56,7 @@ public class BesuNodeConfigurationBuilder { private String name; private Optional dataPath = Optional.empty(); private MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .isMiningEnabled(false) - .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.of(1000)) - .toParameters(); + ImmutableMiningParameters.builder().coinbase(AddressHelpers.ofValue(1)).build(); private JsonRpcConfiguration jsonRpcConfiguration = JsonRpcConfiguration.createDefault(); private JsonRpcConfiguration engineRpcConfiguration = JsonRpcConfiguration.createEngineDefault(); @@ -117,14 +110,7 @@ public BesuNodeConfigurationBuilder miningEnabled() { } public BesuNodeConfigurationBuilder miningEnabled(final boolean enabled) { - this.miningParameters = - ImmutableMiningParameters.builder() - .isMiningEnabled(enabled) - .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.of(1000)) - .toParameters(); + this.miningParameters = miningParameters.setMiningEnabled(enabled); this.jsonRpcConfiguration.addRpcApi(RpcApis.MINER.name()); return this; } diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java index d0bf27c0478..fc61b998a50 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java @@ -27,6 +27,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.InMemoryPrivacyStorageProvider; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; @@ -305,12 +306,13 @@ public BesuNode createNodeWithMultiTenantedPrivacy( final MiningParameters miningParameters = ImmutableMiningParameters.builder() - .isMiningEnabled(true) + .updatableInitValues( + UpdatableInitValues.builder() + .isMiningEnabled(true) + .minTransactionGasPrice(Wei.ZERO) + .build()) .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .toParameters(); + .build(); return create( new BesuNodeConfigurationBuilder() diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java index 45a93da92b1..b4732cc7113 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java @@ -18,6 +18,7 @@ import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.tests.acceptance.dsl.account.Account; import org.hyperledger.besu.tests.acceptance.dsl.blockchain.Amount; @@ -61,12 +62,13 @@ public void shouldMineOnSingleNodeWithFreeGas_Berlin() throws Exception { final BesuNode minerNode = nodeFactory.createNode(besu, "miner1"); final MiningParameters zeroGasMiningParams = ImmutableMiningParameters.builder() - .isMiningEnabled(true) + .updatableInitValues( + UpdatableInitValues.builder() + .isMiningEnabled(true) + .minTransactionGasPrice(Wei.ZERO) + .build()) .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .toParameters(); + .build(); minerNode.setMiningParameters(zeroGasMiningParams); cluster.start(minerNode); 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 8dea22cbb86..4790b4326cf 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -1424,7 +1424,7 @@ public void run() { // Need to create vertx after cmdline has been parsed, such that metricsSystem is configurable vertx = createVertx(createVertxOptions(metricsSystem.get())); - miningParameters = buildMiningParameters(); + miningParameters = getMiningParameters(); validateOptions(); configure(); @@ -1663,7 +1663,7 @@ private void validatePluginOptions() { "--privacy-marker-transaction-signing-key-file can not be used in conjunction with a plugin that specifies a PrivateMarkerTransactionFactory"); } - if (Wei.ZERO.compareTo(miningParameters.getDynamic().getMinTransactionGasPrice()) < 0 + if (Wei.ZERO.compareTo(getMiningParameters().getMinTransactionGasPrice()) < 0 && (privacyOptionGroup.privateMarkerTransactionSigningKeyPath == null && (privacyPluginService == null || privacyPluginService.getPrivateMarkerTransactionFactory() == null))) { @@ -2134,7 +2134,7 @@ public BesuControllerBuilder getControllerBuilder() { .transactionSelectorFactory(getTransactionSelectorFactory()) .pluginTransactionValidatorFactory(getPluginTransactionValidatorFactory()) .dataDirectory(dataDir()) - .miningParameters(miningParameters) + .miningParameters(getMiningParameters()) .transactionPoolConfiguration(buildTransactionPoolConfiguration()) .nodeKey(new NodeKey(securityModule())) .metricsSystem(metricsSystem.get()) @@ -2149,8 +2149,7 @@ public BesuControllerBuilder getControllerBuilder() { new PrunerConfiguration(pruningBlockConfirmations, pruningBlocksRetained)) .genesisConfigOverrides(genesisConfigOverrides) .gasLimitCalculator( - miningParameters != null - && miningParameters.getDynamic().getTargetGasLimit().isPresent() + getMiningParameters().getTargetGasLimit().isPresent() ? new FrontierTargetingGasLimitCalculator() : GasLimitCalculator.constant()) .requiredBlocks(requiredBlocks) @@ -2479,8 +2478,7 @@ private ApiConfiguration apiConfiguration() { .gasPriceBlocks(apiGasPriceBlocks) .gasPricePercentile(apiGasPricePercentile) .gasPriceMinSupplier( - miningParameters.getDynamic().getMinTransactionGasPrice().getAsBigInteger() - ::longValueExact) + getMiningParameters().getMinTransactionGasPrice().getAsBigInteger()::longValueExact) .gasPriceMax(apiGasPriceMax) .build(); } @@ -2816,8 +2814,11 @@ private TransactionPoolConfiguration buildTransactionPoolConfiguration() { .build(); } - private MiningParameters buildMiningParameters() { - return miningOptions.toDomainObject(); + private MiningParameters getMiningParameters() { + if (miningParameters == null) { + miningParameters = miningOptions.toDomainObject(); + } + return miningParameters; } private boolean isPruningEnabled() { @@ -3216,8 +3217,8 @@ private List getEffectivePorts() { effectivePorts, metricsOptionGroup.metricsPort, metricsOptionGroup.isMetricsEnabled); addPortIfEnabled( effectivePorts, - miningParameters.getStratumPort(), - miningParameters.isStratumMiningEnabled()); + getMiningParameters().getStratumPort(), + getMiningParameters().isStratumMiningEnabled()); return effectivePorts; } diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java index ad027521066..b1b87321af5 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java @@ -15,15 +15,15 @@ package org.hyperledger.besu.cli.options.stable; import static java.util.Arrays.asList; -import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_EXTRA_DATA; -import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; -import static org.hyperledger.besu.ethereum.core.MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_MAX_OMMERS_DEPTH; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POW_JOB_TTL; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_REMOTE_SEALERS_LIMIT; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_REMOTE_SEALERS_TTL; +import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_EXTRA_DATA; +import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; +import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE; import org.hyperledger.besu.cli.options.CLIOptions; import org.hyperledger.besu.cli.util.CommandLineUtils; @@ -236,11 +236,9 @@ static MiningOptions fromConfig(final MiningParameters miningParameters) { miningOptions.iStratumMiningEnabled = miningParameters.isStratumMiningEnabled(); miningOptions.stratumNetworkInterface = miningParameters.getStratumNetworkInterface(); miningOptions.stratumPort = miningParameters.getStratumPort(); - miningOptions.extraData = miningParameters.getDynamic().getExtraData(); - miningOptions.minTransactionGasPrice = - miningParameters.getDynamic().getMinTransactionGasPrice(); - miningOptions.minBlockOccupancyRatio = - miningParameters.getDynamic().getMinBlockOccupancyRatio(); + miningOptions.extraData = miningParameters.getExtraData(); + miningOptions.minTransactionGasPrice = miningParameters.getMinTransactionGasPrice(); + miningOptions.minBlockOccupancyRatio = miningParameters.getMinBlockOccupancyRatio(); miningOptions.unstableOptions.remoteSealersLimit = miningParameters.getUnstable().getRemoteSealersLimit(); miningOptions.unstableOptions.remoteSealersTimeToLive = @@ -257,18 +255,26 @@ static MiningOptions fromConfig(final MiningParameters miningParameters) { miningParameters.getUnstable().getPosBlockCreationRepetitionMinDuration(); miningParameters.getCoinbase().ifPresent(coinbase -> miningOptions.coinbase = coinbase); - miningParameters - .getDynamic() - .getTargetGasLimit() - .ifPresent(tgl -> miningOptions.targetGasLimit = tgl); + miningParameters.getTargetGasLimit().ifPresent(tgl -> miningOptions.targetGasLimit = tgl); return miningOptions; } @Override public MiningParameters toDomainObject() { + final var updatableInitValuesBuilder = + ImmutableMiningParameters.UpdatableInitValues.builder() + .isMiningEnabled(isMiningEnabled) + .extraData(extraData) + .minTransactionGasPrice(minTransactionGasPrice) + .minBlockOccupancyRatio(minBlockOccupancyRatio); + + if (targetGasLimit != null) { + updatableInitValuesBuilder.targetGasLimit(targetGasLimit); + } + final var miningParametersBuilder = ImmutableMiningParameters.builder() - .isMiningEnabled(isMiningEnabled) + .updatableInitValues(updatableInitValuesBuilder.build()) .isStratumMiningEnabled(iStratumMiningEnabled) .stratumNetworkInterface(stratumNetworkInterface) .stratumPort(stratumPort) @@ -288,18 +294,7 @@ public MiningParameters toDomainObject() { miningParametersBuilder.coinbase(coinbase); } - final var dynamicParameters = - miningParametersBuilder - .build() - .getDynamic() - .setExtraData(extraData) - .setMinBlockOccupancyRatio(minBlockOccupancyRatio) - .setMinTransactionGasPrice(minTransactionGasPrice); - - if (targetGasLimit != null) { - dynamicParameters.setTargetGasLimit(targetGasLimit); - } - return dynamicParameters.toParameters(); + return miningParametersBuilder.build(); } @Override diff --git a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java index 6198154887a..c8579c2263f 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java @@ -32,6 +32,7 @@ import org.hyperledger.besu.ethereum.blockcreation.IncrementingNonceGenerator; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.metrics.MetricsService; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; @@ -269,13 +270,14 @@ private MiningParameters getMiningParameters() { final Address coinbase = Address.ZERO; final Bytes extraData = Bytes.EMPTY; return ImmutableMiningParameters.builder() + .updatableInitValues( + UpdatableInitValues.builder() + .nonceGenerator(new IncrementingNonceGenerator(0)) + .extraData(extraData) + .minTransactionGasPrice(minTransactionGasPrice) + .build()) .coinbase(coinbase) - .nonceGenerator(new IncrementingNonceGenerator(0)) - .build() - .getDynamic() - .setExtraData(extraData) - .setMinTransactionGasPrice(minTransactionGasPrice) - .toParameters(); + .build(); } private void importJsonBlocks(final BesuController controller, final Path path) @@ -370,7 +372,11 @@ public void run() { } private BesuController createBesuController() { - return parentCommand.parentCommand.buildController(); + return parentCommand + .parentCommand + .getControllerBuilder() + .miningParameters(MiningParameters.newDefault()) + .build(); } private void exportRlpFormat(final BesuController controller) throws IOException { 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 6e6bff2b237..baad246a76b 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java @@ -34,7 +34,6 @@ import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.core.BlockHeader; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; @@ -149,6 +148,6 @@ protected CliqueContext createConsensusContext( @Override public MiningParameters getMiningParameterOverrides(final MiningParameters fromCli) { // Clique mines by default, reflect that with in the mining parameters: - return ImmutableMiningParameters.builder().from(fromCli).isMiningEnabled(true).build(); + return fromCli.setMiningEnabled(true); } } 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 1b352fcddfc..6f034e6f759 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java @@ -55,9 +55,7 @@ protected MiningCoordinator createMiningCoordinator( MainnetBlockHeaderValidator.MINIMUM_SECONDS_SINCE_PARENT, MainnetBlockHeaderValidator.TIMESTAMP_TOLERANCE_S, clock), - epochCalculator, - miningParameters.getUnstable().getPowJobTimeToLive(), - miningParameters.getUnstable().getMaxOmmerDepth()); + epochCalculator); final PoWMiningCoordinator miningCoordinator = new PoWMiningCoordinator( 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 5c18b1291aa..d4541d91b9c 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java @@ -32,7 +32,6 @@ import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; @@ -135,10 +134,7 @@ protected MiningCoordinator createMiningCoordinator( transitionProtocolSchedule.getPreMergeSchedule(), protocolContext, transactionPool, - ImmutableMiningParameters.builder() - .from(miningParameters) - .isMiningEnabled(false) - .build(), + MiningParameters.MINING_DISABLED, syncState, ethProtocolManager), mergeBesuControllerBuilder.createTransitionMiningCoordinator( @@ -281,7 +277,7 @@ private void initTransitionWatcher( } }); - // initialize our merge miningParameters merge status before we would start either + // initialize our merge context merge status before we would start either Blockchain blockchain = protocolContext.getBlockchain(); blockchain .getTotalDifficultyByHash(blockchain.getChainHeadHash()) diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java index 97aa8ff44f7..276740fbfed 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java @@ -39,9 +39,9 @@ import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockDataGenerator; import org.hyperledger.besu.ethereum.core.Difficulty; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.InMemoryPrivacyStorageProvider; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; @@ -187,7 +187,7 @@ public void setUp() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) + .miningParameters(MiningParameters.newDefault()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .dataDirectory(folder) diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java index f587faab4f2..c71d44284fb 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java @@ -30,8 +30,8 @@ import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -111,7 +111,7 @@ private BesuController setUpControllerWithPrivacyEnabled(final boolean flexibleE .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) + .miningParameters(MiningParameters.newDefault()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .dataDirectory(dataDir) diff --git a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java index e7166133672..43a4d2cd963 100644 --- a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java +++ b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java @@ -40,8 +40,8 @@ import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockImporter; import org.hyperledger.besu.ethereum.core.BlockSyncTestUtils; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -448,7 +448,7 @@ private BesuController getController( .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .dataDirectory(dataDir) .networkId(NETWORK_ID) - .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) + .miningParameters(MiningParameters.newDefault()) .nodeKey(nodeKey) .storageProvider(storageProvider) .metricsSystem(metricsSystem) 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 94266aa7d81..89e1b255479 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java @@ -27,8 +27,8 @@ import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -91,7 +91,7 @@ private static BesuController createController() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) + .miningParameters(MiningParameters.newDefault()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) 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 505f4f5d7fc..de338b78549 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java @@ -30,6 +30,7 @@ import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Transaction; @@ -422,11 +423,12 @@ protected BesuController createController(final GenesisConfigFile genesisConfigF .networkId(BigInteger.valueOf(10)) .miningParameters( ImmutableMiningParameters.builder() - .isMiningEnabled(true) - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .toParameters()) + .updatableInitValues( + UpdatableInitValues.builder() + .isMiningEnabled(true) + .minTransactionGasPrice(Wei.ZERO) + .build()) + .build()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) 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 a1e4374ee2e..f9d543aca9f 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java @@ -22,8 +22,8 @@ import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.ethereum.GasLimitCalculator; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -67,7 +67,7 @@ public void blockImport() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) + .miningParameters(MiningParameters.newDefault()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) @@ -100,7 +100,7 @@ public void blockImportRejectsBadPow() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) + .miningParameters(MiningParameters.newDefault()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) @@ -130,7 +130,7 @@ public void blockImportCanSkipPow() throws IOException { .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) .storageProvider(new InMemoryKeyValueStorageProvider()) .networkId(BigInteger.ONE) - .miningParameters(ImmutableMiningParameters.builder().isMiningEnabled(false).build()) + .miningParameters(MiningParameters.newDefault()) .nodeKey(NodeKeyUtils.generate()) .metricsSystem(new NoOpMetricsSystem()) .privacyParameters(PrivacyParameters.DEFAULT) 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 a2401fd2b27..1d4dc768455 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -276,9 +276,8 @@ public void callingBesuCommandWithoutOptionsMustSyncWithDefaultValues() { assertThat(syncConfigurationCaptor.getValue().getSyncMode()).isEqualTo(SyncMode.FAST); assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); assertThat(miningArg.getValue().getCoinbase()).isEqualTo(Optional.empty()); - assertThat(miningArg.getValue().getDynamic().getMinTransactionGasPrice()) - .isEqualTo(Wei.of(1000)); - assertThat(miningArg.getValue().getDynamic().getExtraData()).isEqualTo(Bytes.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); } @@ -903,14 +902,8 @@ public void envVariableOverridesValueFromConfigFile() { verify(mockControllerBuilder) .miningParameters( ImmutableMiningParameters.builder() - .isMiningEnabled(false) .coinbase(Address.fromHexString(expectedCoinbase)) - .build() - .getDynamic() - .setMinTransactionGasPrice( - MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE) - .setExtraData(MiningParameters.Dynamic.DEFAULT_EXTRA_DATA) - .toParameters()); + .build()); } @Test @@ -923,14 +916,8 @@ public void cliOptionOverridesEnvVariableAndConfig() { verify(mockControllerBuilder) .miningParameters( ImmutableMiningParameters.builder() - .isMiningEnabled(false) .coinbase(Address.fromHexString(expectedCoinbase)) - .build() - .getDynamic() - .setMinTransactionGasPrice( - MiningParameters.Dynamic.DEFAULT_MIN_TRANSACTION_GAS_PRICE) - .setExtraData(MiningParameters.Dynamic.DEFAULT_EXTRA_DATA) - .toParameters()); + .build()); } @Test diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java index bb50310d596..5fe050067ad 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java @@ -24,6 +24,8 @@ import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.Unstable; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import java.io.IOException; @@ -251,9 +253,8 @@ public void miningParametersAreCaptured() { internalTestSuccess( miningParams -> { assertThat(miningParams.getCoinbase()).isEqualTo(Optional.of(requestedCoinbase)); - assertThat(miningParams.getDynamic().getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); - assertThat(miningParams.getDynamic().getExtraData()) - .isEqualTo(Bytes.fromHexString(extraDataString)); + assertThat(miningParams.getMinTransactionGasPrice()).isEqualTo(Wei.of(15)); + assertThat(miningParams.getExtraData()).isEqualTo(Bytes.fromHexString(extraDataString)); }, "--miner-enabled", "--miner-coinbase=" + requestedCoinbase.toString(), @@ -265,8 +266,7 @@ public void miningParametersAreCaptured() { public void targetGasLimitIsEnabledWhenSpecified() { internalTestSuccess( miningParams -> - assertThat(miningParams.getDynamic().getTargetGasLimit().getAsLong()) - .isEqualTo(10_000_000L), + assertThat(miningParams.getTargetGasLimit().getAsLong()).isEqualTo(10_000_000L), "--target-gas-limit=10000000"); } @@ -311,22 +311,22 @@ public void posBlockCreationMaxTimeOutOfAllowedRange() { @Override protected MiningParameters createDefaultDomainObject() { - return ImmutableMiningParameters.builder().build(); + return MiningParameters.newDefault(); } @Override protected MiningParameters createCustomizedDomainObject() { return ImmutableMiningParameters.builder() + .updatableInitValues( + UpdatableInitValues.builder() + .isMiningEnabled(true) + .extraData(Bytes.fromHexString("0xabc321")) + .minBlockOccupancyRatio(0.5) + .build()) .coinbase(Address.ZERO) - .isMiningEnabled(true) .isStratumMiningEnabled(true) - .unstable( - ImmutableMiningParameters.Unstable.builder().posBlockCreationMaxTime(1000).build()) - .build() - .getDynamic() - .setExtraData(Bytes.fromHexString("0xabc321")) - .setMinBlockOccupancyRatio(0.5) - .toParameters(); + .unstable(Unstable.builder().posBlockCreationMaxTime(1000).build()) + .build(); } @Override diff --git a/besu/src/test/java/org/hyperledger/besu/controller/BesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/BesuControllerBuilderTest.java index c7c6466e602..a24479e8617 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/BesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/BesuControllerBuilderTest.java @@ -84,7 +84,6 @@ public class BesuControllerBuilderTest { @Mock CheckpointConfigOptions checkpointConfigOptions; @Mock SynchronizerConfiguration synchronizerConfiguration; @Mock EthProtocolConfiguration ethProtocolConfiguration; - @Mock MiningParameters miningParameters; @Mock PrivacyParameters privacyParameters; @Mock Clock clock; @Mock StorageProvider storageProvider; @@ -95,6 +94,8 @@ public class BesuControllerBuilderTest { @Mock WorldStatePreimageStorage worldStatePreimageStorage; private final TransactionPoolConfiguration poolConfiguration = TransactionPoolConfiguration.DEFAULT; + private final MiningParameters miningParameters = MiningParameters.newDefault(); + private final ObservableMetricsSystem observableMetricsSystem = new NoOpMetricsSystem(); BigInteger networkId = BigInteger.ONE; diff --git a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java index 275edcf64f7..33a539f8bc2 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java @@ -147,7 +147,7 @@ public void setup() { when(worldStatePreimageStorage.updater()) .thenReturn(mock(WorldStatePreimageStorage.Updater.class)); when(worldStateStorage.updater()).thenReturn(mock(WorldStateStorage.Updater.class)); - when(miningParameters.getDynamic().getTargetGasLimit()).thenReturn(OptionalLong.empty()); + when(miningParameters.getTargetGasLimit()).thenReturn(OptionalLong.empty()); besuControllerBuilder = visitWithMockConfigs(new MergeBesuControllerBuilder()); } diff --git a/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java index d5c7a95d4ba..6d07e414874 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java @@ -35,6 +35,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; @@ -100,7 +101,7 @@ public void setup() { .thenReturn(mock(CliqueContext.class)); when(protocolContext.getConsensusContext(PostMergeContext.class)).thenReturn(mergeContext); when(protocolContext.getConsensusContext(MergeContext.class)).thenReturn(mergeContext); - miningParameters = ImmutableMiningParameters.builder().isMiningEnabled(false).build(); + miningParameters = MiningParameters.newDefault(); } @Test @@ -119,7 +120,10 @@ public void assertPoWIsNotMiningPreMerge() { @Test public void assertPowMiningPreMerge() { - miningParameters = ImmutableMiningParameters.builder().isMiningEnabled(true).build(); + miningParameters = + ImmutableMiningParameters.builder() + .updatableInitValues(UpdatableInitValues.builder().isMiningEnabled(true).build()) + .build(); var transCoordinator = buildTransitionCoordinator(powBuilder, postMergeBuilder); assertThat(transCoordinator.isMiningBeforeMerge()).isTrue(); } diff --git a/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java b/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java index 978b9b19764..7fcff4ced88 100644 --- a/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java +++ b/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java @@ -34,6 +34,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionTestFixture; @@ -156,10 +157,9 @@ public void setUp() { new NoOpMetricsSystem(), syncState, ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .toParameters(), + .updatableInitValues( + UpdatableInitValues.builder().minTransactionGasPrice(Wei.ZERO).build()) + .build(), txPoolConfig, null); diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java index dab2c02f39a..ac06e776e44 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java @@ -118,7 +118,7 @@ Bytes calculateExtraData(final BlockHeader parentHeader) { final Bytes vanityDataToInsert = ConsensusHelpers.zeroLeftPad( - miningParameters.getDynamic().getExtraData(), CliqueExtraData.EXTRA_VANITY_LENGTH); + miningParameters.getExtraData(), CliqueExtraData.EXTRA_VANITY_LENGTH); // Building ON TOP of canonical head, if the next block is epoch, include validators. if (epochManager.isEpochBlock(parentHeader.getNumber() + 1)) { diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java index 85cecc97a8a..787eff3bda6 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java @@ -136,16 +136,7 @@ public void proposerAddressCanBeExtractFromAConstructedBlock() { final Address coinbase = AddressHelpers.ofValue(1); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .coinbase(coinbase) - .build() - .getDynamic() - .setExtraData(extraData) - .setTargetGasLimit(10_000_000L) - .setMinTransactionGasPrice(Wei.ZERO) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); + final MiningParameters miningParameters = createMiningParameters(extraData, coinbase); final CliqueBlockCreator blockCreator = new CliqueBlockCreator( @@ -174,16 +165,7 @@ public void insertsValidVoteIntoConstructedBlock() { when(voteProvider.getVoteAfterBlock(any(), any())) .thenReturn(Optional.of(new ValidatorVote(VoteType.ADD, coinbase, a1))); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .coinbase(coinbase) - .build() - .getDynamic() - .setExtraData(extraData) - .setTargetGasLimit(10_000_000L) - .setMinTransactionGasPrice(Wei.ZERO) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); + final MiningParameters miningParameters = createMiningParameters(extraData, coinbase); final CliqueBlockCreator blockCreator = new CliqueBlockCreator( @@ -217,16 +199,7 @@ public void insertsNoVoteWhenAtEpoch() { when(mockVoteProvider.getVoteAfterBlock(any(), any())) .thenReturn(Optional.of(new ValidatorVote(VoteType.ADD, coinbase, a1))); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .coinbase(coinbase) - .build() - .getDynamic() - .setExtraData(extraData) - .setTargetGasLimit(10_000_000L) - .setMinTransactionGasPrice(Wei.ZERO) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); + final MiningParameters miningParameters = createMiningParameters(extraData, coinbase); final CliqueBlockCreator blockCreator = new CliqueBlockCreator( @@ -269,4 +242,19 @@ private TransactionPool createTransactionPool() { transactionPool.setEnabled(); return transactionPool; } + + private static MiningParameters createMiningParameters( + final Bytes extraData, final Address coinbase) { + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .updatableInitValues( + ImmutableMiningParameters.UpdatableInitValues.builder() + .extraData(extraData) + .targetGasLimit(10_000_000L) + .minTransactionGasPrice(Wei.ZERO) + .build()) + .coinbase(coinbase) + .build(); + return miningParameters; + } } diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java index 8a6b49f31ed..6bd197cd908 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java @@ -38,6 +38,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -102,16 +103,7 @@ public void setup() { public void extraDataCreatedOnEpochBlocksContainsValidators() { final Bytes vanityData = generateRandomVanityData(); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .isMiningEnabled(false) - .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setExtraData(vanityData) - .setMinTransactionGasPrice(Wei.ZERO) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); + final MiningParameters miningParameters = createMiningParameters(vanityData); final CliqueMinerExecutor executor = new CliqueMinerExecutor( @@ -145,16 +137,7 @@ public void extraDataCreatedOnEpochBlocksContainsValidators() { public void extraDataForNonEpochBlocksDoesNotContainValidaors() { final Bytes vanityData = generateRandomVanityData(); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .isMiningEnabled(false) - .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setExtraData(vanityData) - .setMinTransactionGasPrice(Wei.ZERO) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); + final MiningParameters miningParameters = createMiningParameters(vanityData); final CliqueMinerExecutor executor = new CliqueMinerExecutor( @@ -188,16 +171,7 @@ public void shouldUseLatestVanityData() { final Bytes initialVanityData = generateRandomVanityData(); final Bytes modifiedVanityData = generateRandomVanityData(); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .isMiningEnabled(false) - .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setExtraData(initialVanityData) - .setMinTransactionGasPrice(Wei.ZERO) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); + final MiningParameters miningParameters = createMiningParameters(initialVanityData); final CliqueMinerExecutor executor = new CliqueMinerExecutor( @@ -259,4 +233,15 @@ private Bytes generateRandomVanityData() { random.nextBytes(vanityData); return Bytes.wrap(vanityData); } + + private static MiningParameters createMiningParameters(final Bytes vanityData) { + return ImmutableMiningParameters.builder() + .updatableInitValues( + UpdatableInitValues.builder() + .extraData(vanityData) + .minTransactionGasPrice(Wei.ZERO) + .build()) + .coinbase(AddressHelpers.ofValue(1)) + .build(); + } } diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java index b8d07bae4e8..528f4e72062 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java @@ -118,7 +118,7 @@ public BlockCreator create(final BlockHeader parentHeader, final int round) { */ public void setExtraData(final Bytes extraData) { - miningParameters.getDynamic().setExtraData(extraData.copy()); + miningParameters.setExtraData(extraData.copy()); } /** @@ -127,7 +127,7 @@ public void setExtraData(final Bytes extraData) { * @param minTransactionGasPrice the min transaction gas price */ public void setMinTransactionGasPrice(final Wei minTransactionGasPrice) { - miningParameters.getDynamic().setMinTransactionGasPrice(minTransactionGasPrice); + miningParameters.setMinTransactionGasPrice(minTransactionGasPrice); } /** @@ -136,7 +136,7 @@ public void setMinTransactionGasPrice(final Wei minTransactionGasPrice) { * @return the min transaction gas price */ public Wei getMinTransactionGasPrice() { - return miningParameters.getDynamic().getMinTransactionGasPrice(); + return miningParameters.getMinTransactionGasPrice(); } /** @@ -161,8 +161,7 @@ public Bytes createExtraData(final int round, final BlockHeader parentHeader) { final BftExtraData extraData = new BftExtraData( ConsensusHelpers.zeroLeftPad( - miningParameters.getDynamic().getExtraData(), - BftExtraDataCodec.EXTRA_VANITY_LENGTH), + miningParameters.getExtraData(), BftExtraDataCodec.EXTRA_VANITY_LENGTH), Collections.emptyList(), toVote(proposal), round, @@ -178,7 +177,7 @@ public Bytes createExtraData(final int round, final BlockHeader parentHeader) { */ public void changeTargetGasLimit(final Long newTargetGasLimit) { if (AbstractGasLimitSpecification.isValidTargetGasLimit(newTargetGasLimit)) { - miningParameters.getDynamic().setTargetGasLimit(newTargetGasLimit); + miningParameters.setTargetGasLimit(newTargetGasLimit); } else { throw new UnsupportedOperationException("Specified target gas limit is invalid"); } diff --git a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java index 4892741ab7d..88eba5b8930 100644 --- a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java +++ b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java @@ -78,6 +78,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -306,13 +307,14 @@ private static ControllerAndState createControllerAndFinalState( final MiningParameters miningParams = ImmutableMiningParameters.builder() - .isMiningEnabled(true) + .updatableInitValues( + UpdatableInitValues.builder() + .isMiningEnabled(true) + .minTransactionGasPrice(Wei.ZERO) + .extraData(Bytes.wrap("Ibft Int tests".getBytes(UTF_8))) + .build()) .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .setExtraData(Bytes.wrap("Ibft Int tests".getBytes(UTF_8))) - .toParameters(); + .build(); final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions(); genesisConfigOptions.byzantiumBlock(0); diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java index 5d4fdb06db7..14c1eddc70f 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java @@ -42,6 +42,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -153,20 +154,20 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( final MiningParameters miningParameters = ImmutableMiningParameters.builder() + .updatableInitValues( + UpdatableInitValues.builder() + .extraData( + bftExtraDataEncoder.encode( + new BftExtraData( + Bytes.wrap(new byte[32]), + Collections.emptyList(), + Optional.empty(), + 0, + initialValidatorList))) + .minTransactionGasPrice(Wei.ZERO) + .build()) .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setExtraData( - bftExtraDataEncoder.encode( - new BftExtraData( - Bytes.wrap(new byte[32]), - Collections.emptyList(), - Optional.empty(), - 0, - initialValidatorList))) - .setMinTransactionGasPrice(Wei.ZERO) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); + .build(); final BftBlockCreator blockCreator = new BftBlockCreator( diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java index 085510eb2a7..308fd9b4aba 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java @@ -118,10 +118,10 @@ public MergeCoordinator( this.mergeContext = protocolContext.getConsensusContext(MergeContext.class); this.backwardSyncContext = backwardSyncContext; - if (miningParams.getDynamic().getTargetGasLimit().isEmpty()) { - miningParams.getDynamic().setTargetGasLimit(30000000L); + if (miningParams.getTargetGasLimit().isEmpty()) { + miningParams.setTargetGasLimit(30000000L); } - miningParams.getDynamic().setMinBlockOccupancyRatio(TRY_FILL_BLOCK); + miningParams.setMinBlockOccupancyRatio(TRY_FILL_BLOCK); this.miningParameters = miningParams; @@ -129,7 +129,7 @@ public MergeCoordinator( (parentHeader, address) -> new MergeBlockCreator( miningParameters, - parent -> miningParameters.getDynamic().getExtraData(), + parent -> miningParameters.getExtraData(), transactionPool, protocolContext, protocolSchedule, @@ -163,10 +163,10 @@ public MergeCoordinator( this.blockBuilderExecutor = blockBuilderExecutor; this.mergeContext = protocolContext.getConsensusContext(MergeContext.class); this.backwardSyncContext = backwardSyncContext; - if (miningParams.getDynamic().getTargetGasLimit().isEmpty()) { - miningParams.getDynamic().setTargetGasLimit(30000000L); + if (miningParams.getTargetGasLimit().isEmpty()) { + miningParams.setTargetGasLimit(30000000L); } - miningParams.getDynamic().setMinBlockOccupancyRatio(TRY_FILL_BLOCK); + miningParams.setMinBlockOccupancyRatio(TRY_FILL_BLOCK); this.miningParameters = miningParams; this.mergeBlockCreatorFactory = mergeBlockCreatorFactory; @@ -200,12 +200,12 @@ public boolean isMining() { @Override public Wei getMinTransactionGasPrice() { - return miningParameters.getDynamic().getMinTransactionGasPrice(); + return miningParameters.getMinTransactionGasPrice(); } @Override public void setExtraData(final Bytes extraData) { - this.miningParameters.getDynamic().setExtraData(extraData); + this.miningParameters.setExtraData(extraData); } @Override @@ -229,7 +229,7 @@ public Optional createBlock(final BlockHeader parentHeader, final long ti @Override public void changeTargetGasLimit(final Long newTargetGasLimit) { if (AbstractGasLimitSpecification.isValidTargetGasLimit(newTargetGasLimit)) { - this.miningParameters.getDynamic().setTargetGasLimit(newTargetGasLimit); + this.miningParameters.setTargetGasLimit(newTargetGasLimit); } else { throw new IllegalArgumentException("Specified target gas limit is invalid"); } diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java index aa611817b9c..79abb0be0ae 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java @@ -57,6 +57,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.TransactionTestFixture; @@ -744,11 +745,8 @@ public void shouldUseExtraDataFromMiningParameters() { miningParameters = ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setExtraData(extraData) - .toParameters(); - // new MiningParameters.Builder().extraData(extraData).build(); + .updatableInitValues(UpdatableInitValues.builder().extraData(extraData).build()) + .build(); this.coordinator = new MergeCoordinator( 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 639551f3b2d..afbc2742637 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 @@ -367,13 +367,14 @@ private static ControllerAndState createControllerAndFinalState( final MiningParameters miningParams = ImmutableMiningParameters.builder() - .isMiningEnabled(true) + .updatableInitValues( + ImmutableMiningParameters.UpdatableInitValues.builder() + .isMiningEnabled(true) + .minTransactionGasPrice(Wei.ZERO) + .extraData(Bytes.wrap("Qbft Int tests".getBytes(UTF_8))) + .build()) .coinbase(AddressHelpers.ofValue(1)) - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .setExtraData(Bytes.wrap("Qbft Int tests".getBytes(UTF_8))) - .toParameters(); + .build(); final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions(); final Map qbftConfigValues = diff --git a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactory.java b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactory.java index b655c1a3693..2f993c4d1bb 100644 --- a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactory.java +++ b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactory.java @@ -84,8 +84,7 @@ public Bytes createExtraData(final int round, final BlockHeader parentHeader) { final BftExtraData extraData = new BftExtraData( ConsensusHelpers.zeroLeftPad( - miningParameters.getDynamic().getExtraData(), - BftExtraDataCodec.EXTRA_VANITY_LENGTH), + miningParameters.getExtraData(), BftExtraDataCodec.EXTRA_VANITY_LENGTH), Collections.emptyList(), Optional.empty(), round, diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java index e1a265ae187..a4accedd1b0 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java @@ -50,10 +50,11 @@ public class QbftBlockCreatorFactoryTest { public void setUp() { final MiningParameters miningParams = ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setExtraData(Bytes.wrap("Qbft tests".getBytes(UTF_8))) - .toParameters(); + .updatableInitValues( + ImmutableMiningParameters.UpdatableInitValues.builder() + .extraData(Bytes.wrap("Qbft tests".getBytes(UTF_8))) + .build()) + .build(); final MutableQbftConfigOptions qbftConfigOptions = new MutableQbftConfigOptions(JsonQbftConfigOptions.DEFAULT); diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java index 028e9727c9a..d46ccefbc1a 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetFilterChangesIntegrationTest.java @@ -44,7 +44,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -117,11 +117,7 @@ public void setUp() { protocolContext, batchAddedListener, ethContext, - ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .toParameters(), + MiningParameters.newDefault(), new TransactionPoolMetrics(metricsSystem), TransactionPoolConfiguration.DEFAULT, null); diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java index 260e3674e6c..e9e012486b7 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/london/EthGetFilterChangesIntegrationTest.java @@ -44,7 +44,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -117,11 +117,7 @@ public void setUp() { protocolContext, batchAddedListener, ethContext, - ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .toParameters(), + MiningParameters.newDefault(), new TransactionPoolMetrics(metricsSystem), TransactionPoolConfiguration.DEFAULT, null); diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java index aacbc7b1269..060771b7ca6 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java @@ -387,10 +387,7 @@ private ProcessableBlockHeader createPendingBlockHeader( .getGasLimitCalculator() .nextGasLimit( parentHeader.getGasLimit(), - miningParameters - .getDynamic() - .getTargetGasLimit() - .orElse(parentHeader.getGasLimit()), + miningParameters.getTargetGasLimit().orElse(parentHeader.getGasLimit()), newBlockNumber); final DifficultyCalculator difficultyCalculator = protocolSpec.getDifficultyCalculator(); diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java index 08a0485463f..1432afb34a7 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractMinerExecutor.java @@ -94,15 +94,15 @@ public abstract M createMiner( final BlockHeader parentHeader); public void setExtraData(final Bytes extraData) { - miningParameters.getDynamic().setExtraData(extraData.copy()); + miningParameters.setExtraData(extraData.copy()); } public void setMinTransactionGasPrice(final Wei minTransactionGasPrice) { - miningParameters.getDynamic().setMinTransactionGasPrice(minTransactionGasPrice); + miningParameters.setMinTransactionGasPrice(minTransactionGasPrice); } public Wei getMinTransactionGasPrice() { - return miningParameters.getDynamic().getMinTransactionGasPrice(); + return miningParameters.getMinTransactionGasPrice(); } public abstract Optional
getCoinbase(); diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/NoopMiningCoordinator.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/NoopMiningCoordinator.java index eccd2f291fc..ab0a5c3d717 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/NoopMiningCoordinator.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/NoopMiningCoordinator.java @@ -61,7 +61,7 @@ public boolean isMining() { @Override public Wei getMinTransactionGasPrice() { - return miningParameters.getDynamic().getMinTransactionGasPrice(); + return miningParameters.getMinTransactionGasPrice(); } @Override diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java index f72592e1194..f10fe3d7771 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java @@ -34,7 +34,6 @@ public class PoWMinerExecutor extends AbstractMinerExecutor { protected volatile Optional
coinbase; protected boolean stratumMiningEnabled; - protected final Iterable nonceGenerator; protected final EpochCalculator epochCalculator; public PoWMinerExecutor( @@ -43,11 +42,12 @@ public PoWMinerExecutor( final TransactionPool transactionPool, final MiningParameters miningParams, final AbstractBlockScheduler blockScheduler, - final EpochCalculator epochCalculator -) { + final EpochCalculator epochCalculator) { super(protocolContext, protocolSchedule, transactionPool, miningParams, blockScheduler); this.coinbase = miningParams.getCoinbase(); - this.nonceGenerator = miningParams.nonceGenerator().orElse(new RandomNonceGenerator()); + if (miningParams.getNonceGenerator().isEmpty()) { + miningParams.setNonceGenerator(new RandomNonceGenerator()); + } this.epochCalculator = epochCalculator; } @@ -73,8 +73,7 @@ public PoWBlockMiner createMiner( protocolSchedule.getForNextBlockHeader(parentHeader, 0); final PoWSolver solver = new PoWSolver( - miningParameters, - nonceGenerator, + miningParameters, nextBlockProtocolSpec.getPoWHasher().get(), stratumMiningEnabled, ethHashObservers, @@ -84,7 +83,7 @@ public PoWBlockMiner createMiner( new PoWBlockCreator( miningParameters, coinbase.orElse(Address.ZERO), - parent -> miningParameters.getDynamic().getExtraData(), + parent -> miningParameters.getExtraData(), transactionPool, protocolContext, protocolSchedule, diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java index 92773f7cc1b..67b6b950053 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java @@ -169,9 +169,7 @@ private void timeLimitedSelection() { () -> blockSelectionContext .transactionPool() - .selectTransactions( - this::evaluateTransaction - )); + .selectTransactions(this::evaluateTransaction)); try { txSelection.get(5000, TimeUnit.MILLISECONDS); @@ -236,11 +234,10 @@ private TransactionSelectionResult evaluateTransaction( if (!isTimeout.get()) { return handleTransactionSelected(pendingTransaction, processingResult, worldStateUpdater); } else { - return handleTransactionNotSelected(pendingTransaction, TransactionSelectionResult.BLOCK_SELECTION_TIMEOUT); + return handleTransactionNotSelected( + pendingTransaction, TransactionSelectionResult.BLOCK_SELECTION_TIMEOUT); } } - - } /** diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java index 14ad0d81294..96f357546f3 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java @@ -118,13 +118,13 @@ private boolean blockOccupancyAboveThreshold( LOG.trace( "Min block occupancy ratio {}, gas used {}, available {}, remaining {}, used/available {}", - context.miningParameters().getDynamic().getMinBlockOccupancyRatio(), + context.miningParameters().getMinBlockOccupancyRatio(), gasUsed, gasAvailable, gasRemaining, occupancyRatio); - return occupancyRatio >= context.miningParameters().getDynamic().getMinBlockOccupancyRatio(); + return occupancyRatio >= context.miningParameters().getMinBlockOccupancyRatio(); } /** diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/PriceTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/PriceTransactionSelector.java index 57cef550a21..d421d280ccc 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/PriceTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/PriceTransactionSelector.java @@ -89,14 +89,13 @@ private boolean transactionCurrentPriceBelowMin(final PendingTransaction pending .price(transaction, context.processableBlockHeader().getBaseFee()); if (context .miningParameters() - .getDynamic() .getMinTransactionGasPrice() .compareTo(currentMinTransactionGasPriceInBlock) > 0) { LOG.trace( "Current gas fee of {} is lower than configured minimum {}, skipping", transaction, - context.miningParameters().getDynamic().getMinTransactionGasPrice()); + context.miningParameters().getMinTransactionGasPrice()); return true; } } diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java index 5b3a2836ad1..8a2e91f664f 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java @@ -387,13 +387,14 @@ private AbstractBlockCreator createBlockCreator( final MiningParameters miningParameters = ImmutableMiningParameters.builder() + .updatableInitValues( + ImmutableMiningParameters.UpdatableInitValues.builder() + .extraData(Bytes.fromHexString("deadbeef")) + .minTransactionGasPrice(Wei.ONE) + .minBlockOccupancyRatio(0d) + .build()) .coinbase(Address.ZERO) - .build() - .getDynamic() - .setExtraData(Bytes.fromHexString("deadbeef")) - .setMinTransactionGasPrice(Wei.ONE) - .setMinBlockOccupancyRatio(0d) - .toParameters(); + .build(); return new TestBlockCreator( miningParameters, 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 9dd2394d8f6..ef8314bec69 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 @@ -151,10 +151,11 @@ public void setup() { when(ethContext.getEthPeers().subscribeConnect(any())).thenReturn(1L); miningParameters = ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ONE) - .toParameters(); + .updatableInitValues( + ImmutableMiningParameters.UpdatableInitValues.builder() + .minTransactionGasPrice(Wei.ONE) + .build()) + .build(); transactionPool = createTransactionPool(); } @@ -684,10 +685,8 @@ public void transactionSelectionPluginShouldBeNotifiedWhenTransactionSelectionCo createBlockSelectorWithTxSelPlugin( transactionProcessor, createBlock(300_000), - Wei.ZERO, AddressHelpers.ofValue(1), Wei.ZERO, - MIN_OCCUPANCY_80_PERCENT, transactionSelectorFactory) .buildTransactionListForBlock(); @@ -750,18 +749,14 @@ protected BlockTransactionSelector createBlockSelector( final BlockTransactionSelector selector = new BlockTransactionSelector( miningParameters - .getDynamic() .setMinTransactionGasPrice(minGasPrice) - .setMinBlockOccupancyRatio(minBlockOccupancyRatio) - .toParameters(), + .setMinBlockOccupancyRatio(minBlockOccupancyRatio), transactionProcessor, blockchain, worldState, transactionPool, blockHeader, this::createReceipt, - // minGasPrice, - // minBlockOccupancyRatio, this::isCancelled, miningBeneficiary, blobGasPrice, diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java index 225414cfb8b..2d428dcc054 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java @@ -94,28 +94,19 @@ void createMainnetBlock1() throws IOException { .createProtocolSchedule()) .build(); + final MiningParameters miningParameters = + createMiningParameters(Lists.newArrayList(BLOCK_1_NONCE)); + final PoWSolver solver = new PoWSolver( - Lists.newArrayList(BLOCK_1_NONCE), + miningParameters, PoWHasher.ETHASH_LIGHT, false, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); final TransactionPool transactionPool = createTransactionPool(executionContextTestFixture); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .coinbase(BLOCK_1_COINBASE) - .build() - .getDynamic() - .setExtraData(BLOCK_1_EXTRA_DATA) - .setMinTransactionGasPrice(Wei.ONE) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); - final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, @@ -158,28 +149,19 @@ void createMainnetBlock1_fixedDifficulty1() { .createProtocolSchedule()) .build(); + final MiningParameters miningParameters = + createMiningParameters(Lists.newArrayList(BLOCK_1_NONCE)); + final PoWSolver solver = new PoWSolver( - Lists.newArrayList(BLOCK_1_NONCE), + miningParameters, PoWHasher.ETHASH_LIGHT, false, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); final TransactionPool transactionPool = createTransactionPool(executionContextTestFixture); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .coinbase(BLOCK_1_COINBASE) - .build() - .getDynamic() - .setExtraData(BLOCK_1_EXTRA_DATA) - .setMinTransactionGasPrice(Wei.ONE) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); - final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, @@ -213,29 +195,19 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsFalse() { final ExecutionContextTestFixture executionContextTestFixture = ExecutionContextTestFixture.builder().protocolSchedule(protocolSchedule).build(); + final MiningParameters miningParameters = + createMiningParameters(Lists.newArrayList(BLOCK_1_NONCE)); + final PoWSolver solver = new PoWSolver( - Lists.newArrayList(BLOCK_1_NONCE), + miningParameters, PoWHasher.ETHASH_LIGHT, false, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); final TransactionPool transactionPool = createTransactionPool(executionContextTestFixture); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .coinbase(BLOCK_1_COINBASE) - .build() - .getDynamic() - .setTargetGasLimit(10_000_000L) - .setExtraData(BLOCK_1_EXTRA_DATA) - .setMinTransactionGasPrice(Wei.ONE) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); - final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, @@ -291,29 +263,19 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsTrue() { final ExecutionContextTestFixture executionContextTestFixture = ExecutionContextTestFixture.builder().protocolSchedule(protocolSchedule).build(); + final MiningParameters miningParameters = + createMiningParameters(Lists.newArrayList(BLOCK_1_NONCE)); + final PoWSolver solver = new PoWSolver( - Lists.newArrayList(BLOCK_1_NONCE), + miningParameters, PoWHasher.ETHASH_LIGHT, false, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); final TransactionPool transactionPool = createTransactionPool(executionContextTestFixture); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .coinbase(BLOCK_1_COINBASE) - .build() - .getDynamic() - .setTargetGasLimit(10_000_000L) - .setExtraData(BLOCK_1_EXTRA_DATA) - .setMinTransactionGasPrice(Wei.ONE) - .setMinBlockOccupancyRatio(0.8) - .toParameters(); - final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, @@ -381,4 +343,16 @@ private TransactionPool createTransactionPool( return transactionPool; } + + private MiningParameters createMiningParameters(final Iterable nonceList) { + return ImmutableMiningParameters.builder() + .updatableInitValues( + ImmutableMiningParameters.UpdatableInitValues.builder() + .nonceGenerator(nonceList) + .extraData(BLOCK_1_EXTRA_DATA) + .minTransactionGasPrice(Wei.ONE) + .build()) + .coinbase(BLOCK_1_COINBASE) + .build(); + } } diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java index 9e00bfc64f1..b074e2146a8 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutorTest.java @@ -22,7 +22,6 @@ import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.core.BlockHeader; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.transactions.ImmutableTransactionPoolConfiguration; @@ -48,7 +47,7 @@ public class PoWMinerExecutorTest { @Test public void startingMiningWithoutCoinbaseThrowsException() { - final MiningParameters miningParameters = ImmutableMiningParameters.builder().build(); + final MiningParameters miningParameters = MiningParameters.newDefault(); final TransactionPool transactionPool = createTransactionPool(miningParameters); @@ -59,9 +58,7 @@ public void startingMiningWithoutCoinbaseThrowsException() { transactionPool, miningParameters, new DefaultBlockScheduler(1, 10, TestClock.fixed()), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); assertThatExceptionOfType(CoinbaseNotSetException.class) .isThrownBy(() -> executor.startAsyncMining(Subscribers.create(), Subscribers.none(), null)) @@ -70,7 +67,7 @@ public void startingMiningWithoutCoinbaseThrowsException() { @Test public void settingCoinbaseToNullThrowsException() { - final MiningParameters miningParameters = ImmutableMiningParameters.builder().build(); + final MiningParameters miningParameters = MiningParameters.newDefault(); final TransactionPool transactionPool = createTransactionPool(miningParameters); @@ -81,9 +78,7 @@ public void settingCoinbaseToNullThrowsException() { transactionPool, miningParameters, new DefaultBlockScheduler(1, 10, TestClock.fixed()), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); assertThatExceptionOfType(IllegalArgumentException.class) .isThrownBy(() -> executor.setCoinbase(null)) diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java index 9482c5c396c..298dc87d573 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java @@ -26,46 +26,201 @@ import org.immutables.value.Value; @Value.Immutable -@Value.Style(allParameters = true) @Value.Enclosing -public interface MiningParameters { +public abstract class MiningParameters { + public static final MiningParameters MINING_DISABLED = + ImmutableMiningParameters.builder() + .updatableInitValues( + ImmutableMiningParameters.UpdatableInitValues.builder() + .isMiningEnabled(false) + .build()) + .build(); + + public static final MiningParameters newDefault() { + return ImmutableMiningParameters.builder().build(); + } - Optional
getCoinbase(); + public abstract Optional
getCoinbase(); - @Value.Default - default boolean isMiningEnabled() { - return false; + public boolean isMiningEnabled() { + return getUpdatableRuntimeValues().miningEnabled; + } + + public MiningParameters setMiningEnabled(final boolean miningEnabled) { + getUpdatableRuntimeValues().miningEnabled = miningEnabled; + return this; + } + + public Bytes getExtraData() { + return getUpdatableRuntimeValues().extraData; + } + + public MiningParameters setExtraData(final Bytes extraData) { + getUpdatableRuntimeValues().extraData = extraData; + return this; + } + + public Wei getMinTransactionGasPrice() { + return getUpdatableRuntimeValues().minTransactionGasPrice; + } + + public MiningParameters setMinTransactionGasPrice(final Wei minTransactionGasPrice) { + getUpdatableRuntimeValues().minTransactionGasPrice = minTransactionGasPrice; + return this; + } + + public OptionalLong getTargetGasLimit() { + return getUpdatableRuntimeValues().targetGasLimit; + } + + public MiningParameters setTargetGasLimit(final long targetGasLimit) { + getUpdatableRuntimeValues().targetGasLimit = OptionalLong.of(targetGasLimit); + return this; + } + + public double getMinBlockOccupancyRatio() { + return getUpdatableRuntimeValues().minBlockOccupancyRatio; + } + + public MiningParameters setMinBlockOccupancyRatio(final double minBlockOccupancyRatio) { + getUpdatableRuntimeValues().minBlockOccupancyRatio = minBlockOccupancyRatio; + return this; + } + + public Optional> getNonceGenerator() { + return getUpdatableRuntimeValues().nonceGenerator; + } + + public MiningParameters setNonceGenerator(final Iterable nonceGenerator) { + getUpdatableRuntimeValues().nonceGenerator = Optional.of(nonceGenerator); + return this; } @Value.Default - default boolean isStratumMiningEnabled() { + public boolean isStratumMiningEnabled() { return false; } @Value.Default - default String getStratumNetworkInterface() { + public String getStratumNetworkInterface() { return "0.0.0.0"; } @Value.Default - default int getStratumPort() { + public int getStratumPort() { return 8008; } - Optional> nonceGenerator(); - @Value.Default - default Dynamic getDynamic() { - return new Dynamic(this); + protected UpdatableRuntimeValues getUpdatableRuntimeValues() { + return new UpdatableRuntimeValues(getUpdatableInitValues()); } @Value.Default - default Unstable getUnstable() { + public Unstable getUnstable() { return Unstable.DEFAULT; } + @Value.Default + public UpdatableInitValues getUpdatableInitValues() { + return UpdatableInitValues.DEFAULT; + } + @Value.Immutable - interface Unstable { + public interface UpdatableInitValues { + Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY; + Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); + double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; + + UpdatableInitValues DEFAULT = ImmutableMiningParameters.UpdatableInitValues.builder().build(); + + @Value.Default + default boolean isMiningEnabled() { + return false; + } + + @Value.Default + default Bytes getExtraData() { + return DEFAULT_EXTRA_DATA; + } + + @Value.Default + default Wei getMinTransactionGasPrice() { + return DEFAULT_MIN_TRANSACTION_GAS_PRICE; + } + + @Value.Default + default double getMinBlockOccupancyRatio() { + return DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; + } + + OptionalLong getTargetGasLimit(); + + Optional> nonceGenerator(); + } + + static class UpdatableRuntimeValues { + private volatile boolean miningEnabled; + private volatile Bytes extraData; + private volatile Wei minTransactionGasPrice; + private volatile double minBlockOccupancyRatio; + private volatile OptionalLong targetGasLimit; + private volatile Optional> nonceGenerator; + + private UpdatableRuntimeValues(final UpdatableInitValues initValues) { + miningEnabled = initValues.isMiningEnabled(); + extraData = initValues.getExtraData(); + minTransactionGasPrice = initValues.getMinTransactionGasPrice(); + minBlockOccupancyRatio = initValues.getMinBlockOccupancyRatio(); + targetGasLimit = initValues.getTargetGasLimit(); + nonceGenerator = initValues.nonceGenerator(); + } + + @Override + public boolean equals(final Object o) { + if (this == o) return true; + if (o == null || getClass() != o.getClass()) return false; + final UpdatableRuntimeValues that = (UpdatableRuntimeValues) o; + return miningEnabled == that.miningEnabled + && Double.compare(minBlockOccupancyRatio, that.minBlockOccupancyRatio) == 0 + && Objects.equals(extraData, that.extraData) + && Objects.equals(minTransactionGasPrice, that.minTransactionGasPrice) + && Objects.equals(targetGasLimit, that.targetGasLimit) + && Objects.equals(nonceGenerator, that.nonceGenerator); + } + + @Override + public int hashCode() { + return Objects.hash( + miningEnabled, + extraData, + minTransactionGasPrice, + minBlockOccupancyRatio, + targetGasLimit, + nonceGenerator); + } + + @Override + public String toString() { + return "UpdatableRuntimeValues{" + + "miningEnabled=" + + miningEnabled + + ", extraData=" + + extraData + + ", minTransactionGasPrice=" + + minTransactionGasPrice + + ", minBlockOccupancyRatio=" + + minBlockOccupancyRatio + + ", targetGasLimit=" + + targetGasLimit + + ", nonceGenerator=" + + nonceGenerator + + '}'; + } + } + + @Value.Immutable + public interface Unstable { int DEFAULT_REMOTE_SEALERS_LIMIT = 1000; long DEFAULT_REMOTE_SEALERS_TTL = Duration.ofMinutes(10).toMinutes(); long DEFAULT_POW_JOB_TTL = Duration.ofMinutes(5).toMillis(); @@ -110,91 +265,4 @@ default String getStratumExtranonce() { return "080c"; } } - - class Dynamic { - public static final Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY; - public static final Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); - public static final double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; - - private final MiningParameters miningParameters; - private volatile Bytes extraData = DEFAULT_EXTRA_DATA; - private volatile Wei minTransactionGasPrice = DEFAULT_MIN_TRANSACTION_GAS_PRICE; - private volatile double minBlockOccupancyRatio = DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; - private volatile OptionalLong targetGasLimit = OptionalLong.empty(); - - private Dynamic(final MiningParameters miningParameters) { - this.miningParameters = miningParameters; - } - - public MiningParameters toParameters() { - return miningParameters; - } - - public Bytes getExtraData() { - return extraData; - } - - public Dynamic setExtraData(final Bytes extraData) { - this.extraData = extraData; - return this; - } - - public Wei getMinTransactionGasPrice() { - return minTransactionGasPrice; - } - - public Dynamic setMinTransactionGasPrice(final Wei minTransactionGasPrice) { - this.minTransactionGasPrice = minTransactionGasPrice; - return this; - } - - public double getMinBlockOccupancyRatio() { - return minBlockOccupancyRatio; - } - - public Dynamic setMinBlockOccupancyRatio(final double minBlockOccupancyRatio) { - this.minBlockOccupancyRatio = minBlockOccupancyRatio; - return this; - } - - public OptionalLong getTargetGasLimit() { - return targetGasLimit; - } - - public Dynamic setTargetGasLimit(final long targetGasLimit) { - this.targetGasLimit = OptionalLong.of(targetGasLimit); - return this; - } - - @Override - public boolean equals(final Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; - final Dynamic dynamic = (Dynamic) o; - return Double.compare(minBlockOccupancyRatio, dynamic.minBlockOccupancyRatio) == 0 - && Objects.equals(extraData, dynamic.extraData) - && Objects.equals(minTransactionGasPrice, dynamic.minTransactionGasPrice) - && Objects.equals(targetGasLimit, dynamic.targetGasLimit); - } - - @Override - public int hashCode() { - return Objects.hash( - extraData, minTransactionGasPrice, minBlockOccupancyRatio, targetGasLimit); - } - - @Override - public String toString() { - return "Dynamic{" - + "extraData=" - + extraData - + ", minTransactionGasPrice=" - + minTransactionGasPrice - + ", minBlockOccupancyRatio=" - + minBlockOccupancyRatio - + ", targetGasLimit=" - + targetGasLimit - + '}'; - } - } } diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/PoWSolver.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/PoWSolver.java index db547842413..3161490478e 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/PoWSolver.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/PoWSolver.java @@ -32,11 +32,10 @@ public class PoWSolver { -// private final int maxOmmerDepth; private static final Logger LOG = LoggerFactory.getLogger(PoWSolver.class); -// private final long powJobTimeToLive; private final MiningParameters miningParameters; + public static class PoWSolverJob { private final PoWSolverInputs inputs; @@ -78,7 +77,6 @@ PoWSolution getSolution() throws InterruptedException, ExecutionException { private final long NO_MINING_CONDUCTED = -1; - private final Iterable nonceGenerator; private final PoWHasher poWHasher; private volatile long hashesPerSecond = NO_MINING_CONDUCTED; private final Boolean stratumMiningEnabled; @@ -88,14 +86,12 @@ PoWSolution getSolution() throws InterruptedException, ExecutionException { private final ExpiringMap currentJobs = new ExpiringMap<>(); public PoWSolver( - final MiningParameters miningParameters, - final Iterable nonceGenerator, - final PoWHasher poWHasher, - final Boolean stratumMiningEnabled, - final Subscribers ethHashObservers, - final EpochCalculator epochCalculator) { + final MiningParameters miningParameters, + final PoWHasher poWHasher, + final Boolean stratumMiningEnabled, + final Subscribers ethHashObservers, + final EpochCalculator epochCalculator) { this.miningParameters = miningParameters; - this.nonceGenerator = nonceGenerator; this.poWHasher = poWHasher; this.stratumMiningEnabled = stratumMiningEnabled; this.ethHashObservers = ethHashObservers; @@ -107,7 +103,9 @@ public PoWSolution solveFor(final PoWSolverJob job) throws InterruptedException, ExecutionException { currentJob = Optional.of(job); currentJobs.put( - job.getInputs().getPrePowHash(), job, System.currentTimeMillis() + miningParameters.getUnstable().getPowJobTimeToLive()); + job.getInputs().getPrePowHash(), + job, + System.currentTimeMillis() + miningParameters.getUnstable().getPowJobTimeToLive()); if (stratumMiningEnabled) { LOG.debug( "solving with stratum miner for {} observers", ethHashObservers.getSubscriberCount()); @@ -123,7 +121,7 @@ private void findValidNonce() { final Stopwatch operationTimer = Stopwatch.createStarted(); final PoWSolverJob job = currentJob.get(); long hashesExecuted = 0; - for (final Long n : nonceGenerator) { + for (final Long n : miningParameters.getNonceGenerator().get()) { if (job.isDone()) { return; @@ -213,6 +211,6 @@ public boolean submitSolution(final PoWSolution solution) { } public Iterable getNonceGenerator() { - return nonceGenerator; + return miningParameters.getNonceGenerator().get(); } } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java index 005348ac338..a51846b528e 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java @@ -42,6 +42,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; @@ -233,14 +234,15 @@ static TestBlockCreator forHeader( final MiningParameters miningParameters = ImmutableMiningParameters.builder() + .updatableInitValues( + UpdatableInitValues.builder() + .extraData(Bytes.fromHexString("deadbeef")) + .targetGasLimit(30_000_000L) + .minTransactionGasPrice(Wei.ONE) + .minBlockOccupancyRatio(0d) + .build()) .coinbase(Address.ZERO) - .build() - .getDynamic() - .setExtraData(Bytes.fromHexString("deadbeef")) - .setTargetGasLimit(30_000_000L) - .setMinTransactionGasPrice(Wei.ONE) - .setMinBlockOccupancyRatio(0d) - .toParameters(); + .build(); return new TestBlockCreator( miningParameters, diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/PoWSolverTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/PoWSolverTest.java index 92cdce6eb0e..6137936d22b 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/PoWSolverTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/PoWSolverTest.java @@ -21,6 +21,9 @@ import static org.mockito.Mockito.mock; import org.hyperledger.besu.datatypes.Hash; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.util.Subscribers; import java.util.Arrays; @@ -48,13 +51,11 @@ public void emptyHashRateAndWorkDefinitionIsReportedPriorToSolverStarting() { final List noncesToTry = Arrays.asList(1L, 1L, 1L, 1L, 1L, 1L, 0L); final PoWSolver solver = new PoWSolver( - noncesToTry, + createMiningParameters(noncesToTry, 1000, 8), PoWHasher.ETHASH_LIGHT, false, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); assertThat(solver.hashesPerSecond()).isEqualTo(Optional.empty()); assertThat(solver.getWorkDefinition()).isEqualTo(Optional.empty()); @@ -83,13 +84,11 @@ public void hashRateIsProducedSuccessfully() throws InterruptedException, Execut final PoWSolver solver = new PoWSolver( - noncesToTry, + createMiningParameters(noncesToTry, 1000, 8), hasher, false, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); final Stopwatch operationTimer = Stopwatch.createStarted(); final PoWSolverInputs inputs = new PoWSolverInputs(UInt256.ONE, Bytes.EMPTY, 5); @@ -150,13 +149,15 @@ public void ifInvokedTwiceProducesCorrectAnswerForSecondInvocation() // Nonces need to have a 0L inserted, as it is a "wasted" nonce in the solver. final PoWSolver solver = new PoWSolver( - Lists.newArrayList(expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + createMiningParameters( + Lists.newArrayList( + expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + 1000, + 8), PoWHasher.ETHASH_LIGHT, false, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); PoWSolution soln = solver.solveFor(PoWSolver.PoWSolverJob.createFromInputs(firstInputs)); assertThat(soln.getMixHash()).isEqualTo(expectedFirstOutput.getMixHash()); @@ -210,13 +211,15 @@ public void canAcceptSolutionsSerially() // Nonces need to have a 0L inserted, as it is a "wasted" nonce in the solver. final PoWSolver solver = new PoWSolver( - Lists.newArrayList(expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + createMiningParameters( + Lists.newArrayList( + expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + 1000, + 8), PoWHasher.ETHASH_LIGHT, true, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); CompletableFuture soln1 = new CompletableFuture<>(); CompletableFuture soln2 = new CompletableFuture<>(); @@ -291,13 +294,15 @@ public void canAcceptSolutionsForMultipleJobs() // Nonces need to have a 0L inserted, as it is a "wasted" nonce in the solver. final PoWSolver solver = new PoWSolver( - Lists.newArrayList(expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + createMiningParameters( + Lists.newArrayList( + expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + 10000, + 8), PoWHasher.ETHASH_LIGHT, true, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 10000, - 8); + new EpochCalculator.DefaultEpochCalculator()); CompletableFuture soln1 = new CompletableFuture<>(); CompletableFuture soln2 = new CompletableFuture<>(); @@ -382,13 +387,15 @@ public void canAcceptAtMostOneSolution() // Nonces need to have a 0L inserted, as it is a "wasted" nonce in the solver. final PoWSolver solver = new PoWSolver( - Lists.newArrayList(expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + createMiningParameters( + Lists.newArrayList( + expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + 1000, + 8), PoWHasher.ETHASH_LIGHT, true, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); CompletableFuture soln1 = new CompletableFuture<>(); CompletableFuture soln2 = new CompletableFuture<>(); @@ -475,13 +482,15 @@ public void rejectsSolutionsForOldBlocks() // Nonces need to have a 0L inserted, as it is a "wasted" nonce in the solver. final PoWSolver solver = new PoWSolver( - Lists.newArrayList(expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + createMiningParameters( + Lists.newArrayList( + expectedFirstOutput.getNonce(), 0L, expectedSecondOutput.getNonce()), + 1000, + 8), PoWHasher.ETHASH_LIGHT, true, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); CompletableFuture soln1 = new CompletableFuture<>(); CompletableFuture soln2 = new CompletableFuture<>(); @@ -520,4 +529,16 @@ public void rejectsSolutionsForOldBlocks() assertThat(result2.getMixHash()).isEqualTo(expectedSecondOutput.getMixHash()); powThread1.interrupt(); } + + private MiningParameters createMiningParameters( + final List nonceToTry, final int powJobTimeToLive, final int maxOmmerDepth) { + return ImmutableMiningParameters.builder() + .updatableInitValues(UpdatableInitValues.builder().nonceGenerator(nonceToTry).build()) + .unstable( + ImmutableMiningParameters.Unstable.builder() + .maxOmmerDepth(maxOmmerDepth) + .powJobTimeToLive(powJobTimeToLive) + .build()) + .build(); + } } diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPool.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPool.java index f6c842d8aa9..f2aec4e7e33 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPool.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPool.java @@ -203,7 +203,7 @@ private Optional getMaxGasPrice(final Transaction transaction) { private boolean isMaxGasPriceBelowConfiguredMinGasPrice(final Transaction transaction) { return getMaxGasPrice(transaction) - .map(g -> g.lessThan(miningParameters.getDynamic().getMinTransactionGasPrice())) + .map(g -> g.lessThan(miningParameters.getMinTransactionGasPrice())) .orElse(true); } @@ -526,7 +526,7 @@ && isMaxGasPriceBelowConfiguredMinGasPrice(transaction)) LOG.atTrace() .setMessage("Discard transaction {} below min gas price {}") .addArgument(transaction::toTraceLog) - .addArgument(miningParameters.getDynamic()::getMinTransactionGasPrice) + .addArgument(miningParameters::getMinTransactionGasPrice) .log(); return TransactionInvalidReason.GAS_PRICE_TOO_LOW; } diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java index 562ea0f939c..8884eefdd6e 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/EthProtocolManagerTest.java @@ -27,7 +27,6 @@ import org.hyperledger.besu.consensus.merge.ForkchoiceEvent; import org.hyperledger.besu.datatypes.Hash; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; @@ -37,7 +36,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; import org.hyperledger.besu.ethereum.core.Difficulty; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.core.TransactionReceipt; @@ -1116,11 +1115,7 @@ public void transactionMessagesGoToTheCorrectExecutor() { TestClock.system(ZoneId.systemDefault()), metricsSystem, new SyncState(blockchain, ethManager.ethContext().getEthPeers()), - ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .toParameters(), + MiningParameters.newDefault(), TransactionPoolConfiguration.DEFAULT, null) .setEnabled(); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java index 1514de256a4..88f5457a121 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/ethtaskutils/AbstractMessageTaskTest.java @@ -22,11 +22,10 @@ import org.hyperledger.besu.crypto.SECPPublicKey; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Hash; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.eth.EthProtocol; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.manager.DeterministicEthScheduler; @@ -136,11 +135,7 @@ public void setupTest() { TestClock.system(ZoneId.systemDefault()), metricsSystem, syncState, - ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ONE) - .toParameters(), + MiningParameters.newDefault(), TransactionPoolConfiguration.DEFAULT, null); transactionPool.setEnabled(); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/GetPooledTransactionsFromPeerTaskTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/GetPooledTransactionsFromPeerTaskTest.java index f50237515e4..4c7d521a16b 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/GetPooledTransactionsFromPeerTaskTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/manager/task/GetPooledTransactionsFromPeerTaskTest.java @@ -43,7 +43,7 @@ protected List generateDataToBeRequested() { Transaction tx = new TransactionTestFixture() .nonce(genesisAccountNonce + i) - .gasPrice(Wei.ONE) + .gasPrice(Wei.of(2000)) .gasLimit(100000) .chainId(Optional.empty()) .createTransaction(genesisAccountKeyPair); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTest.java index a3610ef18a3..db5cb34cbc3 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/AbstractTransactionPoolTest.java @@ -252,7 +252,7 @@ public void setUp() { transactionPool = createTransactionPool(); blockchain.observeBlockAdded(transactionPool); - when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.of(2)); + when(miningParameters.getMinTransactionGasPrice()).thenReturn(Wei.of(2)); } protected TransactionPool createTransactionPool() { @@ -947,7 +947,7 @@ public void shouldAcceptZeroGasPriceFrontierLocalTransactionsWhenMining() { public void shouldAcceptZeroGasPriceTransactionWhenMinGasPriceIsZero( final boolean disableLocalTxs) { transactionPool = createTransactionPool(b -> b.disableLocalTransactions(disableLocalTxs)); - when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.ZERO); + when(miningParameters.getMinTransactionGasPrice()).thenReturn(Wei.ZERO); final Transaction transaction = createTransaction(0, Wei.ZERO); @@ -961,7 +961,7 @@ public void shouldAcceptZeroGasPriceTransactionWhenMinGasPriceIsZero( public void shouldAcceptZeroGasPriceFrontierTxsWhenMinGasPriceIsZeroAndLondonWithZeroBaseFee( final boolean disableLocalTxs) { transactionPool = createTransactionPool(b -> b.disableLocalTransactions(disableLocalTxs)); - when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.ZERO); + when(miningParameters.getMinTransactionGasPrice()).thenReturn(Wei.ZERO); when(protocolSpec.getFeeMarket()).thenReturn(FeeMarket.london(0, Optional.of(Wei.ZERO))); whenBlockBaseFeeIs(Wei.ZERO); @@ -976,7 +976,7 @@ public void shouldAcceptZeroGasPriceFrontierTxsWhenMinGasPriceIsZeroAndLondonWit public void shouldAcceptZeroGasPrice1559TxsWhenMinGasPriceIsZeroAndLondonWithZeroBaseFee( final boolean disableLocalTxs) { transactionPool = createTransactionPool(b -> b.disableLocalTransactions(disableLocalTxs)); - when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(Wei.ZERO); + when(miningParameters.getMinTransactionGasPrice()).thenReturn(Wei.ZERO); when(protocolSpec.getFeeMarket()).thenReturn(FeeMarket.london(0, Optional.of(Wei.ZERO))); whenBlockBaseFeeIs(Wei.ZERO); @@ -1247,7 +1247,7 @@ protected int add1559TxAndGetPendingTxsCount( final Wei lastBlockBaseFee, final Wei txMaxFeePerGas, final boolean isLocal) { - when(miningParameters.getDynamic().getMinTransactionGasPrice()).thenReturn(minGasPrice); + when(miningParameters.getMinTransactionGasPrice()).thenReturn(minGasPrice); when(protocolSpec.getFeeMarket()).thenReturn(FeeMarket.london(0, Optional.of(genesisBaseFee))); whenBlockBaseFeeIs(lastBlockBaseFee); 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 bbe4891c3d8..90f77a783f3 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 @@ -26,13 +26,12 @@ import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.cryptoservices.NodeKey; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.difficulty.fixed.FixedDifficultyProtocolSchedule; import org.hyperledger.besu.ethereum.eth.EthProtocol; @@ -163,11 +162,7 @@ public boolean isMessagePermitted(final EnodeURL destinationEnode, final int cod TestClock.system(ZoneId.systemDefault()), metricsSystem, syncState, - ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ZERO) - .toParameters(), + MiningParameters.newDefault(), TransactionPoolConfiguration.DEFAULT, null); diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java index afd80bf0adf..e902c2c1dd8 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/transactions/TransactionPoolFactoryTest.java @@ -27,12 +27,11 @@ import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.datatypes.Hash; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BlockAddedObserver; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -241,11 +240,7 @@ private void setupInitialSyncPhase(final boolean hasInitialSyncPhase) { TestClock.fixed(), new TransactionPoolMetrics(new NoOpMetricsSystem()), syncState, - ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ONE) - .toParameters(), + MiningParameters.newDefault(), ImmutableTransactionPoolConfiguration.builder() .txPoolMaxSize(1) .pendingTxRetentionPeriod(1) @@ -354,11 +349,7 @@ private TransactionPool createTransactionPool( TestClock.fixed(), new NoOpMetricsSystem(), syncState, - ImmutableMiningParameters.builder() - .build() - .getDynamic() - .setMinTransactionGasPrice(Wei.ONE) - .toParameters(), + MiningParameters.newDefault(), ImmutableTransactionPoolConfiguration.builder() .txPoolImplementation(implementation) .txPoolMaxSize(1) diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java index 4b1f0ac586b..706120b1bfc 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java @@ -24,7 +24,6 @@ import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockReplay; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; -import org.hyperledger.besu.ethereum.blockcreation.IncrementingNonceGenerator; import org.hyperledger.besu.ethereum.chain.DefaultBlockchain; import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; @@ -181,25 +180,29 @@ private boolean buildContext( ? HeaderValidationMode.LIGHT : HeaderValidationMode.FULL; - final Iterable nonceGenerator = new IncrementingNonceGenerator(0); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .unstable( + ImmutableMiningParameters.Unstable.builder() + .powJobTimeToLive(1000) + .maxOmmerDepth(8) + .build()) + .build(); + miningParameters.setMinTransactionGasPrice(Wei.ZERO); poWSolver = ("NoProof".equals(sealengine) || "NoReward".equals(sealEngine)) ? new PoWSolver( - nonceGenerator, + miningParameters, NO_WORK_HASHER, false, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8) + new EpochCalculator.DefaultEpochCalculator()) : new PoWSolver( - nonceGenerator, + miningParameters, PoWHasher.ETHASH_LIGHT, false, Subscribers.none(), - new EpochCalculator.DefaultEpochCalculator(), - 1000, - 8); + new EpochCalculator.DefaultEpochCalculator()); blockReplay = new BlockReplay(protocolSchedule, blockchainQueries.getBlockchain()); @@ -232,9 +235,6 @@ private boolean buildContext( .txPoolLimitByAccountPercentage(Fraction.fromFloat(0.004f)) .build(); - final MiningParameters miningParameters = ImmutableMiningParameters.builder().build(); - miningParameters.getDynamic().setMinTransactionGasPrice(Wei.ZERO); - transactionPool = TransactionPoolFactory.createTransactionPool( protocolSchedule, diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java index 0a62de02505..4b6b868383d 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java @@ -62,12 +62,15 @@ private boolean mineNewBlock() { final ProtocolContext protocolContext = context.getProtocolContext(); final MutableBlockchain blockchain = context.getBlockchain(); final HeaderValidationMode headerValidationMode = context.getHeaderValidationMode(); - final MiningParameters miningParameters = ImmutableMiningParameters.builder().build(); - miningParameters - .getDynamic() - .setTargetGasLimit(blockchain.getChainHeadHeader().getGasLimit()) - .setMinBlockOccupancyRatio(0.0) - .setMinTransactionGasPrice(Wei.ZERO); + final MiningParameters miningParameters = + ImmutableMiningParameters.builder() + .updatableInitValues( + ImmutableMiningParameters.UpdatableInitValues.builder() + .targetGasLimit(blockchain.getChainHeadHeader().getGasLimit()) + .minBlockOccupancyRatio(0.0) + .minTransactionGasPrice(Wei.ZERO) + .build()) + .build(); final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, diff --git a/plugin-api/build.gradle b/plugin-api/build.gradle index f768971188a..66877c43c9d 100644 --- a/plugin-api/build.gradle +++ b/plugin-api/build.gradle @@ -69,7 +69,7 @@ Calculated : ${currentHash} tasks.register('checkAPIChanges', FileStateChecker) { description = "Checks that the API for the Plugin-API project does not change without deliberate thought" files = sourceSets.main.allJava.files - knownHash = 'YJdAgciFlYdXDw7/UuK6bG5KQwqF5SQ08h/Aub7VkV0=' + knownHash = 'aRwRZCqqkThbFyseJ9VRqe9rCoLsnsaL5vgfSOHylpY=' } check.dependsOn('checkAPIChanges') From 5e012d08876d2e56d681c9f6cf7da4824c6f634d Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Mon, 16 Oct 2023 11:24:58 +0200 Subject: [PATCH 10/24] New miner option: min-priority-fee Signed-off-by: Fabio Di Fabio --- .../org/hyperledger/besu/RunnerBuilder.java | 6 ++++++ .../cli/options/stable/MiningOptions.java | 15 ++++++++++++- .../jsonrpc/JsonRpcTestMethodsFactory.java | 3 +++ .../methods/JsonRpcMethodsFactory.java | 4 +++- .../jsonrpc/methods/MinerJsonRpcMethods.java | 4 +++- .../AbstractJsonRpcHttpServiceTest.java | 3 +++ .../JsonRpcHttpServiceHostAllowlistTest.java | 2 ++ .../jsonrpc/JsonRpcHttpServiceLoginTest.java | 2 ++ .../JsonRpcHttpServiceRpcApisTest.java | 3 +++ .../jsonrpc/JsonRpcHttpServiceTestBase.java | 2 ++ .../JsonRpcHttpServiceTlsClientAuthTest.java | 2 ++ ...RpcHttpServiceTlsMisconfigurationTest.java | 2 ++ .../jsonrpc/JsonRpcHttpServiceTlsTest.java | 2 ++ .../websocket/WebSocketServiceLoginTest.java | 2 ++ .../besu/ethereum/core/MiningParameters.java | 21 +++++++++++++++++++ 15 files changed, 70 insertions(+), 3 deletions(-) diff --git a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java index 4dc137fe3c7..12ec2f3d849 100644 --- a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java @@ -802,6 +802,7 @@ public Runner build() { blockchainQueries, synchronizer, transactionPool, + miningParameters, miningCoordinator, metricsSystem, supportedCapabilities, @@ -847,6 +848,7 @@ public Runner build() { blockchainQueries, synchronizer, transactionPool, + miningParameters, miningCoordinator, metricsSystem, supportedCapabilities, @@ -937,6 +939,7 @@ public Runner build() { blockchainQueries, synchronizer, transactionPool, + miningParameters, miningCoordinator, metricsSystem, supportedCapabilities, @@ -1019,6 +1022,7 @@ public Runner build() { blockchainQueries, synchronizer, transactionPool, + miningParameters, miningCoordinator, metricsSystem, supportedCapabilities, @@ -1187,6 +1191,7 @@ private Map jsonRpcMethods( final BlockchainQueries blockchainQueries, final Synchronizer synchronizer, final TransactionPool transactionPool, + final MiningParameters miningParameters, final MiningCoordinator miningCoordinator, final ObservableMetricsSystem metricsSystem, final Set supportedCapabilities, @@ -1218,6 +1223,7 @@ private Map jsonRpcMethods( protocolContext, filterManager, transactionPool, + miningParameters, miningCoordinator, metricsSystem, supportedCapabilities, diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java index b1b87321af5..f807dd63291 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java @@ -23,6 +23,7 @@ import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_REMOTE_SEALERS_TTL; import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_EXTRA_DATA; import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; +import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_MIN_PRIORITY_FEE_PER_GAS; import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE; import org.hyperledger.besu.cli.options.CLIOptions; @@ -93,10 +94,19 @@ public class MiningOptions implements CLIOptions { arity = "1") private Wei minTransactionGasPrice = DEFAULT_MIN_TRANSACTION_GAS_PRICE; + @Option( + names = {"--min-priority-fee"}, + description = + "Minimum priority fee per gas (in Wei) offered by a transaction for it to be included in a mined " + + "block (default: ${DEFAULT-VALUE})", + arity = "1") + private Wei minPriorityFeePerGas = DEFAULT_MIN_PRIORITY_FEE_PER_GAS; + @Option( names = {"--target-gas-limit"}, description = - "Sets target gas limit per block. If set, each block's gas limit will approach this setting over time if the current gas limit is different.") + "Sets target gas limit per block." + + " If set, each block's gas limit will approach this setting over time if the current gas limit is different.") private Long targetGasLimit = null; @CommandLine.ArgGroup(validate = false) @@ -202,6 +212,7 @@ public void validate( asList( "--miner-coinbase", "--min-gas-price", + "--min-priority-fee", "--min-block-occupancy-ratio", "--miner-extra-data")); @@ -238,6 +249,7 @@ static MiningOptions fromConfig(final MiningParameters miningParameters) { miningOptions.stratumPort = miningParameters.getStratumPort(); miningOptions.extraData = miningParameters.getExtraData(); miningOptions.minTransactionGasPrice = miningParameters.getMinTransactionGasPrice(); + miningOptions.minPriorityFeePerGas = miningParameters.getMinPriorityFeePerGas(); miningOptions.minBlockOccupancyRatio = miningParameters.getMinBlockOccupancyRatio(); miningOptions.unstableOptions.remoteSealersLimit = miningParameters.getUnstable().getRemoteSealersLimit(); @@ -266,6 +278,7 @@ public MiningParameters toDomainObject() { .isMiningEnabled(isMiningEnabled) .extraData(extraData) .minTransactionGasPrice(minTransactionGasPrice) + .minPriorityFeePerGas(minPriorityFeePerGas) .minBlockOccupancyRatio(minBlockOccupancyRatio); if (targetGasLimit != null) { diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcTestMethodsFactory.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcTestMethodsFactory.java index 518d5b8c364..fd6ca9a1313 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcTestMethodsFactory.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcTestMethodsFactory.java @@ -30,6 +30,7 @@ import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockImporter; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.manager.EthPeers; @@ -128,6 +129,7 @@ public Map methods() { final P2PNetwork peerDiscovery = mock(P2PNetwork.class); final EthPeers ethPeers = mock(EthPeers.class); final TransactionPool transactionPool = mock(TransactionPool.class); + final MiningParameters miningParameters = mock(MiningParameters.class); final PoWMiningCoordinator miningCoordinator = mock(PoWMiningCoordinator.class); final ObservableMetricsSystem metricsSystem = new NoOpMetricsSystem(); final Optional accountWhitelistController = @@ -169,6 +171,7 @@ public Map methods() { context, filterManager, transactionPool, + miningParameters, miningCoordinator, metricsSystem, new HashSet<>(), diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/JsonRpcMethodsFactory.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/JsonRpcMethodsFactory.java index 5effa4dd5da..c8a7ccb7529 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/JsonRpcMethodsFactory.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/JsonRpcMethodsFactory.java @@ -23,6 +23,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.manager.EthPeers; @@ -62,6 +63,7 @@ public Map methods( final ProtocolContext protocolContext, final FilterManager filterManager, final TransactionPool transactionPool, + final MiningParameters miningParameters, final MiningCoordinator miningCoordinator, final ObservableMetricsSystem metricsSystem, final Set supportedCapabilities, @@ -126,7 +128,7 @@ public Map methods( jsonRpcConfiguration, webSocketConfiguration, metricsConfiguration), - new MinerJsonRpcMethods(miningCoordinator), + new MinerJsonRpcMethods(miningParameters, miningCoordinator), new PermJsonRpcMethods(accountsAllowlistController, nodeAllowlistController), new PrivJsonRpcMethods( blockchainQueries, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/MinerJsonRpcMethods.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/MinerJsonRpcMethods.java index 35d6502ad3f..c0888bcff84 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/MinerJsonRpcMethods.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/MinerJsonRpcMethods.java @@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner.MinerStart; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner.MinerStop; import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; +import org.hyperledger.besu.ethereum.core.MiningParameters; import java.util.Map; @@ -29,7 +30,8 @@ public class MinerJsonRpcMethods extends ApiGroupJsonRpcMethods { private final MiningCoordinator miningCoordinator; - public MinerJsonRpcMethods(final MiningCoordinator miningCoordinator) { + public MinerJsonRpcMethods( + final MiningParameters miningParameters, final MiningCoordinator miningCoordinator) { this.miningCoordinator = miningCoordinator; } diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/AbstractJsonRpcHttpServiceTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/AbstractJsonRpcHttpServiceTest.java index d998f54c7e4..b0fc14e63bc 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/AbstractJsonRpcHttpServiceTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/AbstractJsonRpcHttpServiceTest.java @@ -33,6 +33,7 @@ import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.blockcreation.PoWMiningCoordinator; import org.hyperledger.besu.ethereum.core.BlockchainSetupUtil; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.core.Transaction; @@ -133,6 +134,7 @@ protected Map getRpcMethods( final Synchronizer synchronizerMock = mock(Synchronizer.class); final P2PNetwork peerDiscoveryMock = mock(P2PNetwork.class); final TransactionPool transactionPoolMock = mock(TransactionPool.class); + final MiningParameters miningParameters = mock(MiningParameters.class); final PoWMiningCoordinator miningCoordinatorMock = mock(PoWMiningCoordinator.class); when(transactionPoolMock.addTransactionViaApi(any(Transaction.class))) .thenReturn(ValidationResult.valid()); @@ -173,6 +175,7 @@ protected Map getRpcMethods( protocolContext, filterManager, transactionPoolMock, + miningParameters, miningCoordinatorMock, new NoOpMetricsSystem(), supportedCapabilities, diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceHostAllowlistTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceHostAllowlistTest.java index 961970615fb..208c3d5779b 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceHostAllowlistTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceHostAllowlistTest.java @@ -28,6 +28,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.blockcreation.PoWMiningCoordinator; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.EthProtocol; @@ -110,6 +111,7 @@ public void initServerAndClient() throws Exception { mock(ProtocolContext.class), mock(FilterManager.class), mock(TransactionPool.class), + mock(MiningParameters.class), mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(), supportedCapabilities, diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceLoginTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceLoginTest.java index 481aedd8ad7..d86bcbd81c0 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceLoginTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceLoginTest.java @@ -35,6 +35,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.blockcreation.PoWMiningCoordinator; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.EthProtocol; @@ -139,6 +140,7 @@ public static void initServerAndClient() throws Exception { mock(ProtocolContext.class), mock(FilterManager.class), mock(TransactionPool.class), + mock(MiningParameters.class), mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(), supportedCapabilities, diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceRpcApisTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceRpcApisTest.java index 52b942b7238..fcbb2116c9a 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceRpcApisTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceRpcApisTest.java @@ -35,6 +35,7 @@ import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.core.Synchronizer; @@ -212,6 +213,7 @@ private JsonRpcHttpService createJsonRpcHttpServiceWithRpcApis(final JsonRpcConf mock(ProtocolContext.class), mock(FilterManager.class), mock(TransactionPool.class), + mock(MiningParameters.class), mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(), supportedCapabilities, @@ -321,6 +323,7 @@ private JsonRpcHttpService createJsonRpcHttpService( mock(ProtocolContext.class), mock(FilterManager.class), mock(TransactionPool.class), + mock(MiningParameters.class), mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(), supportedCapabilities, diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTestBase.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTestBase.java index 94ec09b2367..8299cf70aa1 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTestBase.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTestBase.java @@ -29,6 +29,7 @@ import org.hyperledger.besu.ethereum.blockcreation.PoWMiningCoordinator; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.ChainHead; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.EthProtocol; @@ -118,6 +119,7 @@ public static void initServerAndClient() throws Exception { mock(ProtocolContext.class), mock(FilterManager.class), mock(TransactionPool.class), + mock(MiningParameters.class), mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(), supportedCapabilities, diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsClientAuthTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsClientAuthTest.java index 75612fa1fb8..2cefd7633e8 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsClientAuthTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsClientAuthTest.java @@ -35,6 +35,7 @@ import org.hyperledger.besu.ethereum.api.tls.SelfSignedP12Certificate; import org.hyperledger.besu.ethereum.api.tls.TlsConfiguration; import org.hyperledger.besu.ethereum.blockcreation.PoWMiningCoordinator; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.EthProtocol; @@ -123,6 +124,7 @@ public void initServer() throws Exception { mock(ProtocolContext.class), mock(FilterManager.class), mock(TransactionPool.class), + mock(MiningParameters.class), mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(), supportedCapabilities, diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsMisconfigurationTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsMisconfigurationTest.java index 6e1ade32850..c6e4a933ea0 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsMisconfigurationTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsMisconfigurationTest.java @@ -34,6 +34,7 @@ import org.hyperledger.besu.ethereum.api.tls.SelfSignedP12Certificate; import org.hyperledger.besu.ethereum.api.tls.TlsConfiguration; import org.hyperledger.besu.ethereum.blockcreation.PoWMiningCoordinator; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.EthProtocol; @@ -112,6 +113,7 @@ public void beforeEach() { mock(ProtocolContext.class), mock(FilterManager.class), mock(TransactionPool.class), + mock(MiningParameters.class), mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(), supportedCapabilities, diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsTest.java index 853412376c7..3fffd3561f0 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTlsTest.java @@ -34,6 +34,7 @@ import org.hyperledger.besu.ethereum.api.tls.SelfSignedP12Certificate; import org.hyperledger.besu.ethereum.api.tls.TlsConfiguration; import org.hyperledger.besu.ethereum.blockcreation.PoWMiningCoordinator; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.EthProtocol; @@ -113,6 +114,7 @@ public void initServer() throws Exception { mock(ProtocolContext.class), mock(FilterManager.class), mock(TransactionPool.class), + mock(MiningParameters.class), mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(), supportedCapabilities, diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/WebSocketServiceLoginTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/WebSocketServiceLoginTest.java index 622dd3c1197..072c493d696 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/WebSocketServiceLoginTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/WebSocketServiceLoginTest.java @@ -41,6 +41,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.subscription.SubscriptionManager; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.blockcreation.PoWMiningCoordinator; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Synchronizer; import org.hyperledger.besu.ethereum.eth.EthProtocol; @@ -174,6 +175,7 @@ public void before() throws URISyntaxException { mock(ProtocolContext.class), mock(FilterManager.class), mock(TransactionPool.class), + mock(MiningParameters.class), mock(PoWMiningCoordinator.class), new NoOpMetricsSystem(), supportedCapabilities, diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java index 298dc87d573..2a81c48949b 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java @@ -69,6 +69,15 @@ public MiningParameters setMinTransactionGasPrice(final Wei minTransactionGasPri return this; } + public Wei getMinPriorityFeePerGas() { + return getUpdatableRuntimeValues().minPriorityFeePerGas; + } + + public MiningParameters setMinPriorityFeePerGas(final Wei minPriorityFeePerGas) { + getUpdatableRuntimeValues().minPriorityFeePerGas = minPriorityFeePerGas; + return this; + } + public OptionalLong getTargetGasLimit() { return getUpdatableRuntimeValues().targetGasLimit; } @@ -130,6 +139,7 @@ public UpdatableInitValues getUpdatableInitValues() { public interface UpdatableInitValues { Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY; Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); + Wei DEFAULT_MIN_PRIORITY_FEE_PER_GAS = Wei.ZERO; double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; UpdatableInitValues DEFAULT = ImmutableMiningParameters.UpdatableInitValues.builder().build(); @@ -149,6 +159,11 @@ default Wei getMinTransactionGasPrice() { return DEFAULT_MIN_TRANSACTION_GAS_PRICE; } + @Value.Default + default Wei getMinPriorityFeePerGas() { + return DEFAULT_MIN_PRIORITY_FEE_PER_GAS; + } + @Value.Default default double getMinBlockOccupancyRatio() { return DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; @@ -163,6 +178,7 @@ static class UpdatableRuntimeValues { private volatile boolean miningEnabled; private volatile Bytes extraData; private volatile Wei minTransactionGasPrice; + private volatile Wei minPriorityFeePerGas; private volatile double minBlockOccupancyRatio; private volatile OptionalLong targetGasLimit; private volatile Optional> nonceGenerator; @@ -171,6 +187,7 @@ private UpdatableRuntimeValues(final UpdatableInitValues initValues) { miningEnabled = initValues.isMiningEnabled(); extraData = initValues.getExtraData(); minTransactionGasPrice = initValues.getMinTransactionGasPrice(); + minPriorityFeePerGas = initValues.getMinPriorityFeePerGas(); minBlockOccupancyRatio = initValues.getMinBlockOccupancyRatio(); targetGasLimit = initValues.getTargetGasLimit(); nonceGenerator = initValues.nonceGenerator(); @@ -185,6 +202,7 @@ public boolean equals(final Object o) { && Double.compare(minBlockOccupancyRatio, that.minBlockOccupancyRatio) == 0 && Objects.equals(extraData, that.extraData) && Objects.equals(minTransactionGasPrice, that.minTransactionGasPrice) + && Objects.equals(minPriorityFeePerGas, that.minPriorityFeePerGas) && Objects.equals(targetGasLimit, that.targetGasLimit) && Objects.equals(nonceGenerator, that.nonceGenerator); } @@ -195,6 +213,7 @@ public int hashCode() { miningEnabled, extraData, minTransactionGasPrice, + minPriorityFeePerGas, minBlockOccupancyRatio, targetGasLimit, nonceGenerator); @@ -209,6 +228,8 @@ public String toString() { + extraData + ", minTransactionGasPrice=" + minTransactionGasPrice + + ", minPriorityFeePerGas=" + + minPriorityFeePerGas + ", minBlockOccupancyRatio=" + minBlockOccupancyRatio + ", targetGasLimit=" From 84919f44728512dc3c1aa5cd752ee7bf7c25d132 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Mon, 16 Oct 2023 11:31:26 +0200 Subject: [PATCH 11/24] Remove not relevant for this feature Signed-off-by: Fabio Di Fabio --- .../txselection/BlockTransactionSelector.java | 40 +------------------ 1 file changed, 2 insertions(+), 38 deletions(-) diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java index 67b6b950053..eb076f52e42 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java @@ -48,11 +48,6 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.CancellationException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import org.slf4j.Logger; @@ -92,7 +87,6 @@ public class BlockTransactionSelector { private final List transactionSelectors; private final PluginTransactionSelector pluginTransactionSelector; private final OperationTracer pluginOperationTracer; - private final AtomicBoolean isTimeout = new AtomicBoolean(false); public BlockTransactionSelector( final MiningParameters miningParameters, @@ -155,7 +149,7 @@ public TransactionSelectionResults buildTransactionListForBlock() { .setMessage("Transaction pool stats {}") .addArgument(blockSelectionContext.transactionPool().logStats()) .log(); - timeLimitedSelection(); + blockSelectionContext.transactionPool().selectTransactions(this::evaluateTransaction); LOG.atTrace() .setMessage("Transaction selection result {}") .addArgument(transactionSelectionResults::toTraceLog) @@ -163,29 +157,6 @@ public TransactionSelectionResults buildTransactionListForBlock() { return transactionSelectionResults; } - private void timeLimitedSelection() { - final var txSelection = - CompletableFuture.runAsync( - () -> - blockSelectionContext - .transactionPool() - .selectTransactions(this::evaluateTransaction)); - - try { - txSelection.get(5000, TimeUnit.MILLISECONDS); - } catch (InterruptedException | ExecutionException e) { - if (isCancelled.get()) { - throw new CancellationException("Cancelled during transaction selection."); - } - LOG.warn("Error during block transaction selection", e); - } catch (TimeoutException e) { - synchronized (isTimeout) { - isTimeout.set(true); - } - LOG.warn("Timeout during block transaction selection, interrupting transaction selection", e); - } - } - /** * Evaluates a list of transactions and updates the selection results accordingly. If a * transaction is not selected during the evaluation, it is updated as not selected in the @@ -230,14 +201,7 @@ private TransactionSelectionResult evaluateTransaction( return handleTransactionNotSelected(pendingTransaction, postProcessingSelectionResult); } - synchronized (isTimeout) { - if (!isTimeout.get()) { - return handleTransactionSelected(pendingTransaction, processingResult, worldStateUpdater); - } else { - return handleTransactionNotSelected( - pendingTransaction, TransactionSelectionResult.BLOCK_SELECTION_TIMEOUT); - } - } + return handleTransactionSelected(pendingTransaction, processingResult, worldStateUpdater); } /** From e89a2440aa056eacee600ce0f05f17d7af01ecba Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Mon, 16 Oct 2023 11:31:26 +0200 Subject: [PATCH 12/24] Remove not relevant for this feature Signed-off-by: Fabio Di Fabio --- .../txselection/BlockTransactionSelector.java | 40 +------------------ 1 file changed, 2 insertions(+), 38 deletions(-) diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java index 67b6b950053..eb076f52e42 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java @@ -48,11 +48,6 @@ import java.util.List; import java.util.Optional; import java.util.concurrent.CancellationException; -import java.util.concurrent.CompletableFuture; -import java.util.concurrent.ExecutionException; -import java.util.concurrent.TimeUnit; -import java.util.concurrent.TimeoutException; -import java.util.concurrent.atomic.AtomicBoolean; import java.util.function.Supplier; import org.slf4j.Logger; @@ -92,7 +87,6 @@ public class BlockTransactionSelector { private final List transactionSelectors; private final PluginTransactionSelector pluginTransactionSelector; private final OperationTracer pluginOperationTracer; - private final AtomicBoolean isTimeout = new AtomicBoolean(false); public BlockTransactionSelector( final MiningParameters miningParameters, @@ -155,7 +149,7 @@ public TransactionSelectionResults buildTransactionListForBlock() { .setMessage("Transaction pool stats {}") .addArgument(blockSelectionContext.transactionPool().logStats()) .log(); - timeLimitedSelection(); + blockSelectionContext.transactionPool().selectTransactions(this::evaluateTransaction); LOG.atTrace() .setMessage("Transaction selection result {}") .addArgument(transactionSelectionResults::toTraceLog) @@ -163,29 +157,6 @@ public TransactionSelectionResults buildTransactionListForBlock() { return transactionSelectionResults; } - private void timeLimitedSelection() { - final var txSelection = - CompletableFuture.runAsync( - () -> - blockSelectionContext - .transactionPool() - .selectTransactions(this::evaluateTransaction)); - - try { - txSelection.get(5000, TimeUnit.MILLISECONDS); - } catch (InterruptedException | ExecutionException e) { - if (isCancelled.get()) { - throw new CancellationException("Cancelled during transaction selection."); - } - LOG.warn("Error during block transaction selection", e); - } catch (TimeoutException e) { - synchronized (isTimeout) { - isTimeout.set(true); - } - LOG.warn("Timeout during block transaction selection, interrupting transaction selection", e); - } - } - /** * Evaluates a list of transactions and updates the selection results accordingly. If a * transaction is not selected during the evaluation, it is updated as not selected in the @@ -230,14 +201,7 @@ private TransactionSelectionResult evaluateTransaction( return handleTransactionNotSelected(pendingTransaction, postProcessingSelectionResult); } - synchronized (isTimeout) { - if (!isTimeout.get()) { - return handleTransactionSelected(pendingTransaction, processingResult, worldStateUpdater); - } else { - return handleTransactionNotSelected( - pendingTransaction, TransactionSelectionResult.BLOCK_SELECTION_TIMEOUT); - } - } + return handleTransactionSelected(pendingTransaction, processingResult, worldStateUpdater); } /** From 2267bc7f142d4fc89b4dfb32df72005e49fcb6c9 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 17 Oct 2023 15:16:55 +0200 Subject: [PATCH 13/24] Fix javadoc Signed-off-by: Fabio Di Fabio --- .../common/bft/blockcreation/BftBlockCreatorFactory.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java index 528f4e72062..fab04b1a770 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreatorFactory.java @@ -51,8 +51,9 @@ public class BftBlockCreatorFactory { /** The Forks schedule. */ protected final ForksSchedule forksSchedule; - + /** The Mining parameters */ protected final MiningParameters miningParameters; + private final TransactionPool transactionPool; /** The Protocol context. */ protected final ProtocolContext protocolContext; From c6b56d241d195eb20cd81beb10307756eb42d8e3 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 17 Oct 2023 15:21:39 +0200 Subject: [PATCH 14/24] Remove code not belonging to this PR Signed-off-by: Fabio Di Fabio --- .../besu/plugin/data/TransactionSelectionResult.java | 6 ------ 1 file changed, 6 deletions(-) diff --git a/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/TransactionSelectionResult.java b/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/TransactionSelectionResult.java index dee35f82b7b..ffae842ca72 100644 --- a/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/TransactionSelectionResult.java +++ b/plugin-api/src/main/java/org/hyperledger/besu/plugin/data/TransactionSelectionResult.java @@ -28,7 +28,6 @@ private enum Status { SELECTED, BLOCK_FULL(true, false), BLOCK_OCCUPANCY_ABOVE_THRESHOLD(true, false), - BLOCK_SELECTION_TIMEOUT(true, false), INVALID_TRANSIENT(false, false), INVALID(false, true); @@ -57,11 +56,6 @@ public String toString() { /** The transaction has not been selected since the block is full. */ public static final TransactionSelectionResult BLOCK_FULL = new TransactionSelectionResult(Status.BLOCK_FULL); - /** There was no more time to add transaction to the block */ - public static final TransactionSelectionResult BLOCK_SELECTION_TIMEOUT = - new TransactionSelectionResult(Status.BLOCK_SELECTION_TIMEOUT); - ; - /** * The transaction has not been selected since too large and the occupancy of the block is enough * to stop the selection. From 477acf93deeb5c3ab950fa1e27f37357645c2f8d Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 17 Oct 2023 16:04:55 +0200 Subject: [PATCH 15/24] coinbase is an updatable parameter Signed-off-by: Fabio Di Fabio --- .../BesuNodeConfigurationBuilder.java | 6 ++++- .../node/configuration/BesuNodeFactory.java | 2 +- .../bft/BftMiningAcceptanceTest.java | 2 +- .../cli/options/stable/MiningOptions.java | 10 +++---- .../subcommands/blocks/BlocksSubCommand.java | 2 +- .../controller/IbftBesuControllerBuilder.java | 1 + .../hyperledger/besu/cli/BesuCommandTest.java | 11 ++++++-- .../cli/options/stable/MiningOptionsTest.java | 2 +- .../blockcreation/CliqueBlockCreator.java | 4 --- .../blockcreation/CliqueMinerExecutor.java | 4 +-- .../blockcreation/CliqueBlockCreatorTest.java | 5 +--- .../CliqueMinerExecutorTest.java | 2 +- .../bft/blockcreation/BftBlockCreator.java | 1 - .../ibft/support/TestContextBuilder.java | 2 +- .../blockcreation/BftBlockCreatorTest.java | 2 +- .../blockcreation/MergeBlockCreator.java | 5 +--- .../merge/blockcreation/MergeCoordinator.java | 4 ++- .../blockcreation/MergeCoordinatorTest.java | 9 +++---- .../merge/blockcreation/MergeReorgTest.java | 5 +++- .../qbft/support/TestContextBuilder.java | 2 +- .../blockcreation/AbstractBlockCreator.java | 5 +--- .../blockcreation/PoWBlockCreator.java | 5 +--- .../blockcreation/PoWMinerExecutor.java | 9 +++---- .../AbstractBlockCreatorTest.java | 5 +--- .../blockcreation/PoWBlockCreatorTest.java | 22 +++++----------- .../besu/ethereum/core/MiningParameters.java | 19 ++++++++++++-- .../bonsai/AbstractIsolationTests.java | 5 +--- .../ethereum/retesteth/RetestethContext.java | 26 ++++++++++--------- .../retesteth/methods/TestMineBlocks.java | 15 ++--------- 29 files changed, 90 insertions(+), 102 deletions(-) diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java index 287f4fe6cfe..6e925f6a2c7 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java @@ -30,6 +30,7 @@ import org.hyperledger.besu.ethereum.api.tls.FileBasedPasswordProvider; import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.p2p.config.NetworkingConfiguration; @@ -56,7 +57,10 @@ public class BesuNodeConfigurationBuilder { private String name; private Optional dataPath = Optional.empty(); private MiningParameters miningParameters = - ImmutableMiningParameters.builder().coinbase(AddressHelpers.ofValue(1)).build(); + ImmutableMiningParameters.builder() + .updatableInitValues( + UpdatableInitValues.builder().coinbase(AddressHelpers.ofValue(1)).build()) + .build(); private JsonRpcConfiguration jsonRpcConfiguration = JsonRpcConfiguration.createDefault(); private JsonRpcConfiguration engineRpcConfiguration = JsonRpcConfiguration.createEngineDefault(); diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java index fc61b998a50..7960fd46437 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java @@ -310,8 +310,8 @@ public BesuNode createNodeWithMultiTenantedPrivacy( UpdatableInitValues.builder() .isMiningEnabled(true) .minTransactionGasPrice(Wei.ZERO) + .coinbase(AddressHelpers.ofValue(1)) .build()) - .coinbase(AddressHelpers.ofValue(1)) .build(); return create( diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java index b4732cc7113..8093661ebeb 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java @@ -66,8 +66,8 @@ public void shouldMineOnSingleNodeWithFreeGas_Berlin() throws Exception { UpdatableInitValues.builder() .isMiningEnabled(true) .minTransactionGasPrice(Wei.ZERO) + .coinbase(AddressHelpers.ofValue(1)) .build()) - .coinbase(AddressHelpers.ofValue(1)) .build(); minerNode.setMiningParameters(zeroGasMiningParams); diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java index b1b87321af5..29733ed0b89 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java @@ -30,6 +30,7 @@ import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import java.util.List; @@ -262,7 +263,7 @@ static MiningOptions fromConfig(final MiningParameters miningParameters) { @Override public MiningParameters toDomainObject() { final var updatableInitValuesBuilder = - ImmutableMiningParameters.UpdatableInitValues.builder() + UpdatableInitValues.builder() .isMiningEnabled(isMiningEnabled) .extraData(extraData) .minTransactionGasPrice(minTransactionGasPrice) @@ -271,6 +272,9 @@ public MiningParameters toDomainObject() { if (targetGasLimit != null) { updatableInitValuesBuilder.targetGasLimit(targetGasLimit); } + if (coinbase != null) { + updatableInitValuesBuilder.coinbase(coinbase); + } final var miningParametersBuilder = ImmutableMiningParameters.builder() @@ -290,10 +294,6 @@ public MiningParameters toDomainObject() { unstableOptions.posBlockCreationRepetitionMinDuration) .build()); - if (coinbase != null) { - miningParametersBuilder.coinbase(coinbase); - } - return miningParametersBuilder.build(); } diff --git a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java index c8579c2263f..3242ce9799a 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java @@ -275,8 +275,8 @@ private MiningParameters getMiningParameters() { .nonceGenerator(new IncrementingNonceGenerator(0)) .extraData(extraData) .minTransactionGasPrice(minTransactionGasPrice) + .coinbase(coinbase) .build()) - .coinbase(coinbase) .build(); } 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 40765769e6e..1f9fd70f745 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java @@ -145,6 +145,7 @@ protected MiningCoordinator createMiningCoordinator( final Address localAddress = Util.publicKeyToAddress(nodeKey.getPublicKey()); final BftProtocolSchedule bftProtocolSchedule = (BftProtocolSchedule) protocolSchedule; + miningParameters.setCoinbase(localAddress); final BftBlockCreatorFactory blockCreatorFactory = new BftBlockCreatorFactory<>( transactionPool, 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 013da67e8c2..8f2124ddfa9 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -71,6 +71,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.api.tls.TlsConfiguration; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -902,7 +903,10 @@ public void envVariableOverridesValueFromConfigFile() { verify(mockControllerBuilder) .miningParameters( ImmutableMiningParameters.builder() - .coinbase(Address.fromHexString(expectedCoinbase)) + .updatableInitValues( + UpdatableInitValues.builder() + .coinbase(Address.fromHexString(expectedCoinbase)) + .build()) .build()); } @@ -916,7 +920,10 @@ public void cliOptionOverridesEnvVariableAndConfig() { verify(mockControllerBuilder) .miningParameters( ImmutableMiningParameters.builder() - .coinbase(Address.fromHexString(expectedCoinbase)) + .updatableInitValues( + UpdatableInitValues.builder() + .coinbase(Address.fromHexString(expectedCoinbase)) + .build()) .build()); } diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java index 5fe050067ad..95a83e7ce87 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java @@ -322,8 +322,8 @@ protected MiningParameters createCustomizedDomainObject() { .isMiningEnabled(true) .extraData(Bytes.fromHexString("0xabc321")) .minBlockOccupancyRatio(0.5) + .coinbase(Address.ZERO) .build()) - .coinbase(Address.ZERO) .isStratumMiningEnabled(true) .unstable(Unstable.builder().posBlockCreationMaxTime(1000).build()) .build(); diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java index 1f4206b7ec8..d991fb9db4c 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreator.java @@ -23,7 +23,6 @@ import org.hyperledger.besu.consensus.common.EpochManager; import org.hyperledger.besu.consensus.common.validator.ValidatorVote; import org.hyperledger.besu.cryptoservices.NodeKey; -import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.blockcreation.AbstractBlockCreator; @@ -49,7 +48,6 @@ public class CliqueBlockCreator extends AbstractBlockCreator { * Instantiates a new Clique block creator. * * @param miningParameters the mining parameters - * @param coinbase the coinbase * @param extraDataCalculator the extra data calculator * @param transactionPool the pending transactions * @param protocolContext the protocol context @@ -60,7 +58,6 @@ public class CliqueBlockCreator extends AbstractBlockCreator { */ public CliqueBlockCreator( final MiningParameters miningParameters, - final Address coinbase, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, @@ -70,7 +67,6 @@ public CliqueBlockCreator( final EpochManager epochManager) { super( miningParameters, - coinbase, __ -> Util.publicKeyToAddress(nodeKey.getPublicKey()), extraDataCalculator, transactionPool, diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java index ac06e776e44..81b754b267c 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutor.java @@ -71,6 +71,7 @@ public CliqueMinerExecutor( this.nodeKey = nodeKey; this.localAddress = Util.publicKeyToAddress(nodeKey.getPublicKey()); this.epochManager = epochManager; + miningParams.setCoinbase(localAddress); } @Override @@ -82,7 +83,6 @@ public CliqueBlockMiner createMiner( (header) -> new CliqueBlockCreator( miningParameters, - localAddress, // TOOD(tmm): This can be removed (used for voting not coinbase). this::calculateExtraData, transactionPool, protocolContext, @@ -103,7 +103,7 @@ public CliqueBlockMiner createMiner( @Override public Optional
getCoinbase() { - return Optional.of(localAddress); + return miningParameters.getCoinbase(); } /** diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java index 787eff3bda6..208d5ac64b5 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java @@ -141,7 +141,6 @@ public void proposerAddressCanBeExtractFromAConstructedBlock() { final CliqueBlockCreator blockCreator = new CliqueBlockCreator( miningParameters, - coinbase, parent -> extraData, createTransactionPool(), protocolContext, @@ -170,7 +169,6 @@ public void insertsValidVoteIntoConstructedBlock() { final CliqueBlockCreator blockCreator = new CliqueBlockCreator( miningParameters, - coinbase, parent -> extraData, createTransactionPool(), protocolContext, @@ -204,7 +202,6 @@ public void insertsNoVoteWhenAtEpoch() { final CliqueBlockCreator blockCreator = new CliqueBlockCreator( miningParameters, - coinbase, parent -> extraData, createTransactionPool(), protocolContext, @@ -252,8 +249,8 @@ private static MiningParameters createMiningParameters( .extraData(extraData) .targetGasLimit(10_000_000L) .minTransactionGasPrice(Wei.ZERO) + .coinbase(coinbase) .build()) - .coinbase(coinbase) .build(); return miningParameters; } diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java index 6bd197cd908..a538a491b67 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java @@ -240,8 +240,8 @@ private static MiningParameters createMiningParameters(final Bytes vanityData) { UpdatableInitValues.builder() .extraData(vanityData) .minTransactionGasPrice(Wei.ZERO) + .coinbase(AddressHelpers.ofValue(1)) .build()) - .coinbase(AddressHelpers.ofValue(1)) .build(); } } diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java index 692d64e7988..47bf915a142 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java @@ -63,7 +63,6 @@ public BftBlockCreator( final BftExtraDataCodec bftExtraDataCodec) { super( miningParameters, - localAddress, miningBeneficiaryCalculator(localAddress, forksSchedule), extraDataCalculator, transactionPool, diff --git a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java index 88eba5b8930..41fbbbe1940 100644 --- a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java +++ b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java @@ -312,8 +312,8 @@ private static ControllerAndState createControllerAndFinalState( .isMiningEnabled(true) .minTransactionGasPrice(Wei.ZERO) .extraData(Bytes.wrap("Ibft Int tests".getBytes(UTF_8))) + .coinbase(AddressHelpers.ofValue(1)) .build()) - .coinbase(AddressHelpers.ofValue(1)) .build(); final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions(); diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java index 14c1eddc70f..afd967a2caf 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java @@ -165,8 +165,8 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( 0, initialValidatorList))) .minTransactionGasPrice(Wei.ZERO) + .coinbase(AddressHelpers.ofValue(1)) .build()) - .coinbase(AddressHelpers.ofValue(1)) .build(); final BftBlockCreator blockCreator = diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java index 294e0943598..b81a941816a 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeBlockCreator.java @@ -44,7 +44,6 @@ class MergeBlockCreator extends AbstractBlockCreator { * @param transactionPool the pending transactions * @param protocolContext the protocol context * @param protocolSchedule the protocol schedule - * @param miningBeneficiary the mining beneficiary * @param parentHeader the parent header */ public MergeBlockCreator( @@ -53,13 +52,11 @@ public MergeBlockCreator( final TransactionPool transactionPool, final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule, - final Address miningBeneficiary, final BlockHeader parentHeader, final Optional
depositContractAddress) { super( miningParameters, - miningBeneficiary, - __ -> miningBeneficiary, + __ -> miningParameters.getCoinbase().orElseThrow(), extraDataCalculator, transactionPool, protocolContext, diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java index 308fd9b4aba..b83e607ef4b 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java @@ -118,6 +118,9 @@ public MergeCoordinator( this.mergeContext = protocolContext.getConsensusContext(MergeContext.class); this.backwardSyncContext = backwardSyncContext; + if (miningParams.getCoinbase().isEmpty()) { + miningParams.setCoinbase(Address.ZERO); + } if (miningParams.getTargetGasLimit().isEmpty()) { miningParams.setTargetGasLimit(30000000L); } @@ -133,7 +136,6 @@ public MergeCoordinator( transactionPool, protocolContext, protocolSchedule, - address.or(miningParameters::getCoinbase).orElse(Address.ZERO), parentHeader, depositContractAddress); diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java index 28fe40d5d70..3eeb87539bd 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java @@ -57,6 +57,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.Unstable; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.TransactionTestFixture; @@ -134,9 +135,9 @@ public class MergeCoordinatorTest implements MergeGenesisConfigHelper { MiningParameters miningParameters = ImmutableMiningParameters.builder() - .coinbase(coinbase) + .updatableInitValues(UpdatableInitValues.builder().coinbase(coinbase).build()) .unstable( - ImmutableMiningParameters.Unstable.builder() + Unstable.builder() .posBlockCreationRepetitionMinDuration(REPETITION_MIN_DURATION) .build()) .build(); @@ -285,7 +286,6 @@ public void exceptionDuringBuildingBlockShouldNotBeInvalid() transactionPool, protocolContext, protocolSchedule, - address.or(miningParameters::getCoinbase).orElse(Address.ZERO), parentHeader, Optional.empty())); @@ -551,8 +551,7 @@ public void shouldStopRetryBlockCreationIfTimeExpired() throws InterruptedExcept miningParameters = ImmutableMiningParameters.builder() .from(miningParameters) - .unstable( - ImmutableMiningParameters.Unstable.builder().posBlockCreationMaxTime(100).build()) + .unstable(Unstable.builder().posBlockCreationMaxTime(100).build()) .build(); doAnswer( invocation -> { diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java index 4c9712c9b47..75de7e190d3 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java @@ -34,6 +34,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.eth.sync.backwardsync.BackwardSyncContext; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator; @@ -93,7 +94,9 @@ public void setUp() { mockProtocolSchedule, CompletableFuture::runAsync, mockTransactionPool, - ImmutableMiningParameters.builder().coinbase(coinbase).build(), + ImmutableMiningParameters.builder() + .updatableInitValues(UpdatableInitValues.builder().coinbase(coinbase).build()) + .build(), mock(BackwardSyncContext.class), Optional.empty()); mergeContext.setIsPostMerge(genesisState.getBlock().getHeader().getDifficulty()); 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 afbc2742637..c1a05a9709e 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 @@ -372,8 +372,8 @@ private static ControllerAndState createControllerAndFinalState( .isMiningEnabled(true) .minTransactionGasPrice(Wei.ZERO) .extraData(Bytes.wrap("Qbft Int tests".getBytes(UTF_8))) + .coinbase(AddressHelpers.ofValue(1)) .build()) - .coinbase(AddressHelpers.ofValue(1)) .build(); final StubGenesisConfigOptions genesisConfigOptions = new StubGenesisConfigOptions(); diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java index 060771b7ca6..a8bb17e93cd 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreator.java @@ -79,7 +79,6 @@ public interface ExtraDataCalculator { private static final Logger LOG = LoggerFactory.getLogger(AbstractBlockCreator.class); - protected final Address coinbase; private final MiningBeneficiaryCalculator miningBeneficiaryCalculator; private final ExtraDataCalculator extraDataCalculator; private final TransactionPool transactionPool; @@ -94,7 +93,6 @@ public interface ExtraDataCalculator { protected AbstractBlockCreator( final MiningParameters miningParameters, - final Address coinbase, final MiningBeneficiaryCalculator miningBeneficiaryCalculator, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, @@ -103,7 +101,6 @@ protected AbstractBlockCreator( final BlockHeader parentHeader, final Optional
depositContractAddress) { this.miningParameters = miningParameters; - this.coinbase = coinbase; this.miningBeneficiaryCalculator = miningBeneficiaryCalculator; this.extraDataCalculator = extraDataCalculator; this.transactionPool = transactionPool; @@ -411,7 +408,7 @@ private ProcessableBlockHeader createPendingBlockHeader( final Bytes32 parentBeaconBlockRoot = maybeParentBeaconBlockRoot.orElse(null); return BlockHeaderBuilder.create() .parentHash(parentHeader.getHash()) - .coinbase(coinbase) + .coinbase(miningParameters.getCoinbase().orElseThrow()) .difficulty(Difficulty.of(difficulty)) .number(newBlockNumber) .gasLimit(gasLimit) diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java index 032ad0b8fed..66c57379ccb 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreator.java @@ -14,7 +14,6 @@ */ package org.hyperledger.besu.ethereum.blockcreation; -import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder; @@ -40,7 +39,6 @@ public class PoWBlockCreator extends AbstractBlockCreator { public PoWBlockCreator( final MiningParameters miningParameters, - final Address coinbase, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, final ProtocolContext protocolContext, @@ -49,8 +47,7 @@ public PoWBlockCreator( final BlockHeader parentHeader) { super( miningParameters, - coinbase, - __ -> coinbase, + __ -> miningParameters.getCoinbase().orElseThrow(), extraDataCalculator, transactionPool, protocolContext, diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java index f10fe3d7771..cd44318e960 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/PoWMinerExecutor.java @@ -32,7 +32,6 @@ public class PoWMinerExecutor extends AbstractMinerExecutor { - protected volatile Optional
coinbase; protected boolean stratumMiningEnabled; protected final EpochCalculator epochCalculator; @@ -44,7 +43,6 @@ public PoWMinerExecutor( final AbstractBlockScheduler blockScheduler, final EpochCalculator epochCalculator) { super(protocolContext, protocolSchedule, transactionPool, miningParams, blockScheduler); - this.coinbase = miningParams.getCoinbase(); if (miningParams.getNonceGenerator().isEmpty()) { miningParams.setNonceGenerator(new RandomNonceGenerator()); } @@ -56,7 +54,7 @@ public Optional startAsyncMining( final Subscribers observers, final Subscribers ethHashObservers, final BlockHeader parentHeader) { - if (coinbase.isEmpty()) { + if (miningParameters.getCoinbase().isEmpty()) { throw new CoinbaseNotSetException("Unable to start mining without a coinbase."); } return super.startAsyncMining(observers, ethHashObservers, parentHeader); @@ -82,7 +80,6 @@ public PoWBlockMiner createMiner( (header) -> new PoWBlockCreator( miningParameters, - coinbase.orElse(Address.ZERO), parent -> miningParameters.getExtraData(), transactionPool, protocolContext, @@ -98,7 +95,7 @@ public void setCoinbase(final Address coinbase) { if (coinbase == null) { throw new IllegalArgumentException("Coinbase cannot be unset."); } else { - this.coinbase = Optional.of(Address.wrap(coinbase.copy())); + miningParameters.setCoinbase(Address.wrap(coinbase.copy())); } } @@ -108,7 +105,7 @@ void setStratumMiningEnabled(final boolean stratumMiningEnabled) { @Override public Optional
getCoinbase() { - return coinbase; + return miningParameters.getCoinbase(); } public EpochCalculator getEpochCalculator() { diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java index 8a2e91f664f..3ed629cb935 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java @@ -392,13 +392,12 @@ private AbstractBlockCreator createBlockCreator( .extraData(Bytes.fromHexString("deadbeef")) .minTransactionGasPrice(Wei.ONE) .minBlockOccupancyRatio(0d) + .coinbase(Address.ZERO) .build()) - .coinbase(Address.ZERO) .build(); return new TestBlockCreator( miningParameters, - Address.ZERO, __ -> Address.ZERO, __ -> Bytes.fromHexString("deadbeef"), transactionPool, @@ -412,7 +411,6 @@ static class TestBlockCreator extends AbstractBlockCreator { protected TestBlockCreator( final MiningParameters miningParameters, - final Address coinbase, final MiningBeneficiaryCalculator miningBeneficiaryCalculator, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, @@ -422,7 +420,6 @@ protected TestBlockCreator( final Optional
depositContractAddress) { super( miningParameters, - coinbase, miningBeneficiaryCalculator, extraDataCalculator, transactionPool, diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java index 2d428dcc054..cddb0073f8d 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java @@ -94,8 +94,7 @@ void createMainnetBlock1() throws IOException { .createProtocolSchedule()) .build(); - final MiningParameters miningParameters = - createMiningParameters(Lists.newArrayList(BLOCK_1_NONCE)); + final MiningParameters miningParameters = createMiningParameters(); final PoWSolver solver = new PoWSolver( @@ -110,7 +109,6 @@ void createMainnetBlock1() throws IOException { final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, - BLOCK_1_COINBASE, parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), @@ -149,8 +147,7 @@ void createMainnetBlock1_fixedDifficulty1() { .createProtocolSchedule()) .build(); - final MiningParameters miningParameters = - createMiningParameters(Lists.newArrayList(BLOCK_1_NONCE)); + final MiningParameters miningParameters = createMiningParameters(); final PoWSolver solver = new PoWSolver( @@ -165,7 +162,6 @@ void createMainnetBlock1_fixedDifficulty1() { final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, - BLOCK_1_COINBASE, parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), @@ -195,8 +191,7 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsFalse() { final ExecutionContextTestFixture executionContextTestFixture = ExecutionContextTestFixture.builder().protocolSchedule(protocolSchedule).build(); - final MiningParameters miningParameters = - createMiningParameters(Lists.newArrayList(BLOCK_1_NONCE)); + final MiningParameters miningParameters = createMiningParameters(); final PoWSolver solver = new PoWSolver( @@ -211,7 +206,6 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsFalse() { final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, - BLOCK_1_COINBASE, parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), @@ -263,8 +257,7 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsTrue() { final ExecutionContextTestFixture executionContextTestFixture = ExecutionContextTestFixture.builder().protocolSchedule(protocolSchedule).build(); - final MiningParameters miningParameters = - createMiningParameters(Lists.newArrayList(BLOCK_1_NONCE)); + final MiningParameters miningParameters = createMiningParameters(); final PoWSolver solver = new PoWSolver( @@ -279,7 +272,6 @@ void rewardBeneficiary_zeroReward_skipZeroRewardsTrue() { final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, - BLOCK_1_COINBASE, parent -> BLOCK_1_EXTRA_DATA, transactionPool, executionContextTestFixture.getProtocolContext(), @@ -344,15 +336,15 @@ private TransactionPool createTransactionPool( return transactionPool; } - private MiningParameters createMiningParameters(final Iterable nonceList) { + private MiningParameters createMiningParameters() { return ImmutableMiningParameters.builder() .updatableInitValues( ImmutableMiningParameters.UpdatableInitValues.builder() - .nonceGenerator(nonceList) + .nonceGenerator(Lists.newArrayList(BLOCK_1_NONCE)) .extraData(BLOCK_1_EXTRA_DATA) .minTransactionGasPrice(Wei.ONE) + .coinbase(BLOCK_1_COINBASE) .build()) - .coinbase(BLOCK_1_COINBASE) .build(); } } diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java index 298dc87d573..ea14d863839 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java @@ -40,8 +40,6 @@ public static final MiningParameters newDefault() { return ImmutableMiningParameters.builder().build(); } - public abstract Optional
getCoinbase(); - public boolean isMiningEnabled() { return getUpdatableRuntimeValues().miningEnabled; } @@ -69,6 +67,15 @@ public MiningParameters setMinTransactionGasPrice(final Wei minTransactionGasPri return this; } + public Optional
getCoinbase() { + return getUpdatableRuntimeValues().coinbase; + } + + public MiningParameters setCoinbase(final Address coinbase) { + getUpdatableRuntimeValues().coinbase = Optional.of(coinbase); + return this; + } + public OptionalLong getTargetGasLimit() { return getUpdatableRuntimeValues().targetGasLimit; } @@ -154,6 +161,8 @@ default double getMinBlockOccupancyRatio() { return DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; } + Optional
getCoinbase(); + OptionalLong getTargetGasLimit(); Optional> nonceGenerator(); @@ -164,6 +173,7 @@ static class UpdatableRuntimeValues { private volatile Bytes extraData; private volatile Wei minTransactionGasPrice; private volatile double minBlockOccupancyRatio; + private volatile Optional
coinbase; private volatile OptionalLong targetGasLimit; private volatile Optional> nonceGenerator; @@ -172,6 +182,7 @@ private UpdatableRuntimeValues(final UpdatableInitValues initValues) { extraData = initValues.getExtraData(); minTransactionGasPrice = initValues.getMinTransactionGasPrice(); minBlockOccupancyRatio = initValues.getMinBlockOccupancyRatio(); + coinbase = initValues.getCoinbase(); targetGasLimit = initValues.getTargetGasLimit(); nonceGenerator = initValues.nonceGenerator(); } @@ -185,6 +196,7 @@ public boolean equals(final Object o) { && Double.compare(minBlockOccupancyRatio, that.minBlockOccupancyRatio) == 0 && Objects.equals(extraData, that.extraData) && Objects.equals(minTransactionGasPrice, that.minTransactionGasPrice) + && Objects.equals(coinbase, that.coinbase) && Objects.equals(targetGasLimit, that.targetGasLimit) && Objects.equals(nonceGenerator, that.nonceGenerator); } @@ -196,6 +208,7 @@ public int hashCode() { extraData, minTransactionGasPrice, minBlockOccupancyRatio, + coinbase, targetGasLimit, nonceGenerator); } @@ -211,6 +224,8 @@ public String toString() { + minTransactionGasPrice + ", minBlockOccupancyRatio=" + minBlockOccupancyRatio + + ", coinbase=" + + coinbase + ", targetGasLimit=" + targetGasLimit + ", nonceGenerator=" diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java index a51846b528e..0d30843cb38 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java @@ -207,7 +207,6 @@ public int getDatabaseVersion() { static class TestBlockCreator extends AbstractBlockCreator { private TestBlockCreator( final MiningParameters miningParameters, - final Address coinbase, final MiningBeneficiaryCalculator miningBeneficiaryCalculator, final ExtraDataCalculator extraDataCalculator, final TransactionPool transactionPool, @@ -216,7 +215,6 @@ private TestBlockCreator( final BlockHeader parentHeader) { super( miningParameters, - coinbase, miningBeneficiaryCalculator, extraDataCalculator, transactionPool, @@ -240,13 +238,12 @@ static TestBlockCreator forHeader( .targetGasLimit(30_000_000L) .minTransactionGasPrice(Wei.ONE) .minBlockOccupancyRatio(0d) + .coinbase(Address.ZERO) .build()) - .coinbase(Address.ZERO) .build(); return new TestBlockCreator( miningParameters, - Address.ZERO, __ -> Address.ZERO, __ -> Bytes.fromHexString("deadbeef"), transactionPool, diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java index 706120b1bfc..2327bfaae07 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java @@ -32,6 +32,8 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.Unstable; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; @@ -99,7 +101,7 @@ public class RetestethContext { private HeaderValidationMode headerValidationMode; private BlockReplay blockReplay; private RetestethClock retestethClock; - + private MiningParameters miningParameters; private TransactionPool transactionPool; private EthScheduler ethScheduler; private PoWSolver poWSolver; @@ -180,13 +182,17 @@ private boolean buildContext( ? HeaderValidationMode.LIGHT : HeaderValidationMode.FULL; - final MiningParameters miningParameters = + miningParameters = ImmutableMiningParameters.builder() - .unstable( - ImmutableMiningParameters.Unstable.builder() - .powJobTimeToLive(1000) - .maxOmmerDepth(8) + .updatableInitValues( + UpdatableInitValues.builder() + .coinbase(coinbase) + .extraData(extraData) + .targetGasLimit(blockchain.getChainHeadHeader().getGasLimit()) + .minBlockOccupancyRatio(0.0) + .minTransactionGasPrice(Wei.ZERO) .build()) + .unstable(Unstable.builder().powJobTimeToLive(1000).maxOmmerDepth(8).build()) .build(); miningParameters.setMinTransactionGasPrice(Wei.ZERO); poWSolver = @@ -311,12 +317,8 @@ public TransactionPool getTransactionPool() { return transactionPool; } - public Address getCoinbase() { - return coinbase; - } - - public Bytes getExtraData() { - return extraData; + public MiningParameters getMiningParameters() { + return miningParameters; } public MutableBlockchain getBlockchain() { diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java index 4b6b868383d..6c3fddae1c7 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java @@ -14,7 +14,6 @@ */ package org.hyperledger.besu.ethereum.retesteth.methods; -import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; @@ -24,7 +23,6 @@ import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockImporter; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.mainnet.BlockImportResult; import org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode; @@ -62,20 +60,11 @@ private boolean mineNewBlock() { final ProtocolContext protocolContext = context.getProtocolContext(); final MutableBlockchain blockchain = context.getBlockchain(); final HeaderValidationMode headerValidationMode = context.getHeaderValidationMode(); - final MiningParameters miningParameters = - ImmutableMiningParameters.builder() - .updatableInitValues( - ImmutableMiningParameters.UpdatableInitValues.builder() - .targetGasLimit(blockchain.getChainHeadHeader().getGasLimit()) - .minBlockOccupancyRatio(0.0) - .minTransactionGasPrice(Wei.ZERO) - .build()) - .build(); + final MiningParameters miningParameters = context.getMiningParameters(); final PoWBlockCreator blockCreator = new PoWBlockCreator( miningParameters, - context.getCoinbase(), - header -> context.getExtraData(), + header -> miningParameters.getExtraData(), context.getTransactionPool(), protocolContext, protocolSchedule, From 4626230467a960ed2f4a6b8a7085d4775c19674b Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 17 Oct 2023 17:48:09 +0200 Subject: [PATCH 16/24] Move MiningOptions to upper package Signed-off-by: Fabio Di Fabio --- .../org/hyperledger/besu/cli/BesuCommand.java | 2 +- .../options/{stable => }/MiningOptions.java | 3 +-- .../besu/cli/CommandTestAbstract.java | 2 +- .../{stable => }/MiningOptionsTest.java | 3 +-- .../merge/blockcreation/MergeCoordinator.java | 20 ++++++++++--------- plugin-api/build.gradle | 2 +- 6 files changed, 16 insertions(+), 16 deletions(-) rename besu/src/main/java/org/hyperledger/besu/cli/options/{stable => }/MiningOptions.java (99%) rename besu/src/test/java/org/hyperledger/besu/cli/options/{stable => }/MiningOptionsTest.java (99%) 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 916face134e..2e63b236342 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -53,10 +53,10 @@ import org.hyperledger.besu.cli.custom.RpcAuthFileValidator; import org.hyperledger.besu.cli.error.BesuExecutionExceptionHandler; import org.hyperledger.besu.cli.error.BesuParameterExceptionHandler; +import org.hyperledger.besu.cli.options.MiningOptions; import org.hyperledger.besu.cli.options.stable.DataStorageOptions; import org.hyperledger.besu.cli.options.stable.EthstatsOptions; import org.hyperledger.besu.cli.options.stable.LoggingLevelOption; -import org.hyperledger.besu.cli.options.stable.MiningOptions; import org.hyperledger.besu.cli.options.stable.NodePrivateKeyFileOption; import org.hyperledger.besu.cli.options.stable.P2PTLSConfigOptions; import org.hyperledger.besu.cli.options.stable.TransactionPoolOptions; diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java similarity index 99% rename from besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java rename to besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java index 29733ed0b89..aff3212d0b1 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java @@ -12,7 +12,7 @@ * * SPDX-License-Identifier: Apache-2.0 */ -package org.hyperledger.besu.cli.options.stable; +package org.hyperledger.besu.cli.options; import static java.util.Arrays.asList; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_MAX_OMMERS_DEPTH; @@ -25,7 +25,6 @@ import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE; -import org.hyperledger.besu.cli.options.CLIOptions; import org.hyperledger.besu.cli.util.CommandLineUtils; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; 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 84a45de2514..bccf28c4522 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java @@ -31,8 +31,8 @@ import org.hyperledger.besu.chainimport.JsonBlockImporter; import org.hyperledger.besu.chainimport.RlpBlockImporter; import org.hyperledger.besu.cli.config.EthNetworkConfig; +import org.hyperledger.besu.cli.options.MiningOptions; import org.hyperledger.besu.cli.options.stable.EthstatsOptions; -import org.hyperledger.besu.cli.options.stable.MiningOptions; import org.hyperledger.besu.cli.options.unstable.EthProtocolOptions; import org.hyperledger.besu.cli.options.unstable.MetricsCLIOptions; import org.hyperledger.besu.cli.options.unstable.NetworkingOptions; diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/MiningOptionsTest.java similarity index 99% rename from besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java rename to besu/src/test/java/org/hyperledger/besu/cli/options/MiningOptionsTest.java index 95a83e7ce87..5509df0fee5 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/MiningOptionsTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/MiningOptionsTest.java @@ -12,14 +12,13 @@ * * SPDX-License-Identifier: Apache-2.0 */ -package org.hyperledger.besu.cli.options.stable; +package org.hyperledger.besu.cli.options; import static org.assertj.core.api.Assertions.assertThat; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; import static org.mockito.Mockito.atMost; import static org.mockito.Mockito.verify; -import org.hyperledger.besu.cli.options.AbstractCLIOptionsTest; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java index b83e607ef4b..60a88649a04 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java @@ -129,15 +129,17 @@ public MergeCoordinator( this.miningParameters = miningParams; this.mergeBlockCreatorFactory = - (parentHeader, address) -> - new MergeBlockCreator( - miningParameters, - parent -> miningParameters.getExtraData(), - transactionPool, - protocolContext, - protocolSchedule, - parentHeader, - depositContractAddress); + (parentHeader, address) -> { + address.ifPresent(miningParams::setCoinbase); + return new MergeBlockCreator( + miningParameters, + parent -> miningParameters.getExtraData(), + transactionPool, + protocolContext, + protocolSchedule, + parentHeader, + depositContractAddress); + }; this.backwardSyncContext.subscribeBadChainListener(this); } diff --git a/plugin-api/build.gradle b/plugin-api/build.gradle index 66877c43c9d..f79852f2011 100644 --- a/plugin-api/build.gradle +++ b/plugin-api/build.gradle @@ -69,7 +69,7 @@ Calculated : ${currentHash} tasks.register('checkAPIChanges', FileStateChecker) { description = "Checks that the API for the Plugin-API project does not change without deliberate thought" files = sourceSets.main.allJava.files - knownHash = 'aRwRZCqqkThbFyseJ9VRqe9rCoLsnsaL5vgfSOHylpY=' + knownHash = 'j6NRklFHlG35Pq/t6t/oJBrT8DbYOyruGq3cJNh4ENw=' } check.dependsOn('checkAPIChanges') From 25b152264bb71bf5b6f6ed3a19187e53d8634afa Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 17 Oct 2023 18:48:20 +0200 Subject: [PATCH 17/24] Fix coinbase for *bft Signed-off-by: Fabio Di Fabio --- .../consensus/common/bft/blockcreation/BftBlockCreator.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java index 47bf915a142..4c5e773966f 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/blockcreation/BftBlockCreator.java @@ -62,7 +62,7 @@ public BftBlockCreator( final BlockHeader parentHeader, final BftExtraDataCodec bftExtraDataCodec) { super( - miningParameters, + miningParameters.setCoinbase(localAddress), miningBeneficiaryCalculator(localAddress, forksSchedule), extraDataCalculator, transactionPool, From b7f421346adcdfaa06510006fe127f123d1fe6eb Mon Sep 17 00:00:00 2001 From: Gabriel-Trintinalia Date: Wed, 18 Oct 2023 14:06:21 +1100 Subject: [PATCH 18/24] Implement methods to get and set min priority fee Signed-off-by: Gabriel-Trintinalia --- .../besu/ethereum/api/jsonrpc/RpcMethod.java | 2 + .../methods/miner/MinerGetMinPriorityFee.java | 41 +++++++++++ .../methods/miner/MinerSetMinPriorityFee.java | 53 +++++++++++++++ .../jsonrpc/methods/MinerJsonRpcMethods.java | 8 ++- .../miner/MinerGetMinPriorityFeeTest.java | 55 +++++++++++++++ .../miner/MinerSetMinPriorityFeeTest.java | 68 +++++++++++++++++++ 6 files changed, 226 insertions(+), 1 deletion(-) create mode 100644 ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFee.java create mode 100644 ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java create mode 100644 ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java create mode 100644 ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFeeTest.java diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/RpcMethod.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/RpcMethod.java index fe7e432081b..78e3f078f7d 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/RpcMethod.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/RpcMethod.java @@ -153,6 +153,8 @@ public enum RpcMethod { MINER_SET_ETHERBASE("miner_setEtherbase"), MINER_START("miner_start"), MINER_STOP("miner_stop"), + MINER_GET_MIN_PRIORITY_FEE("miner_getMinPriorityFee"), + MINER_SET_MIN_PRIORITY_FEE("miner_setMinPriorityFee"), NET_ENODE("net_enode"), NET_LISTENING("net_listening"), NET_PEER_COUNT("net_peerCount"), diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFee.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFee.java new file mode 100644 index 00000000000..f473fede16f --- /dev/null +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFee.java @@ -0,0 +1,41 @@ +/* + * Copyright Hyperledger Besu Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner; + +import org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; +import org.hyperledger.besu.ethereum.core.MiningParameters; + +public class MinerGetMinPriorityFee implements JsonRpcMethod { + private final MiningParameters miningParameters; + + public MinerGetMinPriorityFee(final MiningParameters miningParameters) { + this.miningParameters = miningParameters; + } + + @Override + public String getName() { + return RpcMethod.MINER_GET_MIN_PRIORITY_FEE.getMethodName(); + } + + @Override + public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { + return new JsonRpcSuccessResponse( + requestContext.getRequest().getId(), miningParameters.getMinPriorityFeePerGas().getValue()); + } +} diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java new file mode 100644 index 00000000000..fb0c3d69c0d --- /dev/null +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java @@ -0,0 +1,53 @@ +/* + * Copyright Hyperledger Besu Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner; + +import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; +import org.hyperledger.besu.ethereum.core.MiningParameters; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +public class MinerSetMinPriorityFee implements JsonRpcMethod { + private static final Logger LOG = LoggerFactory.getLogger(MinerSetMinPriorityFee.class); + + private final MiningParameters miningParameters; + + public MinerSetMinPriorityFee(final MiningParameters miningParameters) { + this.miningParameters = miningParameters; + } + + @Override + public String getName() { + return RpcMethod.MINER_SET_MIN_PRIORITY_FEE.getMethodName(); + } + + @Override + public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { + try { + final Wei minPriorityFee = Wei.of(requestContext.getRequiredParameter(0, Long.class)); + miningParameters.setMinPriorityFeePerGas(minPriorityFee); + LOG.debug("min priority fee changed to {}", minPriorityFee); + return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), true); + } catch (final IllegalArgumentException invalidJsonRpcParameters) { + return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), false); + } + } +} diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/MinerJsonRpcMethods.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/MinerJsonRpcMethods.java index c0888bcff84..1742fe1e552 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/MinerJsonRpcMethods.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/MinerJsonRpcMethods.java @@ -17,8 +17,10 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner.MinerChangeTargetGasLimit; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner.MinerGetMinPriorityFee; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner.MinerSetCoinbase; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner.MinerSetEtherbase; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner.MinerSetMinPriorityFee; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner.MinerStart; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner.MinerStop; import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; @@ -29,9 +31,11 @@ public class MinerJsonRpcMethods extends ApiGroupJsonRpcMethods { private final MiningCoordinator miningCoordinator; + private final MiningParameters miningParameters; public MinerJsonRpcMethods( final MiningParameters miningParameters, final MiningCoordinator miningCoordinator) { + this.miningParameters = miningParameters; this.miningCoordinator = miningCoordinator; } @@ -48,6 +52,8 @@ protected Map create() { new MinerStop(miningCoordinator), minerSetCoinbase, new MinerSetEtherbase(minerSetCoinbase), - new MinerChangeTargetGasLimit(miningCoordinator)); + new MinerChangeTargetGasLimit(miningCoordinator), + new MinerGetMinPriorityFee(miningParameters), + new MinerSetMinPriorityFee(miningParameters)); } } diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java new file mode 100644 index 00000000000..372bad4ae9b --- /dev/null +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java @@ -0,0 +1,55 @@ +/* + * Copyright Hyperledger Besu Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; +import org.hyperledger.besu.ethereum.core.MiningParameters; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class MinerGetMinPriorityFeeTest { + MiningParameters miningParameters = mock(MiningParameters.class); + private MinerGetMinPriorityFee method; + + @BeforeEach + public void setUp() { + method = new MinerGetMinPriorityFee(miningParameters); + } + + @Test + public void shouldReturnMinPriorityFee() { + Wei minPriorityFee = Wei.of(70); + final JsonRpcRequestContext request = + new JsonRpcRequestContext( + new JsonRpcRequest("2.0", method.getName(), new Object[] {})); + + when(miningParameters.getMinPriorityFeePerGas()).thenReturn(minPriorityFee); + + final JsonRpcResponse expected = + new JsonRpcSuccessResponse(request.getRequest().getId(), minPriorityFee); + + final JsonRpcResponse actual = method.response(request); + assertThat(actual).usingRecursiveComparison().isEqualTo(expected); + } +} diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFeeTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFeeTest.java new file mode 100644 index 00000000000..b145c24045d --- /dev/null +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFeeTest.java @@ -0,0 +1,68 @@ +/* + * Copyright Hyperledger Besu Contributors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with + * the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on + * an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the + * specific language governing permissions and limitations under the License. + * + * SPDX-License-Identifier: Apache-2.0 + */ +package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.miner; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; +import org.hyperledger.besu.ethereum.core.MiningParameters; + +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +public class MinerSetMinPriorityFeeTest { + MiningParameters miningParameters = MiningParameters.newDefault(); + private MinerSetMinPriorityFee method; + + @BeforeEach + public void setUp() { + method = new MinerSetMinPriorityFee(miningParameters); + } + + @Test + public void shouldReturnFalseWhenParameterIsInvalid() { + final long newMinPriorityFee = -1; + final var request = request(newMinPriorityFee); + + method.response(request); + final JsonRpcResponse expected = + new JsonRpcSuccessResponse(request.getRequest().getId(), false); + + final JsonRpcResponse actual = method.response(request); + assertThat(actual).usingRecursiveComparison().isEqualTo(expected); + } + + @Test + public void shouldChangeMinPriorityFee() { + final long newMinPriorityFee = 10; + final var request = request(newMinPriorityFee); + method.response(request); + final JsonRpcResponse expected = new JsonRpcSuccessResponse(request.getRequest().getId(), true); + + final JsonRpcResponse actual = method.response(request); + assertThat(actual).usingRecursiveComparison().isEqualTo(expected); + assertThat(miningParameters.getMinPriorityFeePerGas()).isEqualTo(Wei.of(newMinPriorityFee)); + } + + private JsonRpcRequestContext request(final long longParam) { + return new JsonRpcRequestContext( + new JsonRpcRequest( + "2.0", method.getName(), new Object[] {String.valueOf(longParam)})); + } +} From 31f21838f06c3bf67a7670f6a368c9d9e986eba3 Mon Sep 17 00:00:00 2001 From: Gabriel-Trintinalia Date: Thu, 19 Oct 2023 13:44:08 +1100 Subject: [PATCH 19/24] Fix spotless Signed-off-by: Gabriel-Trintinalia --- .../internal/methods/miner/MinerGetMinPriorityFeeTest.java | 3 +-- .../internal/methods/miner/MinerSetMinPriorityFeeTest.java | 3 +-- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java index 372bad4ae9b..1805bea4a46 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java @@ -41,8 +41,7 @@ public void setUp() { public void shouldReturnMinPriorityFee() { Wei minPriorityFee = Wei.of(70); final JsonRpcRequestContext request = - new JsonRpcRequestContext( - new JsonRpcRequest("2.0", method.getName(), new Object[] {})); + new JsonRpcRequestContext(new JsonRpcRequest("2.0", method.getName(), new Object[] {})); when(miningParameters.getMinPriorityFeePerGas()).thenReturn(minPriorityFee); diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFeeTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFeeTest.java index b145c24045d..e90e171c15a 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFeeTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFeeTest.java @@ -62,7 +62,6 @@ public void shouldChangeMinPriorityFee() { private JsonRpcRequestContext request(final long longParam) { return new JsonRpcRequestContext( - new JsonRpcRequest( - "2.0", method.getName(), new Object[] {String.valueOf(longParam)})); + new JsonRpcRequest("2.0", method.getName(), new Object[] {String.valueOf(longParam)})); } } From e55392ba00ead2d358db6351c799edd0e0c0c883 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Mon, 23 Oct 2023 14:15:44 +0200 Subject: [PATCH 20/24] Apply suggestions from code review Signed-off-by: Fabio Di Fabio --- .../BesuNodeConfigurationBuilder.java | 6 +-- .../node/configuration/BesuNodeFactory.java | 6 +-- .../bft/BftMiningAcceptanceTest.java | 6 +-- .../org/hyperledger/besu/cli/BesuCommand.java | 1 - .../besu/cli/options/MiningOptions.java | 12 ++--- .../subcommands/blocks/BlocksSubCommand.java | 6 +-- .../controller/IbftBesuControllerBuilder.java | 1 - .../chainimport/JsonBlockImporterTest.java | 6 +-- .../hyperledger/besu/cli/BesuCommandTest.java | 10 ++-- .../besu/cli/options/MiningOptionsTest.java | 6 +-- .../TransitionControllerBuilderTest.java | 4 +- .../besu/services/BesuEventsImplTest.java | 6 +-- .../blockcreation/CliqueBlockCreatorTest.java | 5 +- .../CliqueMinerExecutorTest.java | 6 +-- .../ibft/support/TestContextBuilder.java | 6 +-- .../blockcreation/BftBlockCreatorTest.java | 6 +-- .../merge/blockcreation/MergeCoordinator.java | 6 ++- .../blockcreation/MergeCoordinatorTest.java | 6 +-- .../merge/blockcreation/MergeReorgTest.java | 4 +- .../qbft/support/TestContextBuilder.java | 5 +- .../QbftBlockCreatorFactoryTest.java | 5 +- .../AbstractBlockCreatorTest.java | 5 +- .../AbstractBlockTransactionSelectorTest.java | 6 +-- .../blockcreation/PoWBlockCreatorTest.java | 5 +- .../besu/ethereum/core/MiningParameters.java | 52 +++++++++---------- .../bonsai/AbstractIsolationTests.java | 6 +-- .../besu/ethereum/mainnet/PoWSolverTest.java | 4 +- .../ethereum/retesteth/RetestethContext.java | 6 +-- 28 files changed, 102 insertions(+), 101 deletions(-) diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java index 6e925f6a2c7..fea87c35088 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeConfigurationBuilder.java @@ -30,7 +30,7 @@ import org.hyperledger.besu.ethereum.api.tls.FileBasedPasswordProvider; import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.p2p.config.NetworkingConfiguration; @@ -58,8 +58,8 @@ public class BesuNodeConfigurationBuilder { private Optional dataPath = Optional.empty(); private MiningParameters miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder().coinbase(AddressHelpers.ofValue(1)).build()) + .mutableInitValues( + MutableInitValues.builder().coinbase(AddressHelpers.ofValue(1)).build()) .build(); private JsonRpcConfiguration jsonRpcConfiguration = JsonRpcConfiguration.createDefault(); diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java index 7960fd46437..9e35d09f2fc 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java @@ -27,7 +27,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.InMemoryPrivacyStorageProvider; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; @@ -306,8 +306,8 @@ public BesuNode createNodeWithMultiTenantedPrivacy( final MiningParameters miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .isMiningEnabled(true) .minTransactionGasPrice(Wei.ZERO) .coinbase(AddressHelpers.ofValue(1)) diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java index 8093661ebeb..a109a3b8567 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftMiningAcceptanceTest.java @@ -18,7 +18,7 @@ import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.tests.acceptance.dsl.account.Account; import org.hyperledger.besu.tests.acceptance.dsl.blockchain.Amount; @@ -62,8 +62,8 @@ public void shouldMineOnSingleNodeWithFreeGas_Berlin() throws Exception { final BesuNode minerNode = nodeFactory.createNode(besu, "miner1"); final MiningParameters zeroGasMiningParams = ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .isMiningEnabled(true) .minTransactionGasPrice(Wei.ZERO) .coinbase(AddressHelpers.ofValue(1)) 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 26c1fa39c10..c360a490ea3 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -1429,7 +1429,6 @@ public void run() { // Need to create vertx after cmdline has been parsed, such that metricsSystem is configurable vertx = createVertx(createVertxOptions(metricsSystem.get())); - miningParameters = getMiningParameters(); validateOptions(); configure(); diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java index aff3212d0b1..af4e423b416 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java @@ -15,21 +15,21 @@ package org.hyperledger.besu.cli.options; import static java.util.Arrays.asList; +import static org.hyperledger.besu.ethereum.core.MiningParameters.MutableInitValues.DEFAULT_EXTRA_DATA; +import static org.hyperledger.besu.ethereum.core.MiningParameters.MutableInitValues.DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; +import static org.hyperledger.besu.ethereum.core.MiningParameters.MutableInitValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_MAX_OMMERS_DEPTH; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POS_BLOCK_CREATION_MAX_TIME; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POS_BLOCK_CREATION_REPETITION_MIN_DURATION; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_POW_JOB_TTL; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_REMOTE_SEALERS_LIMIT; import static org.hyperledger.besu.ethereum.core.MiningParameters.Unstable.DEFAULT_REMOTE_SEALERS_TTL; -import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_EXTRA_DATA; -import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO; -import static org.hyperledger.besu.ethereum.core.MiningParameters.UpdatableInitValues.DEFAULT_MIN_TRANSACTION_GAS_PRICE; import org.hyperledger.besu.cli.util.CommandLineUtils; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import java.util.List; @@ -262,7 +262,7 @@ static MiningOptions fromConfig(final MiningParameters miningParameters) { @Override public MiningParameters toDomainObject() { final var updatableInitValuesBuilder = - UpdatableInitValues.builder() + MutableInitValues.builder() .isMiningEnabled(isMiningEnabled) .extraData(extraData) .minTransactionGasPrice(minTransactionGasPrice) @@ -277,7 +277,7 @@ public MiningParameters toDomainObject() { final var miningParametersBuilder = ImmutableMiningParameters.builder() - .updatableInitValues(updatableInitValuesBuilder.build()) + .mutableInitValues(updatableInitValuesBuilder.build()) .isStratumMiningEnabled(iStratumMiningEnabled) .stratumNetworkInterface(stratumNetworkInterface) .stratumPort(stratumPort) diff --git a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java index 3242ce9799a..ea8bfab8d14 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java @@ -32,7 +32,7 @@ import org.hyperledger.besu.ethereum.blockcreation.IncrementingNonceGenerator; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.metrics.MetricsService; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; @@ -270,8 +270,8 @@ private MiningParameters getMiningParameters() { final Address coinbase = Address.ZERO; final Bytes extraData = Bytes.EMPTY; return ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .nonceGenerator(new IncrementingNonceGenerator(0)) .extraData(extraData) .minTransactionGasPrice(minTransactionGasPrice) 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 1f9fd70f745..40765769e6e 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java @@ -145,7 +145,6 @@ protected MiningCoordinator createMiningCoordinator( final Address localAddress = Util.publicKeyToAddress(nodeKey.getPublicKey()); final BftProtocolSchedule bftProtocolSchedule = (BftProtocolSchedule) protocolSchedule; - miningParameters.setCoinbase(localAddress); final BftBlockCreatorFactory blockCreatorFactory = new BftBlockCreatorFactory<>( transactionPool, 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 de338b78549..00ebc610823 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java @@ -30,7 +30,7 @@ import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.Transaction; @@ -423,8 +423,8 @@ protected BesuController createController(final GenesisConfigFile genesisConfigF .networkId(BigInteger.valueOf(10)) .miningParameters( ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .isMiningEnabled(true) .minTransactionGasPrice(Wei.ZERO) .build()) 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 8f2124ddfa9..91a203ff576 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -71,7 +71,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration; import org.hyperledger.besu.ethereum.api.tls.TlsConfiguration; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; @@ -903,8 +903,8 @@ public void envVariableOverridesValueFromConfigFile() { verify(mockControllerBuilder) .miningParameters( ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .coinbase(Address.fromHexString(expectedCoinbase)) .build()) .build()); @@ -920,8 +920,8 @@ public void cliOptionOverridesEnvVariableAndConfig() { verify(mockControllerBuilder) .miningParameters( ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .coinbase(Address.fromHexString(expectedCoinbase)) .build()) .build()); 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 5509df0fee5..7d6d3cfe06e 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 @@ -23,8 +23,8 @@ import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.Unstable; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import java.io.IOException; @@ -316,8 +316,8 @@ protected MiningParameters createDefaultDomainObject() { @Override protected MiningParameters createCustomizedDomainObject() { return ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .isMiningEnabled(true) .extraData(Bytes.fromHexString("0xabc321")) .minBlockOccupancyRatio(0.5) diff --git a/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java index 6d07e414874..0b1a98a210f 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/TransitionControllerBuilderTest.java @@ -35,7 +35,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; @@ -122,7 +122,7 @@ public void assertPoWIsNotMiningPreMerge() { public void assertPowMiningPreMerge() { miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues(UpdatableInitValues.builder().isMiningEnabled(true).build()) + .mutableInitValues(MutableInitValues.builder().isMiningEnabled(true).build()) .build(); var transCoordinator = buildTransitionCoordinator(powBuilder, postMergeBuilder); assertThat(transCoordinator.isMiningBeforeMerge()).isTrue(); diff --git a/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java b/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java index 7fcff4ced88..921d4e7fbe6 100644 --- a/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java +++ b/besu/src/test/java/org/hyperledger/besu/services/BesuEventsImplTest.java @@ -34,7 +34,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.TransactionReceipt; import org.hyperledger.besu.ethereum.core.TransactionTestFixture; @@ -157,8 +157,8 @@ public void setUp() { new NoOpMetricsSystem(), syncState, ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder().minTransactionGasPrice(Wei.ZERO).build()) + .mutableInitValues( + MutableInitValues.builder().minTransactionGasPrice(Wei.ZERO).build()) .build(), txPoolConfig, null); diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java index 208d5ac64b5..3ddfdb1149d 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockCreatorTest.java @@ -48,6 +48,7 @@ import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -244,8 +245,8 @@ private static MiningParameters createMiningParameters( final Bytes extraData, final Address coinbase) { final MiningParameters miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues( - ImmutableMiningParameters.UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .extraData(extraData) .targetGasLimit(10_000_000L) .minTransactionGasPrice(Wei.ZERO) diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java index a538a491b67..7a089f2ef37 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueMinerExecutorTest.java @@ -38,7 +38,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -236,8 +236,8 @@ private Bytes generateRandomVanityData() { private static MiningParameters createMiningParameters(final Bytes vanityData) { return ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .extraData(vanityData) .minTransactionGasPrice(Wei.ZERO) .coinbase(AddressHelpers.ofValue(1)) diff --git a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java index 41fbbbe1940..9b0d9f65ad9 100644 --- a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java +++ b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/support/TestContextBuilder.java @@ -78,7 +78,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -307,8 +307,8 @@ private static ControllerAndState createControllerAndFinalState( final MiningParameters miningParams = ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .isMiningEnabled(true) .minTransactionGasPrice(Wei.ZERO) .extraData(Bytes.wrap("Ibft Int tests".getBytes(UTF_8))) diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java index afd967a2caf..6065c269be7 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/blockcreation/BftBlockCreatorTest.java @@ -42,7 +42,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -154,8 +154,8 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( final MiningParameters miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .extraData( bftExtraDataEncoder.encode( new BftExtraData( diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java index e7e98ee89e8..9a5d26f1c63 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinator.java @@ -75,6 +75,8 @@ public class MergeCoordinator implements MergeMiningCoordinator, BadChainListene * to fill 100% of the block. */ private static final double TRY_FILL_BLOCK = 1.0; + + private static final long DEFAULT_TARGET_GAS_LIMIT = 30000000L; /** The Mining parameters. */ protected final MiningParameters miningParameters; /** The Merge block creator factory. */ @@ -122,7 +124,7 @@ public MergeCoordinator( miningParams.setCoinbase(Address.ZERO); } if (miningParams.getTargetGasLimit().isEmpty()) { - miningParams.setTargetGasLimit(30000000L); + miningParams.setTargetGasLimit(DEFAULT_TARGET_GAS_LIMIT); } miningParams.setMinBlockOccupancyRatio(TRY_FILL_BLOCK); @@ -168,7 +170,7 @@ public MergeCoordinator( this.mergeContext = protocolContext.getConsensusContext(MergeContext.class); this.backwardSyncContext = backwardSyncContext; if (miningParams.getTargetGasLimit().isEmpty()) { - miningParams.setTargetGasLimit(30000000L); + miningParams.setTargetGasLimit(DEFAULT_TARGET_GAS_LIMIT); } miningParams.setMinBlockOccupancyRatio(TRY_FILL_BLOCK); this.miningParameters = miningParams; diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java index 3eeb87539bd..7c54b9260f9 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeCoordinatorTest.java @@ -57,8 +57,8 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.Unstable; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.TransactionTestFixture; import org.hyperledger.besu.ethereum.eth.manager.EthContext; @@ -135,7 +135,7 @@ public class MergeCoordinatorTest implements MergeGenesisConfigHelper { MiningParameters miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues(UpdatableInitValues.builder().coinbase(coinbase).build()) + .mutableInitValues(MutableInitValues.builder().coinbase(coinbase).build()) .unstable( Unstable.builder() .posBlockCreationRepetitionMinDuration(REPETITION_MIN_DURATION) @@ -744,7 +744,7 @@ public void shouldUseExtraDataFromMiningParameters() { miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues(UpdatableInitValues.builder().extraData(extraData).build()) + .mutableInitValues(MutableInitValues.builder().extraData(extraData).build()) .build(); this.coordinator = diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java index 75de7e190d3..cd96d9cbdbb 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java @@ -34,7 +34,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.eth.sync.backwardsync.BackwardSyncContext; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.BlockHeaderValidator; @@ -95,7 +95,7 @@ public void setUp() { CompletableFuture::runAsync, mockTransactionPool, ImmutableMiningParameters.builder() - .updatableInitValues(UpdatableInitValues.builder().coinbase(coinbase).build()) + .mutableInitValues(MutableInitValues.builder().coinbase(coinbase).build()) .build(), mock(BackwardSyncContext.class), Optional.empty()); 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 c1a05a9709e..2b0386d9066 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 @@ -91,6 +91,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.core.Util; @@ -367,8 +368,8 @@ private static ControllerAndState createControllerAndFinalState( final MiningParameters miningParams = ImmutableMiningParameters.builder() - .updatableInitValues( - ImmutableMiningParameters.UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .isMiningEnabled(true) .minTransactionGasPrice(Wei.ZERO) .extraData(Bytes.wrap("Qbft Int tests".getBytes(UTF_8))) diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java index a4accedd1b0..d7b63bc215c 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/blockcreation/QbftBlockCreatorFactoryTest.java @@ -31,6 +31,7 @@ import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; @@ -50,8 +51,8 @@ public class QbftBlockCreatorFactoryTest { public void setUp() { final MiningParameters miningParams = ImmutableMiningParameters.builder() - .updatableInitValues( - ImmutableMiningParameters.UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .extraData(Bytes.wrap("Qbft tests".getBytes(UTF_8))) .build()) .build(); diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java index 3ed629cb935..413f9bb9ce6 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/AbstractBlockCreatorTest.java @@ -50,6 +50,7 @@ import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; @@ -387,8 +388,8 @@ private AbstractBlockCreator createBlockCreator( final MiningParameters miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues( - ImmutableMiningParameters.UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .extraData(Bytes.fromHexString("deadbeef")) .minTransactionGasPrice(Wei.ONE) .minBlockOccupancyRatio(0d) 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 ef8314bec69..1ddcd264ea0 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 @@ -47,6 +47,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; @@ -151,10 +152,7 @@ public void setup() { when(ethContext.getEthPeers().subscribeConnect(any())).thenReturn(1L); miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues( - ImmutableMiningParameters.UpdatableInitValues.builder() - .minTransactionGasPrice(Wei.ONE) - .build()) + .mutableInitValues(MutableInitValues.builder().minTransactionGasPrice(Wei.ONE).build()) .build(); transactionPool = createTransactionPool(); diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java index cddb0073f8d..80c0a3d4426 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/PoWBlockCreatorTest.java @@ -32,6 +32,7 @@ import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ExecutionContextTestFixture; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.PrivacyParameters; @@ -338,8 +339,8 @@ private TransactionPool createTransactionPool( private MiningParameters createMiningParameters() { return ImmutableMiningParameters.builder() - .updatableInitValues( - ImmutableMiningParameters.UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .nonceGenerator(Lists.newArrayList(BLOCK_1_NONCE)) .extraData(BLOCK_1_EXTRA_DATA) .minTransactionGasPrice(Wei.ONE) diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java index ea14d863839..014c0c2ae8a 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/MiningParameters.java @@ -30,10 +30,8 @@ public abstract class MiningParameters { public static final MiningParameters MINING_DISABLED = ImmutableMiningParameters.builder() - .updatableInitValues( - ImmutableMiningParameters.UpdatableInitValues.builder() - .isMiningEnabled(false) - .build()) + .mutableInitValues( + ImmutableMiningParameters.MutableInitValues.builder().isMiningEnabled(false).build()) .build(); public static final MiningParameters newDefault() { @@ -41,65 +39,65 @@ public static final MiningParameters newDefault() { } public boolean isMiningEnabled() { - return getUpdatableRuntimeValues().miningEnabled; + return getMutableRuntimeValues().miningEnabled; } public MiningParameters setMiningEnabled(final boolean miningEnabled) { - getUpdatableRuntimeValues().miningEnabled = miningEnabled; + getMutableRuntimeValues().miningEnabled = miningEnabled; return this; } public Bytes getExtraData() { - return getUpdatableRuntimeValues().extraData; + return getMutableRuntimeValues().extraData; } public MiningParameters setExtraData(final Bytes extraData) { - getUpdatableRuntimeValues().extraData = extraData; + getMutableRuntimeValues().extraData = extraData; return this; } public Wei getMinTransactionGasPrice() { - return getUpdatableRuntimeValues().minTransactionGasPrice; + return getMutableRuntimeValues().minTransactionGasPrice; } public MiningParameters setMinTransactionGasPrice(final Wei minTransactionGasPrice) { - getUpdatableRuntimeValues().minTransactionGasPrice = minTransactionGasPrice; + getMutableRuntimeValues().minTransactionGasPrice = minTransactionGasPrice; return this; } public Optional
getCoinbase() { - return getUpdatableRuntimeValues().coinbase; + return getMutableRuntimeValues().coinbase; } public MiningParameters setCoinbase(final Address coinbase) { - getUpdatableRuntimeValues().coinbase = Optional.of(coinbase); + getMutableRuntimeValues().coinbase = Optional.of(coinbase); return this; } public OptionalLong getTargetGasLimit() { - return getUpdatableRuntimeValues().targetGasLimit; + return getMutableRuntimeValues().targetGasLimit; } public MiningParameters setTargetGasLimit(final long targetGasLimit) { - getUpdatableRuntimeValues().targetGasLimit = OptionalLong.of(targetGasLimit); + getMutableRuntimeValues().targetGasLimit = OptionalLong.of(targetGasLimit); return this; } public double getMinBlockOccupancyRatio() { - return getUpdatableRuntimeValues().minBlockOccupancyRatio; + return getMutableRuntimeValues().minBlockOccupancyRatio; } public MiningParameters setMinBlockOccupancyRatio(final double minBlockOccupancyRatio) { - getUpdatableRuntimeValues().minBlockOccupancyRatio = minBlockOccupancyRatio; + getMutableRuntimeValues().minBlockOccupancyRatio = minBlockOccupancyRatio; return this; } public Optional> getNonceGenerator() { - return getUpdatableRuntimeValues().nonceGenerator; + return getMutableRuntimeValues().nonceGenerator; } public MiningParameters setNonceGenerator(final Iterable nonceGenerator) { - getUpdatableRuntimeValues().nonceGenerator = Optional.of(nonceGenerator); + getMutableRuntimeValues().nonceGenerator = Optional.of(nonceGenerator); return this; } @@ -119,8 +117,8 @@ public int getStratumPort() { } @Value.Default - protected UpdatableRuntimeValues getUpdatableRuntimeValues() { - return new UpdatableRuntimeValues(getUpdatableInitValues()); + protected MutableRuntimeValues getMutableRuntimeValues() { + return new MutableRuntimeValues(getMutableInitValues()); } @Value.Default @@ -129,17 +127,17 @@ public Unstable getUnstable() { } @Value.Default - public UpdatableInitValues getUpdatableInitValues() { - return UpdatableInitValues.DEFAULT; + public MutableInitValues getMutableInitValues() { + return MutableInitValues.DEFAULT; } @Value.Immutable - public interface UpdatableInitValues { + public interface MutableInitValues { Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY; Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; - UpdatableInitValues DEFAULT = ImmutableMiningParameters.UpdatableInitValues.builder().build(); + MutableInitValues DEFAULT = ImmutableMiningParameters.MutableInitValues.builder().build(); @Value.Default default boolean isMiningEnabled() { @@ -168,7 +166,7 @@ default double getMinBlockOccupancyRatio() { Optional> nonceGenerator(); } - static class UpdatableRuntimeValues { + static class MutableRuntimeValues { private volatile boolean miningEnabled; private volatile Bytes extraData; private volatile Wei minTransactionGasPrice; @@ -177,7 +175,7 @@ static class UpdatableRuntimeValues { private volatile OptionalLong targetGasLimit; private volatile Optional> nonceGenerator; - private UpdatableRuntimeValues(final UpdatableInitValues initValues) { + private MutableRuntimeValues(final MutableInitValues initValues) { miningEnabled = initValues.isMiningEnabled(); extraData = initValues.getExtraData(); minTransactionGasPrice = initValues.getMinTransactionGasPrice(); @@ -191,7 +189,7 @@ private UpdatableRuntimeValues(final UpdatableInitValues initValues) { public boolean equals(final Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; - final UpdatableRuntimeValues that = (UpdatableRuntimeValues) o; + final MutableRuntimeValues that = (MutableRuntimeValues) o; return miningEnabled == that.miningEnabled && Double.compare(minBlockOccupancyRatio, that.minBlockOccupancyRatio) == 0 && Objects.equals(extraData, that.extraData) diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java index 0d30843cb38..a6441f970fb 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/bonsai/AbstractIsolationTests.java @@ -42,7 +42,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.SealableBlockHeader; @@ -232,8 +232,8 @@ static TestBlockCreator forHeader( final MiningParameters miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .extraData(Bytes.fromHexString("deadbeef")) .targetGasLimit(30_000_000L) .minTransactionGasPrice(Wei.ONE) diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/PoWSolverTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/PoWSolverTest.java index 6137936d22b..91553afed33 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/PoWSolverTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/PoWSolverTest.java @@ -22,7 +22,7 @@ import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.util.Subscribers; @@ -533,7 +533,7 @@ public void rejectsSolutionsForOldBlocks() private MiningParameters createMiningParameters( final List nonceToTry, final int powJobTimeToLive, final int maxOmmerDepth) { return ImmutableMiningParameters.builder() - .updatableInitValues(UpdatableInitValues.builder().nonceGenerator(nonceToTry).build()) + .mutableInitValues(MutableInitValues.builder().nonceGenerator(nonceToTry).build()) .unstable( ImmutableMiningParameters.Unstable.builder() .maxOmmerDepth(maxOmmerDepth) diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java index 2327bfaae07..bed7652c6d7 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/RetestethContext.java @@ -32,8 +32,8 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; +import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.Unstable; -import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.UpdatableInitValues; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; @@ -184,8 +184,8 @@ private boolean buildContext( miningParameters = ImmutableMiningParameters.builder() - .updatableInitValues( - UpdatableInitValues.builder() + .mutableInitValues( + MutableInitValues.builder() .coinbase(coinbase) .extraData(extraData) .targetGasLimit(blockchain.getChainHeadHeader().getGasLimit()) From 639af829d54312e900befcb17dd79460c7d7898f Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 24 Oct 2023 10:31:04 +0200 Subject: [PATCH 21/24] Update besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java [skip-ci] Co-authored-by: Sally MacFarlane Signed-off-by: Fabio Di Fabio --- besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 c360a490ea3..6d6bed2bfcf 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -306,7 +306,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable { final org.hyperledger.besu.cli.options.stable.TransactionPoolOptions stableTransactionPoolOptions = TransactionPoolOptions.create(); - @CommandLine.ArgGroup(validate = false, heading = "@|bold Miner Options|@%n") + @CommandLine.ArgGroup(validate = false, heading = "@|bold Block Builder Options|@%n") final MiningOptions miningOptions = MiningOptions.create(); private final RunnerBuilder runnerBuilder; From e2bf4e43195f5fe902883ccbb2aad4a562f95fd4 Mon Sep 17 00:00:00 2001 From: Gabriel-Trintinalia Date: Wed, 25 Oct 2023 10:29:08 +1100 Subject: [PATCH 22/24] Add new config option to everything config Signed-off-by: Gabriel-Trintinalia --- besu/src/test/resources/everything_config.toml | 1 + 1 file changed, 1 insertion(+) diff --git a/besu/src/test/resources/everything_config.toml b/besu/src/test/resources/everything_config.toml index f4c1d517d91..2bbf25a97d4 100644 --- a/besu/src/test/resources/everything_config.toml +++ b/besu/src/test/resources/everything_config.toml @@ -137,6 +137,7 @@ miner-stratum-enabled=false miner-coinbase="0x0000000000000000000000000000000000000002" miner-extra-data="0x444F4E27542050414E4943202120484F444C2C20484F444C2C20484F444C2021" min-gas-price=1 +min-priority-fee=0 min-block-occupancy-ratio=0.7 miner-stratum-host="0.0.0.0" miner-stratum-port=8008 From 65b84e57f32af0b8df97da90f705aab123e8cbea Mon Sep 17 00:00:00 2001 From: Gabriel-Trintinalia Date: Wed, 25 Oct 2023 12:48:33 +1100 Subject: [PATCH 23/24] Fix unit test Signed-off-by: Gabriel-Trintinalia --- .../internal/methods/miner/MinerGetMinPriorityFeeTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java index 1805bea4a46..2f0bc33e313 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerGetMinPriorityFeeTest.java @@ -46,7 +46,7 @@ public void shouldReturnMinPriorityFee() { when(miningParameters.getMinPriorityFeePerGas()).thenReturn(minPriorityFee); final JsonRpcResponse expected = - new JsonRpcSuccessResponse(request.getRequest().getId(), minPriorityFee); + new JsonRpcSuccessResponse(request.getRequest().getId(), minPriorityFee.getValue()); final JsonRpcResponse actual = method.response(request); assertThat(actual).usingRecursiveComparison().isEqualTo(expected); From f0a4c974f6582ee09eea58bb491fba54e7af5f4e Mon Sep 17 00:00:00 2001 From: Gabriel-Trintinalia Date: Wed, 25 Oct 2023 14:15:17 +1100 Subject: [PATCH 24/24] Accept PR suggestions Signed-off-by: Gabriel-Trintinalia --- .../org/hyperledger/besu/cli/options/MiningOptions.java | 4 ++-- .../internal/methods/miner/MinerSetMinPriorityFee.java | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java index 55b73d15172..8890f295515 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/MiningOptions.java @@ -97,7 +97,7 @@ public class MiningOptions implements CLIOptions { @Option( names = {"--min-priority-fee"}, description = - "Minimum priority fee per gas (in Wei) offered by a transaction for it to be included in a mined " + "Minimum priority fee per gas (in Wei) offered by a transaction for it to be included in a " + "block (default: ${DEFAULT-VALUE})", arity = "1") private Wei minPriorityFeePerGas = DEFAULT_MIN_PRIORITY_FEE_PER_GAS; @@ -106,7 +106,7 @@ public class MiningOptions implements CLIOptions { names = {"--target-gas-limit"}, description = "Sets target gas limit per block." - + " If set, each block's gas limit will approach this setting over time if the current gas limit is different.") + + " If set, each block's gas limit will approach this setting over time.") private Long targetGasLimit = null; @CommandLine.ArgGroup(validate = false) diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java index fb0c3d69c0d..ddc19cfe1de 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java @@ -42,9 +42,9 @@ public String getName() { @Override public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { try { - final Wei minPriorityFee = Wei.of(requestContext.getRequiredParameter(0, Long.class)); - miningParameters.setMinPriorityFeePerGas(minPriorityFee); - LOG.debug("min priority fee changed to {}", minPriorityFee); + final Wei minPriorityFeePerGas = Wei.of(requestContext.getRequiredParameter(0, Long.class)); + miningParameters.setMinPriorityFeePerGas(minPriorityFeePerGas); + LOG.debug("min priority fee per gas changed to {}", minPriorityFeePerGas); return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), true); } catch (final IllegalArgumentException invalidJsonRpcParameters) { return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), false);