From 6c2fea2162231c764088a5690c8bb22cb622a88d Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Thu, 17 Oct 2024 17:42:34 +0200 Subject: [PATCH 1/7] WIP Signed-off-by: Fabio Di Fabio --- .../dsl/node/ThreadBesuNodeRunner.java | 7 +- .../org/hyperledger/besu/RunnerBuilder.java | 25 ++-- .../org/hyperledger/besu/cli/BesuCommand.java | 1 + .../controller/BesuControllerBuilder.java | 9 +- .../CliqueBesuControllerBuilder.java | 26 ++-- ...onsensusScheduleBesuControllerBuilder.java | 10 +- .../controller/IbftBesuControllerBuilder.java | 10 +- .../MainnetBesuControllerBuilder.java | 5 +- .../MergeBesuControllerBuilder.java | 6 +- .../controller/QbftBesuControllerBuilder.java | 31 +++-- .../TransitionBesuControllerBuilder.java | 10 +- .../TransactionSimulationServiceImpl.java | 36 ++++-- ...nsusScheduleBesuControllerBuilderTest.java | 10 +- .../MergeBesuControllerBuilderTest.java | 33 +++-- .../clique/CliqueDifficultyCalculator.java | 15 ++- .../clique/CliqueProtocolSchedule.java | 52 ++------ .../CliqueDifficultyValidationRule.java | 8 +- .../CliqueDifficultyCalculatorTest.java | 22 ++-- .../clique/CliqueProtocolScheduleTest.java | 21 +++- .../clique/NodeCanProduceNextBlockTest.java | 21 ++-- .../blockcreation/CliqueBlockCreatorTest.java | 23 ++-- .../blockcreation/CliqueBlockMinerTest.java | 4 +- .../CliqueMinerExecutorTest.java | 8 +- .../CliqueDifficultyValidationRuleTest.java | 3 +- .../CliqueExtraDataValidationRuleTest.java | 3 +- .../common/MigratingProtocolContext.java | 29 +++-- .../bft/BaseBftProtocolScheduleBuilder.java | 2 +- .../common/MigratingProtocolContextTest.java | 8 +- .../BftCoinbaseValidationRuleTest.java | 16 ++- .../BftCommitSealsValidationRuleTest.java | 10 +- .../BftValidatorsValidationRuleTest.java | 15 ++- .../BftVanityDataValidationRuleTest.java | 5 +- .../ibft/support/TestContextBuilder.java | 5 +- .../tests/round/IbftRoundIntegrationTest.java | 5 +- ...ockHeaderValidationRulesetFactoryTest.java | 5 +- .../ibft/IbftProtocolScheduleTest.java | 6 +- .../blockcreation/BftBlockCreatorTest.java | 6 +- .../IbftBlockHeightManagerTest.java | 8 +- .../ibft/statemachine/IbftRoundTest.java | 5 +- .../ibft/validation/MessageValidatorTest.java | 5 +- .../merge/MergeProtocolSchedule.java | 2 +- .../merge/MergeProtocolScheduleTest.java | 3 +- .../blockcreation/MergeCoordinatorTest.java | 7 +- .../merge/blockcreation/MergeReorgTest.java | 7 +- .../qbft/support/TestContextBuilder.java | 7 +- .../test/round/QbftRoundIntegrationTest.java | 8 +- ...ockHeaderValidationRulesetFactoryTest.java | 7 +- .../qbft/QbftProtocolScheduleTest.java | 7 +- .../QbftValidatorsValidationRuleTest.java | 24 ++-- .../QbftBlockHeightManagerTest.java | 8 +- .../qbft/statemachine/QbftRoundTest.java | 8 +- .../ProposalPayloadValidatorTest.java | 7 +- .../validation/ProposalValidatorTest.java | 7 +- .../RoundChangeMessageValidatorTest.java | 7 +- .../jsonrpc/JsonRpcTestMethodsFactory.java | 32 +++-- ...ckByNumberLatestDesyncIntegrationTest.java | 3 +- .../api/graphql/GraphQLContextType.java | 5 +- .../pojoadapter/BlockAdapterBase.java | 3 +- .../pojoadapter/PendingStateAdapter.java | 3 +- .../internal/methods/AbstractEstimateGas.java | 91 ++++++++++---- .../internal/methods/EthCreateAccessList.java | 70 ++++------- .../internal/methods/EthEstimateGas.java | 38 ++---- .../internal/methods/TraceCallMany.java | 15 ++- .../jsonrpc/methods/DebugJsonRpcMethods.java | 16 +-- .../jsonrpc/methods/EthJsonRpcMethods.java | 29 ++--- .../methods/JsonRpcMethodsFactory.java | 15 ++- .../jsonrpc/methods/TraceJsonRpcMethods.java | 33 ++--- .../AbstractEthGraphQLHttpServiceTest.java | 8 +- .../AbstractJsonRpcHttpServiceTest.java | 4 +- .../JsonRpcHttpServiceHostAllowlistTest.java | 4 +- .../jsonrpc/JsonRpcHttpServiceLoginTest.java | 4 +- .../JsonRpcHttpServiceRpcApisTest.java | 7 +- .../jsonrpc/JsonRpcHttpServiceTestBase.java | 4 +- .../JsonRpcHttpServiceTlsClientAuthTest.java | 4 +- ...RpcHttpServiceTlsMisconfigurationTest.java | 4 +- .../jsonrpc/JsonRpcHttpServiceTlsTest.java | 4 +- .../websocket/WebSocketServiceLoginTest.java | 4 +- .../blockcreation/AbstractBlockCreator.java | 68 ++-------- .../blockcreation/BlockMinerTest.java | 6 +- .../ethereum/ConsensusContextFactory.java | 12 +- .../besu/ethereum/ProtocolContext.java | 28 ++--- .../ethereum/core/BlockHeaderBuilder.java | 53 ++++++++ .../fixed/FixedDifficultyCalculators.java | 2 +- .../mainnet/ClassicDifficultyCalculators.java | 8 +- .../mainnet/DifficultyCalculator.java | 4 +- .../mainnet/MainnetDifficultyCalculators.java | 25 ++-- .../CalculatedDifficultyValidationRule.java | 2 +- .../transaction/TransactionSimulator.java | 117 +++++++++++++++--- .../ethereum/core/BlockchainSetupUtil.java | 13 +- .../core/ExecutionContextTestFixture.java | 3 +- .../fixed/FixedProtocolScheduleTest.java | 6 +- .../transaction/TransactionSimulatorTest.java | 8 +- .../bonsai/AbstractIsolationTests.java | 3 +- .../AbstractBlockPropagationManagerTest.java | 5 +- .../fullsync/FullSyncTargetManagerTest.java | 3 +- ...neCommonAncestorTaskParameterizedTest.java | 3 +- .../DetermineCommonAncestorTaskTest.java | 3 +- .../ethereum/eth/transactions/TestNode.java | 3 +- ...rtContractPermissioningControllerTest.java | 4 +- ...rtContractPermissioningControllerTest.java | 4 +- .../BlockchainReferenceTestCaseSpec.java | 8 +- .../referencetests/ReferenceTestEnv.java | 3 +- .../mainnet/DifficultyCalculatorTests.java | 4 +- .../ethereum/retesteth/RetestethContext.java | 4 +- .../tracing/AccessListOperationTracer.java | 5 +- .../TransactionSimulationService.java | 4 +- 106 files changed, 813 insertions(+), 636 deletions(-) diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java index d4334fd93cf..bc503d3589d 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java @@ -383,9 +383,14 @@ TransactionSimulator provideTransactionSimulator( final Blockchain blockchain, final WorldStateArchive worldStateArchive, final ProtocolSchedule protocolSchedule, + final MiningParameters miningParameters, final ApiConfiguration apiConfiguration) { return new TransactionSimulator( - blockchain, worldStateArchive, protocolSchedule, apiConfiguration.getGasCap()); + blockchain, + worldStateArchive, + protocolSchedule, + miningParameters, + apiConfiguration.getGasCap()); } @Provides diff --git a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java index 96eef547fed..22f7c260519 100644 --- a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java @@ -697,12 +697,14 @@ public Runner build() { final List bootnodes = discoveryConfiguration.getBootnodes(); final Synchronizer synchronizer = besuController.getSynchronizer(); + final MiningParameters miningParameters = besuController.getMiningParameters(); final TransactionSimulator transactionSimulator = new TransactionSimulator( context.getBlockchain(), context.getWorldStateArchive(), protocolSchedule, + miningParameters, apiConfiguration.getGasCap()); final Bytes localNodeId = nodeKey.getPublicKey().getEncodedBytes(); @@ -773,7 +775,6 @@ public Runner build() { final TransactionPool transactionPool = besuController.getTransactionPool(); final MiningCoordinator miningCoordinator = besuController.getMiningCoordinator(); - final MiningParameters miningParameters = besuController.getMiningParameters(); final BlockchainQueries blockchainQueries = new BlockchainQueries( @@ -867,7 +868,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); jsonRpcHttpService = Optional.of( @@ -912,7 +914,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); final Optional authToUse = engineJsonRpcConfiguration.get().isAuthenticationEnabled() @@ -960,6 +963,7 @@ public Runner build() { graphQlContextMap.putIfAbsent( GraphQLContextType.CHAIN_ID, protocolSchedule.getChainId().map(UInt256::valueOf)); graphQlContextMap.putIfAbsent(GraphQLContextType.GAS_CAP, apiConfiguration.getGasCap()); + graphQlContextMap.putIfAbsent(GraphQLContextType.TRANSACTION_SIMULATOR, transactionSimulator); final GraphQL graphQL; try { graphQL = GraphQLProvider.buildGraphQL(fetchers); @@ -1007,7 +1011,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); createLogsSubscriptionService( context.getBlockchain(), subscriptionManager, privacyParameters, blockchainQueries); @@ -1088,7 +1093,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); jsonRpcIpcService = Optional.of( @@ -1127,7 +1133,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); } else { inProcessRpcMethods = Map.of(); } @@ -1289,7 +1296,8 @@ private Map jsonRpcMethods( final NatService natService, final Map namedPlugins, final Path dataDir, - final RpcEndpointServiceImpl rpcEndpointServiceImpl) { + final RpcEndpointServiceImpl rpcEndpointServiceImpl, + final TransactionSimulator transactionSimulator) { // sync vertx for engine consensus API, to process requests in FIFO order; final Vertx consensusEngineServer = Vertx.vertx(new VertxOptions().setWorkerPoolSize(1)); @@ -1326,7 +1334,8 @@ private Map jsonRpcMethods( besuController.getProtocolManager().ethContext().getEthPeers(), consensusEngineServer, apiConfiguration, - enodeDnsConfiguration); + enodeDnsConfiguration, + transactionSimulator); methods.putAll(besuController.getAdditionalJsonRpcMethods(jsonRpcApis)); final var pluginMethods = 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 b21305c87ad..7a284fab61e 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -1247,6 +1247,7 @@ private void startPlugins(final Runner runner) { besuController.getProtocolContext().getBlockchain(), besuController.getProtocolContext().getWorldStateArchive(), besuController.getProtocolSchedule(), + miningParametersSupplier.get(), apiConfiguration.getGasCap())); rpcEndpointServiceImpl.init(runner.getInProcessRpcMethods()); diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java index bded2a38ac7..ac490d4ca45 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java @@ -989,15 +989,12 @@ protected void validateContext(final ProtocolContext context) {} /** * Create consensus context consensus context. * - * @param blockchain the blockchain - * @param worldStateArchive the world state archive + * @param protocolContext the protocol context * @param protocolSchedule the protocol schedule * @return the consensus context */ protected abstract ConsensusContext createConsensusContext( - Blockchain blockchain, - WorldStateArchive worldStateArchive, - ProtocolSchedule protocolSchedule); + ProtocolContext protocolContext, ProtocolSchedule protocolSchedule); /** * Gets supported protocol. @@ -1066,7 +1063,7 @@ protected ProtocolContext createProtocolContext( final WorldStateArchive worldStateArchive, final ProtocolSchedule protocolSchedule, final ConsensusContextFactory consensusContextFactory) { - return ProtocolContext.init( + return ProtocolContext.create( blockchain, worldStateArchive, protocolSchedule, consensusContextFactory, badBlockManager); } 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 b4ada605498..89f02c7dd86 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java @@ -29,6 +29,7 @@ import org.hyperledger.besu.consensus.common.BlockInterface; import org.hyperledger.besu.consensus.common.EpochManager; import org.hyperledger.besu.consensus.common.ForksSchedule; +import org.hyperledger.besu.consensus.common.validator.ValidatorProvider; import org.hyperledger.besu.consensus.common.validator.blockbased.BlockValidatorProvider; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.ProtocolContext; @@ -42,7 +43,8 @@ import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; -import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; + +import java.util.concurrent.atomic.AtomicReference; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -56,6 +58,7 @@ public class CliqueBesuControllerBuilder extends BesuControllerBuilder { private EpochManager epochManager; private final BlockInterface blockInterface = new CliqueBlockInterface(); private ForksSchedule forksSchedule; + private final AtomicReference validatorProviderRef = new AtomicReference<>(); /** Default constructor. */ public CliqueBesuControllerBuilder() {} @@ -138,7 +141,8 @@ protected ProtocolSchedule createProtocolSchedule() { miningParameters, badBlockManager, isParallelTxProcessingEnabled, - metricsSystem); + metricsSystem, + validatorProviderRef::get); } @Override @@ -158,19 +162,19 @@ protected PluginServiceFactory createAdditionalPluginServices( @Override protected CliqueContext createConsensusContext( - final Blockchain blockchain, - final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule) { + final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { + validatorProviderRef.set(createValidatorProvider(protocolContext.getBlockchain())); final CliqueContext cliqueContext = - new CliqueContext( - BlockValidatorProvider.nonForkingValidatorProvider( - blockchain, epochManager, blockInterface), - epochManager, - blockInterface); - installCliqueBlockChoiceRule(blockchain, cliqueContext); + new CliqueContext(validatorProviderRef.get(), epochManager, blockInterface); + installCliqueBlockChoiceRule(protocolContext.getBlockchain(), cliqueContext); return cliqueContext; } + private ValidatorProvider createValidatorProvider(final Blockchain blockchain) { + return BlockValidatorProvider.nonForkingValidatorProvider( + blockchain, epochManager, blockInterface); + } + @Override public MiningParameters getMiningParameterOverrides(final MiningParameters fromCli) { // Clique mines by default, reflect that with in the mining parameters: diff --git a/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java index 0d0f8d2fd87..2780dbd73d0 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java @@ -176,19 +176,15 @@ protected ProtocolContext createProtocolContext( @Override protected ConsensusContext createConsensusContext( - final Blockchain blockchain, - final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule) { + final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { final List> consensusContextSpecs = besuControllerBuilderSchedule.entrySet().stream() .map( e -> new ForkSpec<>( e.getKey(), - e.getValue() - .createConsensusContext( - blockchain, worldStateArchive, protocolSchedule))) - .collect(Collectors.toList()); + e.getValue().createConsensusContext(protocolContext, protocolSchedule))) + .toList(); final ForksSchedule consensusContextsSchedule = new ForksSchedule<>(consensusContextSpecs); return new MigratingContext(consensusContextsSchedule); 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 738dcfc5963..1b1bc212ec1 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java @@ -70,7 +70,6 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; -import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.plugin.services.BesuEvents; import org.hyperledger.besu.util.Subscribers; @@ -320,9 +319,7 @@ protected void validateContext(final ProtocolContext context) { @Override protected BftContext createConsensusContext( - final Blockchain blockchain, - final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule) { + final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { final BftConfigOptions ibftConfig = genesisConfigOptions.getBftConfigOptions(); final EpochManager epochManager = new EpochManager(ibftConfig.getEpochLength()); @@ -331,7 +328,10 @@ protected BftContext createConsensusContext( return new BftContext( BlockValidatorProvider.forkingValidatorProvider( - blockchain, epochManager, bftBlockInterface().get(), validatorOverrides), + protocolContext.getBlockchain(), + epochManager, + bftBlockInterface().get(), + validatorOverrides), epochManager, bftBlockInterface().get()); } 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 e0fbed608ab..7ac1d8c35da 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java @@ -29,7 +29,6 @@ import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderValidator; import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; -import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; /** The Mainnet besu controller builder. */ public class MainnetBesuControllerBuilder extends BesuControllerBuilder { @@ -79,9 +78,7 @@ protected MiningCoordinator createMiningCoordinator( @Override protected ConsensusContext createConsensusContext( - final Blockchain blockchain, - final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule) { + final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { return null; } diff --git a/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java index f5fc75959e1..03079de42fe 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java @@ -44,7 +44,6 @@ import org.hyperledger.besu.ethereum.forkid.ForkIdManager; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions; -import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import java.util.List; import java.util.Optional; @@ -184,10 +183,9 @@ protected ProtocolSchedule createProtocolSchedule() { @Override protected MergeContext createConsensusContext( - final Blockchain blockchain, - final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule) { + final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { + final var blockchain = protocolContext.getBlockchain(); final OptionalLong terminalBlockNumber = genesisConfigOptions.getTerminalBlockNumber(); final Optional terminalBlockHash = genesisConfigOptions.getTerminalBlockHash(); final boolean isPostMergeAtGenesis = diff --git a/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java index 498435e4afb..c5c0f5c6720 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java @@ -80,7 +80,6 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; -import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.plugin.services.BesuEvents; import org.hyperledger.besu.util.Subscribers; @@ -112,10 +111,7 @@ public QbftBesuControllerBuilder() {} @Override protected Supplier bftExtraDataCodec() { - return Suppliers.memoize( - () -> { - return new QbftExtraDataCodec(); - }); + return Suppliers.memoize(() -> new QbftExtraDataCodec()); } @Override @@ -391,26 +387,37 @@ private boolean signersExistIn(final BlockHeader genesisBlockHeader) { @Override protected BftContext createConsensusContext( - final Blockchain blockchain, - final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule) { + final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { final EpochManager epochManager = new EpochManager(qbftConfig.getEpochLength()); final BftValidatorOverrides validatorOverrides = convertBftForks(genesisConfigOptions.getTransitions().getQbftForks()); final BlockValidatorProvider blockValidatorProvider = BlockValidatorProvider.forkingValidatorProvider( - blockchain, epochManager, bftBlockInterface().get(), validatorOverrides); + protocolContext.getBlockchain(), + epochManager, + bftBlockInterface().get(), + validatorOverrides); final TransactionSimulator transactionSimulator = - new TransactionSimulator(blockchain, worldStateArchive, protocolSchedule, 0L); + new TransactionSimulator( + protocolContext.getBlockchain(), + protocolContext.getWorldStateArchive(), + protocolSchedule, + miningParameters, + 0L); transactionValidatorProvider = new TransactionValidatorProvider( - blockchain, new ValidatorContractController(transactionSimulator), qbftForksSchedule); + protocolContext.getBlockchain(), + new ValidatorContractController(transactionSimulator), + qbftForksSchedule); final ValidatorProvider validatorProvider = new ForkingValidatorProvider( - blockchain, qbftForksSchedule, blockValidatorProvider, transactionValidatorProvider); + protocolContext.getBlockchain(), + qbftForksSchedule, + blockValidatorProvider, + transactionValidatorProvider); return new BftContext(validatorProvider, epochManager, bftBlockInterface().get()); } 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 ee2611d9c87..cbe5e4454f8 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java @@ -203,14 +203,10 @@ protected ProtocolContext createProtocolContext( @Override protected ConsensusContext createConsensusContext( - final Blockchain blockchain, - final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule) { + final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { return new TransitionContext( - preMergeBesuControllerBuilder.createConsensusContext( - blockchain, worldStateArchive, protocolSchedule), - mergeBesuControllerBuilder.createConsensusContext( - blockchain, worldStateArchive, protocolSchedule)); + preMergeBesuControllerBuilder.createConsensusContext(protocolContext, protocolSchedule), + mergeBesuControllerBuilder.createConsensusContext(protocolContext, protocolSchedule)); } @Override diff --git a/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java index 54cce205a36..0e2ed37413b 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java @@ -59,31 +59,45 @@ public void init(final Blockchain blockchain, final TransactionSimulator transac @Override public Optional simulate( final Transaction transaction, - final Hash blockHash, + final Optional maybeBlockHash, final OperationTracer operationTracer, final boolean isAllowExceedingBalance) { final CallParameter callParameter = CallParameter.fromTransaction(transaction); - final var maybeBlockHeader = - blockchain.getBlockHeader(blockHash).or(() -> blockchain.getBlockHeaderSafe(blockHash)); + if (maybeBlockHash.isPresent()) { + final Hash blockHash = maybeBlockHash.get(); - if (maybeBlockHeader.isEmpty()) { - return Optional.of( - new TransactionSimulationResult( - transaction, - TransactionProcessingResult.invalid( - ValidationResult.invalid(TransactionInvalidReason.BLOCK_NOT_FOUND)))); + final var maybeBlockHeader = + blockchain.getBlockHeader(blockHash).or(() -> blockchain.getBlockHeaderSafe(blockHash)); + + if (maybeBlockHeader.isEmpty()) { + return Optional.of( + new TransactionSimulationResult( + transaction, + TransactionProcessingResult.invalid( + ValidationResult.invalid(TransactionInvalidReason.BLOCK_NOT_FOUND)))); + } + + return transactionSimulator + .process( + callParameter, + isAllowExceedingBalance + ? SIMULATOR_ALLOWING_EXCEEDING_BALANCE + : TransactionValidationParams.transactionSimulator(), + operationTracer, + maybeBlockHeader.get()) + .map(res -> new TransactionSimulationResult(transaction, res.result())); } return transactionSimulator - .process( + .processOnPending( callParameter, isAllowExceedingBalance ? SIMULATOR_ALLOWING_EXCEEDING_BALANCE : TransactionValidationParams.transactionSimulator(), operationTracer, - maybeBlockHeader.get()) + transactionSimulator.simulatePendingBlockHeader()) .map(res -> new TransactionSimulationResult(transaction, res.result())); } } diff --git a/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java index 5efeed50b24..401cdcdab31 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java @@ -30,14 +30,12 @@ import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; 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.MiningParameters; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; -import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import java.math.BigInteger; import java.util.Collections; @@ -173,16 +171,14 @@ public void createsMigratingContext() { besuControllerBuilderSchedule.put(0L, besuControllerBuilder1); besuControllerBuilderSchedule.put(10L, besuControllerBuilder2); - when(besuControllerBuilder1.createConsensusContext(any(), any(), any())).thenReturn(context1); - when(besuControllerBuilder2.createConsensusContext(any(), any(), any())).thenReturn(context2); + when(besuControllerBuilder1.createConsensusContext(any(), any())).thenReturn(context1); + when(besuControllerBuilder2.createConsensusContext(any(), any())).thenReturn(context2); final ConsensusScheduleBesuControllerBuilder controllerBuilder = new ConsensusScheduleBesuControllerBuilder(besuControllerBuilderSchedule); final ConsensusContext consensusContext = controllerBuilder.createConsensusContext( - Mockito.mock(Blockchain.class), - Mockito.mock(WorldStateArchive.class), - Mockito.mock(ProtocolSchedule.class)); + Mockito.mock(ProtocolContext.class), Mockito.mock(ProtocolSchedule.class)); assertThat(consensusContext).isInstanceOf(MigratingContext.class); final MigratingContext migratingContext = (MigratingContext) consensusContext; 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 f8c00b20ea7..5bff87b8b2f 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java @@ -33,7 +33,7 @@ import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; -import org.hyperledger.besu.ethereum.chain.Blockchain; +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.Block; @@ -55,7 +55,6 @@ import org.hyperledger.besu.ethereum.storage.keyvalue.VariablesKeyValueStorage; import org.hyperledger.besu.ethereum.trie.forest.storage.ForestWorldStateKeyValueStorage; import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; -import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.ethereum.worldstate.WorldStatePreimageStorage; import org.hyperledger.besu.ethereum.worldstate.WorldStateStorageCoordinator; import org.hyperledger.besu.evm.internal.EvmConfiguration; @@ -211,13 +210,13 @@ public void assertTerminalTotalDifficultyInMergeContext() { @Test public void assertConfiguredBlock() { - final Blockchain mockChain = mock(Blockchain.class); + final MutableBlockchain mockChain = mock(MutableBlockchain.class); when(mockChain.getBlockHeader(anyLong())).thenReturn(Optional.of(mock(BlockHeader.class))); + final ProtocolContext mockContext = mock(ProtocolContext.class); + when(mockContext.getBlockchain()).thenReturn(mockChain); final MergeContext mergeContext = besuControllerBuilder.createConsensusContext( - mockChain, - mock(WorldStateArchive.class), - this.besuControllerBuilder.createProtocolSchedule()); + mockContext, this.besuControllerBuilder.createProtocolSchedule()); assertThat(mergeContext).isNotNull(); assertThat(mergeContext.getTerminalPoWBlock()).isPresent(); } @@ -228,12 +227,12 @@ public void assertBuiltContextMonitorsTTD() { GenesisState.fromConfig( genesisConfigFile, this.besuControllerBuilder.createProtocolSchedule()); final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); + final ProtocolContext mockContext = mock(ProtocolContext.class); + when(mockContext.getBlockchain()).thenReturn(blockchain); final MergeContext mergeContext = spy( besuControllerBuilder.createConsensusContext( - blockchain, - mock(WorldStateArchive.class), - this.besuControllerBuilder.createProtocolSchedule())); + mockContext, this.besuControllerBuilder.createProtocolSchedule())); assertThat(mergeContext).isNotNull(); final Difficulty over = Difficulty.of(10000L); final Difficulty under = Difficulty.of(10L); @@ -263,13 +262,13 @@ public void assertBuiltContextMonitorsTTD() { @Test public void assertNoFinalizedBlockWhenNotStored() { - final Blockchain mockChain = mock(Blockchain.class); + final MutableBlockchain mockChain = mock(MutableBlockchain.class); when(mockChain.getFinalized()).thenReturn(Optional.empty()); + final ProtocolContext mockContext = mock(ProtocolContext.class); + when(mockContext.getBlockchain()).thenReturn(mockChain); final MergeContext mergeContext = besuControllerBuilder.createConsensusContext( - mockChain, - mock(WorldStateArchive.class), - this.besuControllerBuilder.createProtocolSchedule()); + mockContext, this.besuControllerBuilder.createProtocolSchedule()); assertThat(mergeContext).isNotNull(); assertThat(mergeContext.getFinalized()).isEmpty(); } @@ -278,15 +277,15 @@ public void assertNoFinalizedBlockWhenNotStored() { public void assertFinalizedBlockIsPresentWhenStored() { final BlockHeader finalizedHeader = finalizedBlockHeader(); - final Blockchain mockChain = mock(Blockchain.class); + final MutableBlockchain mockChain = mock(MutableBlockchain.class); when(mockChain.getFinalized()).thenReturn(Optional.of(finalizedHeader.getHash())); when(mockChain.getBlockHeader(finalizedHeader.getHash())) .thenReturn(Optional.of(finalizedHeader)); + final ProtocolContext mockContext = mock(ProtocolContext.class); + when(mockContext.getBlockchain()).thenReturn(mockChain); final MergeContext mergeContext = besuControllerBuilder.createConsensusContext( - mockChain, - mock(WorldStateArchive.class), - this.besuControllerBuilder.createProtocolSchedule()); + mockContext, this.besuControllerBuilder.createProtocolSchedule()); assertThat(mergeContext).isNotNull(); assertThat(mergeContext.getFinalized().get()).isEqualTo(finalizedHeader); } diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/CliqueDifficultyCalculator.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/CliqueDifficultyCalculator.java index a5771238d2a..c8a9f2d892b 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/CliqueDifficultyCalculator.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/CliqueDifficultyCalculator.java @@ -14,17 +14,19 @@ */ package org.hyperledger.besu.consensus.clique; +import org.hyperledger.besu.consensus.common.validator.ValidatorProvider; import org.hyperledger.besu.datatypes.Address; -import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.mainnet.DifficultyCalculator; import java.math.BigInteger; +import java.util.function.Supplier; /** The Clique difficulty calculator. */ public class CliqueDifficultyCalculator implements DifficultyCalculator { private final Address localAddress; + private final Supplier validatorProviderSupplier; private final BigInteger IN_TURN_DIFFICULTY = BigInteger.valueOf(2); private final BigInteger OUT_OF_TURN_DIFFICULTY = BigInteger.ONE; @@ -33,18 +35,19 @@ public class CliqueDifficultyCalculator implements DifficultyCalculator { * Instantiates a new Clique difficulty calculator. * * @param localAddress the local address + * @param validatorProviderSupplier the validator provider supplier */ - public CliqueDifficultyCalculator(final Address localAddress) { + public CliqueDifficultyCalculator( + final Address localAddress, final Supplier validatorProviderSupplier) { this.localAddress = localAddress; + this.validatorProviderSupplier = validatorProviderSupplier; } @Override - public BigInteger nextDifficulty( - final long time, final BlockHeader parent, final ProtocolContext context) { + public BigInteger nextDifficulty(final long time, final BlockHeader parent) { final Address nextProposer = - CliqueHelpers.getProposerForBlockAfter( - parent, context.getConsensusContext(CliqueContext.class).getValidatorProvider()); + CliqueHelpers.getProposerForBlockAfter(parent, validatorProviderSupplier.get()); return nextProposer.equals(localAddress) ? IN_TURN_DIFFICULTY : OUT_OF_TURN_DIFFICULTY; } } diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/CliqueProtocolSchedule.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/CliqueProtocolSchedule.java index cd197556386..e46c4bf9a6e 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/CliqueProtocolSchedule.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/CliqueProtocolSchedule.java @@ -18,6 +18,7 @@ import org.hyperledger.besu.config.GenesisConfigOptions; import org.hyperledger.besu.consensus.common.EpochManager; import org.hyperledger.besu.consensus.common.ForksSchedule; +import org.hyperledger.besu.consensus.common.validator.ValidatorProvider; import org.hyperledger.besu.cryptoservices.NodeKey; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; @@ -43,8 +44,7 @@ import java.util.Map; import java.util.Optional; import java.util.function.Function; - -import com.google.common.annotations.VisibleForTesting; +import java.util.function.Supplier; /** Defines the protocol behaviours for a blockchain using Clique. */ public class CliqueProtocolSchedule { @@ -68,6 +68,7 @@ public class CliqueProtocolSchedule { * @param isParallelTxProcessingEnabled indicates whether parallel transaction is enabled * @param metricsSystem A metricSystem instance to be able to expose metrics in the underlying * calls + * @param validatorProviderSupplier the validator provider supplier * @return the protocol schedule */ public static ProtocolSchedule create( @@ -80,7 +81,8 @@ public static ProtocolSchedule create( final MiningParameters miningParameters, final BadBlockManager badBlockManager, final boolean isParallelTxProcessingEnabled, - final MetricsSystem metricsSystem) { + final MetricsSystem metricsSystem, + final Supplier validatorProviderSupplier) { final CliqueConfigOptions cliqueConfig = config.getCliqueConfigOptions(); @@ -105,6 +107,7 @@ public static ProtocolSchedule create( forkSpec.getValue().getBlockPeriodSeconds(), forkSpec.getValue().getCreateEmptyBlocks(), localNodeAddress, + validatorProviderSupplier, builder))); final ProtocolSpecAdapters specAdapters = new ProtocolSpecAdapters(specMap); @@ -122,50 +125,12 @@ public static ProtocolSchedule create( .createProtocolSchedule(); } - /** - * Create protocol schedule. - * - * @param config the config - * @param forksSchedule the transitions - * @param nodeKey the node key - * @param isRevertReasonEnabled the is revert reason enabled - * @param evmConfiguration the evm configuration - * @param miningParameters the mining parameters - * @param badBlockManager the cache to use to keep invalid blocks - * @param isParallelTxProcessingEnabled indicates whether parallel transaction is enabled - * @param metricsSystem A metricSystem instance to be able to expose metrics in the underlying - * calls - * @return the protocol schedule - */ - @VisibleForTesting - public static ProtocolSchedule create( - final GenesisConfigOptions config, - final ForksSchedule forksSchedule, - final NodeKey nodeKey, - final boolean isRevertReasonEnabled, - final EvmConfiguration evmConfiguration, - final MiningParameters miningParameters, - final BadBlockManager badBlockManager, - final boolean isParallelTxProcessingEnabled, - final MetricsSystem metricsSystem) { - return create( - config, - forksSchedule, - nodeKey, - PrivacyParameters.DEFAULT, - isRevertReasonEnabled, - evmConfiguration, - miningParameters, - badBlockManager, - isParallelTxProcessingEnabled, - metricsSystem); - } - private static ProtocolSpecBuilder applyCliqueSpecificModifications( final EpochManager epochManager, final long secondsBetweenBlocks, final boolean createEmptyBlocks, final Address localNodeAddress, + final Supplier validatorProviderSupplier, final ProtocolSpecBuilder specBuilder) { return specBuilder @@ -180,7 +145,8 @@ private static ProtocolSpecBuilder applyCliqueSpecificModifications( .blockBodyValidatorBuilder(MainnetBlockBodyValidator::new) .blockValidatorBuilder(MainnetProtocolSpecs.blockValidatorBuilder()) .blockImporterBuilder(MainnetBlockImporter::new) - .difficultyCalculator(new CliqueDifficultyCalculator(localNodeAddress)) + .difficultyCalculator( + new CliqueDifficultyCalculator(localNodeAddress, validatorProviderSupplier)) .blockReward(Wei.ZERO) .skipZeroBlockRewards(true) .miningBeneficiaryCalculator(CliqueHelpers::getProposerOfBlock) diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRule.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRule.java index a14b5187ef7..86e8c6bd484 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRule.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRule.java @@ -14,6 +14,7 @@ */ package org.hyperledger.besu.consensus.clique.headervalidationrules; +import org.hyperledger.besu.consensus.clique.CliqueContext; import org.hyperledger.besu.consensus.clique.CliqueDifficultyCalculator; import org.hyperledger.besu.consensus.clique.CliqueHelpers; import org.hyperledger.besu.datatypes.Address; @@ -38,10 +39,11 @@ public CliqueDifficultyValidationRule() {} public boolean validate( final BlockHeader header, final BlockHeader parent, final ProtocolContext protocolContext) { final Address actualBlockCreator = CliqueHelpers.getProposerOfBlock(header); - + final var cliqueContext = protocolContext.getConsensusContext(CliqueContext.class); final CliqueDifficultyCalculator diffCalculator = - new CliqueDifficultyCalculator(actualBlockCreator); - final BigInteger expectedDifficulty = diffCalculator.nextDifficulty(0, parent, protocolContext); + new CliqueDifficultyCalculator( + actualBlockCreator, () -> cliqueContext.getValidatorProvider()); + final BigInteger expectedDifficulty = diffCalculator.nextDifficulty(0, parent); final BigInteger actualDifficulty = header.getDifficulty().toBigInteger(); diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueDifficultyCalculatorTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueDifficultyCalculatorTest.java index 3c9da2520d9..09a9ed4dcf7 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueDifficultyCalculatorTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueDifficultyCalculatorTest.java @@ -23,8 +23,6 @@ import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.crypto.SignatureAlgorithmFactory; import org.hyperledger.besu.datatypes.Address; -import org.hyperledger.besu.ethereum.ProtocolContext; -import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.core.AddressHelpers; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; @@ -32,6 +30,7 @@ import java.math.BigInteger; import java.util.List; +import java.util.function.Supplier; import com.google.common.collect.Lists; import org.junit.jupiter.api.BeforeEach; @@ -43,9 +42,8 @@ public class CliqueDifficultyCalculatorTest { private Address localAddr; private final List
validatorList = Lists.newArrayList(); - private ProtocolContext cliqueProtocolContext; + private Supplier validatorProviderSupplier; private BlockHeaderTestFixture blockHeaderBuilder; - private final CliqueBlockInterface blockInterface = new CliqueBlockInterface(); @BeforeEach public void setup() { @@ -56,29 +54,27 @@ public void setup() { final ValidatorProvider validatorProvider = mock(ValidatorProvider.class); when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); - - final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); - cliqueProtocolContext = new ProtocolContext(null, null, cliqueContext, new BadBlockManager()); + validatorProviderSupplier = () -> validatorProvider; blockHeaderBuilder = new BlockHeaderTestFixture(); } @Test public void inTurnValidatorProducesDifficultyOfTwo() { - final CliqueDifficultyCalculator calculator = new CliqueDifficultyCalculator(localAddr); + final CliqueDifficultyCalculator calculator = + new CliqueDifficultyCalculator(localAddr, validatorProviderSupplier); final BlockHeader parentHeader = blockHeaderBuilder.number(1).buildHeader(); - assertThat(calculator.nextDifficulty(0, parentHeader, cliqueProtocolContext)) - .isEqualTo(BigInteger.valueOf(2)); + assertThat(calculator.nextDifficulty(0, parentHeader)).isEqualTo(BigInteger.valueOf(2)); } @Test public void outTurnValidatorProducesDifficultyOfOne() { - final CliqueDifficultyCalculator calculator = new CliqueDifficultyCalculator(localAddr); + final CliqueDifficultyCalculator calculator = + new CliqueDifficultyCalculator(localAddr, validatorProviderSupplier); final BlockHeader parentHeader = blockHeaderBuilder.number(2).buildHeader(); - assertThat(calculator.nextDifficulty(0, parentHeader, cliqueProtocolContext)) - .isEqualTo(BigInteger.valueOf(1)); + assertThat(calculator.nextDifficulty(0, parentHeader)).isEqualTo(BigInteger.valueOf(1)); } } diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueProtocolScheduleTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueProtocolScheduleTest.java index 5cbdbb6d06e..60a6be7a33f 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueProtocolScheduleTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/CliqueProtocolScheduleTest.java @@ -33,6 +33,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.MiningParameters; +import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec; @@ -66,12 +67,14 @@ public void protocolSpecsAreCreatedAtBlockDefinedInJson() { config, new ForksSchedule<>(List.of()), NODE_KEY, + PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager(), false, - new NoOpMetricsSystem()); + new NoOpMetricsSystem(), + () -> null); final ProtocolSpec homesteadSpec = protocolSchedule.getByBlockHeader(blockHeader(1)); final ProtocolSpec tangerineWhistleSpec = protocolSchedule.getByBlockHeader(blockHeader(2)); @@ -92,12 +95,14 @@ public void parametersAlignWithMainnetWithAdjustments() { GenesisConfigFile.DEFAULT.getConfigOptions(), forksSchedule, NODE_KEY, + PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager(), false, - new NoOpMetricsSystem()) + new NoOpMetricsSystem(), + () -> null) .getByBlockHeader(blockHeader(0)); assertThat(homestead.getName()).isEqualTo("Frontier"); @@ -118,12 +123,14 @@ public void zeroEpochLengthThrowsException() { genesisConfig, new ForksSchedule<>(List.of()), NODE_KEY, + PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager(), false, - new NoOpMetricsSystem())) + new NoOpMetricsSystem(), + () -> null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Epoch length in config must be greater than zero"); } @@ -140,12 +147,14 @@ public void negativeEpochLengthThrowsException() { genesisConfig, new ForksSchedule<>(List.of()), NODE_KEY, + PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager(), false, - new NoOpMetricsSystem())) + new NoOpMetricsSystem(), + () -> null)) .isInstanceOf(IllegalArgumentException.class) .hasMessage("Epoch length in config must be greater than zero"); } @@ -166,12 +175,14 @@ public void shouldValidateBaseFeeMarketTransition() { config, forksSchedule, NODE_KEY, + PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager(), false, - new NoOpMetricsSystem()); + new NoOpMetricsSystem(), + () -> null); BlockHeader emptyFrontierParent = headerBuilder diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/NodeCanProduceNextBlockTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/NodeCanProduceNextBlockTest.java index afd9651df61..f53b308a0ad 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/NodeCanProduceNextBlockTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/NodeCanProduceNextBlockTest.java @@ -81,7 +81,8 @@ public void networkWithOneValidatorIsAllowedToCreateConsecutiveBlocks() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - new ProtocolContext(blockChain, null, cliqueContext, new BadBlockManager()); + ProtocolContext.create( + blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); headerBuilder.number(1).parentHash(genesisBlock.getHash()); final Block block_1 = createEmptyBlock(proposerKeyPair); @@ -106,7 +107,8 @@ public void networkWithTwoValidatorsIsAllowedToProduceBlockIfNotPreviousBlockPro when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - new ProtocolContext(blockChain, null, cliqueContext, new BadBlockManager()); + ProtocolContext.create( + blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); headerBuilder.number(1).parentHash(genesisBlock.getHash()); final Block block_1 = createEmptyBlock(proposerKeyPair); @@ -140,7 +142,8 @@ public void networkWithTwoValidatorsIsNotAllowedToProduceBlockIfIsPreviousBlockP when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - new ProtocolContext(blockChain, null, cliqueContext, new BadBlockManager()); + ProtocolContext.create( + blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); headerBuilder.parentHash(genesisBlock.getHash()).number(1); final Block block_1 = createEmptyBlock(proposerKeyPair); @@ -170,7 +173,8 @@ public void withThreeValidatorsMustHaveOneBlockBetweenSignings() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - new ProtocolContext(blockChain, null, cliqueContext, new BadBlockManager()); + ProtocolContext.create( + blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); headerBuilder.parentHash(genesisBlock.getHash()).number(1); final Block block_1 = createEmptyBlock(proposerKeyPair); @@ -215,7 +219,8 @@ public void signerIsValidIfInsufficientBlocksExistInHistory() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - new ProtocolContext(blockChain, null, cliqueContext, new BadBlockManager()); + ProtocolContext.create( + blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); headerBuilder.parentHash(genesisBlock.getHash()).number(1); final Block block_1 = createEmptyBlock(otherNodeKeyPair); @@ -244,7 +249,8 @@ public void exceptionIsThrownIfOnAnOrphanedChain() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - new ProtocolContext(blockChain, null, cliqueContext, new BadBlockManager()); + ProtocolContext.create( + blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); headerBuilder.parentHash(Hash.ZERO).number(3); final BlockHeader parentHeader = @@ -268,7 +274,8 @@ public void nonValidatorIsNotAllowedToCreateABlock() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - new ProtocolContext(blockChain, null, cliqueContext, new BadBlockManager()); + ProtocolContext.create( + blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); headerBuilder.parentHash(Hash.ZERO).number(3); final BlockHeader parentHeader = headerBuilder.buildHeader(); 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 ca76517c62c..065320103bc 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 @@ -52,6 +52,7 @@ 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.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; @@ -99,32 +100,36 @@ public class CliqueBlockCreatorTest { @BeforeEach void setup() { + final Address otherAddress = Util.publicKeyToAddress(otherKeyPair.getPublicKey()); + validatorList.add(otherAddress); + + validatorProvider = mock(ValidatorProvider.class); + voteProvider = mock(VoteProvider.class); + when(validatorProvider.getVoteProviderAtHead()).thenReturn(Optional.of(voteProvider)); + when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); + protocolSchedule = CliqueProtocolSchedule.create( GenesisConfigFile.DEFAULT.getConfigOptions(), new ForksSchedule<>(List.of()), proposerNodeKey, + PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager(), false, - new NoOpMetricsSystem()); + new NoOpMetricsSystem(), + () -> validatorProvider); - final Address otherAddress = Util.publicKeyToAddress(otherKeyPair.getPublicKey()); - validatorList.add(otherAddress); - - validatorProvider = mock(ValidatorProvider.class); - voteProvider = mock(VoteProvider.class); - when(validatorProvider.getVoteProviderAtHead()).thenReturn(Optional.of(voteProvider)); - when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); final Block genesis = GenesisState.fromConfig(GenesisConfigFile.mainnet(), protocolSchedule).getBlock(); blockchain = createInMemoryBlockchain(genesis); protocolContext = - new ProtocolContext(blockchain, stateArchive, cliqueContext, new BadBlockManager()); + ProtocolContext.create( + blockchain, stateArchive, null, (pc, ps) -> cliqueContext, new BadBlockManager()); epochManager = new EpochManager(10); // Add a block above the genesis diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockMinerTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockMinerTest.java index 8aca4713cd9..3d4d65ab7fa 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockMinerTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockMinerTest.java @@ -86,7 +86,7 @@ void doesNotMineBlockIfNoTransactionsWhenEmptyBlocksNotAllowed() throws Interrup final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, null); final ProtocolContext protocolContext = - new ProtocolContext(null, null, cliqueContext, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); final CliqueBlockCreator blockCreator = mock(CliqueBlockCreator.class); final Function blockCreatorSupplier = @@ -142,7 +142,7 @@ void minesBlockIfHasTransactionsWhenEmptyBlocksNotAllowed() throws InterruptedEx final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, null); final ProtocolContext protocolContext = - new ProtocolContext(null, null, cliqueContext, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); final CliqueBlockCreator blockCreator = mock(CliqueBlockCreator.class); final Function blockCreatorSupplier = 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 1aa2d75ef3b..1c97dbaab73 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 @@ -42,6 +42,7 @@ 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.Util; import org.hyperledger.besu.ethereum.eth.manager.EthContext; import org.hyperledger.besu.ethereum.eth.manager.EthScheduler; @@ -97,18 +98,21 @@ public void setup() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); - cliqueProtocolContext = new ProtocolContext(null, null, cliqueContext, new BadBlockManager()); + cliqueProtocolContext = + ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); cliqueProtocolSchedule = CliqueProtocolSchedule.create( GENESIS_CONFIG_OPTIONS, new ForksSchedule<>(List.of()), proposerNodeKey, + PrivacyParameters.DEFAULT, false, EvmConfiguration.DEFAULT, MiningParameters.MINING_DISABLED, new BadBlockManager(), false, - new NoOpMetricsSystem()); + new NoOpMetricsSystem(), + () -> validatorProvider); cliqueEthContext = mock(EthContext.class, RETURNS_DEEP_STUBS); blockHeaderBuilder = new BlockHeaderTestFixture(); } diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRuleTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRuleTest.java index d970d83d80e..a62433653c9 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRuleTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRuleTest.java @@ -58,7 +58,8 @@ public void setup() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); - cliqueProtocolContext = new ProtocolContext(null, null, cliqueContext, new BadBlockManager()); + cliqueProtocolContext = + ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); blockHeaderBuilder = new BlockHeaderTestFixture(); } diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueExtraDataValidationRuleTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueExtraDataValidationRuleTest.java index afcc7e23c2f..917034221b2 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueExtraDataValidationRuleTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueExtraDataValidationRuleTest.java @@ -62,7 +62,8 @@ public void setup() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); - cliqueProtocolContext = new ProtocolContext(null, null, cliqueContext, new BadBlockManager()); + cliqueProtocolContext = + ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); } @Test diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingProtocolContext.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingProtocolContext.java index c0557485f3e..7651e3c9910 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingProtocolContext.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingProtocolContext.java @@ -25,23 +25,20 @@ /** The Migrating protocol context. */ public class MigratingProtocolContext extends ProtocolContext { - private final ForksSchedule consensusContextSchedule; + private ForksSchedule consensusContextSchedule; /** * Instantiates a new Migrating protocol context. * * @param blockchain the blockchain * @param worldStateArchive the world state archive - * @param consensusContextSchedule the consensus context schedule * @param badBlockManager the cache to use to keep invalid blocks */ - public MigratingProtocolContext( + private MigratingProtocolContext( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, - final ForksSchedule consensusContextSchedule, final BadBlockManager badBlockManager) { - super(blockchain, worldStateArchive, null, badBlockManager); - this.consensusContextSchedule = consensusContextSchedule; + super(blockchain, worldStateArchive, badBlockManager); } /** @@ -54,20 +51,26 @@ public MigratingProtocolContext( * @param badBlockManager the cache to use to keep invalid blocks * @return the protocol context */ - public static ProtocolContext init( + public static MigratingProtocolContext init( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, final ProtocolSchedule protocolSchedule, final ConsensusContextFactory consensusContextFactory, final BadBlockManager badBlockManager) { + final var migratingProtocolContext = + new MigratingProtocolContext(blockchain, worldStateArchive, badBlockManager); + final ConsensusContext consensusContext = - consensusContextFactory.create(blockchain, worldStateArchive, protocolSchedule); + consensusContextFactory.create(migratingProtocolContext, protocolSchedule); final MigratingContext migratingContext = consensusContext.as(MigratingContext.class); - return new MigratingProtocolContext( - blockchain, - worldStateArchive, - migratingContext.getConsensusContextSchedule(), - badBlockManager); + migratingProtocolContext.setConsensusContextSchedule( + migratingContext.getConsensusContextSchedule()); + return migratingProtocolContext; + } + + private void setConsensusContextSchedule( + final ForksSchedule consensusContextSchedule) { + this.consensusContextSchedule = consensusContextSchedule; } @Override diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/BaseBftProtocolScheduleBuilder.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/BaseBftProtocolScheduleBuilder.java index 311bf30faef..c51f3d1f9f9 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/BaseBftProtocolScheduleBuilder.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/bft/BaseBftProtocolScheduleBuilder.java @@ -132,7 +132,7 @@ private ProtocolSpecBuilder applyBftChanges( .blockBodyValidatorBuilder(MainnetBlockBodyValidator::new) .blockValidatorBuilder(MainnetProtocolSpecs.blockValidatorBuilder()) .blockImporterBuilder(MainnetBlockImporter::new) - .difficultyCalculator((time, parent, protocolContext) -> BigInteger.ONE) + .difficultyCalculator((time, parent) -> BigInteger.ONE) .skipZeroBlockRewards(true) .blockHeaderFunctions(BftBlockHeaderFunctions.forOnchainBlock(bftExtraDataCodec)) .blockReward(Wei.of(configOptions.getBlockRewardWei())) diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/MigratingProtocolContextTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/MigratingProtocolContextTest.java index d62de57eac9..0aa60bfcce3 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/MigratingProtocolContextTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/MigratingProtocolContextTest.java @@ -19,6 +19,7 @@ import static org.mockito.Mockito.when; import org.hyperledger.besu.ethereum.ConsensusContext; +import org.hyperledger.besu.ethereum.ConsensusContextFactory; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; @@ -43,9 +44,12 @@ public void returnsContextForSpecificChainHeight() { final ForksSchedule contextSchedule = new ForksSchedule<>(List.of(new ForkSpec<>(0L, context1), new ForkSpec<>(10L, context2))); + final ConsensusContextFactory consensusContextFactory = + (pc, ps) -> new MigratingContext(contextSchedule); + final MigratingProtocolContext migratingProtocolContext = - new MigratingProtocolContext( - blockchain, worldStateArchive, contextSchedule, new BadBlockManager()); + MigratingProtocolContext.init( + blockchain, worldStateArchive, null, consensusContextFactory, new BadBlockManager()); assertThat(migratingProtocolContext.getConsensusContext(ConsensusContext.class)) .isSameAs(context1); diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCoinbaseValidationRuleTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCoinbaseValidationRuleTest.java index 791edaf636d..a34ad401da8 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCoinbaseValidationRuleTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCoinbaseValidationRuleTest.java @@ -51,8 +51,12 @@ public void proposerInValidatorListPassesValidation() { final List
validators = Lists.newArrayList(proposerAddress); final ProtocolContext context = - new ProtocolContext( - null, null, setupContextWithValidators(validators), new BadBlockManager()); + ProtocolContext.create( + null, + null, + null, + (pc, ps) -> setupContextWithValidators(validators), + new BadBlockManager()); final BftCoinbaseValidationRule coinbaseValidationRule = new BftCoinbaseValidationRule(); @@ -72,8 +76,12 @@ public void proposerNotInValidatorListFailsValidation() { final List
validators = Lists.newArrayList(otherValidatorNodeAddress); final ProtocolContext context = - new ProtocolContext( - null, null, setupContextWithValidators(validators), new BadBlockManager()); + ProtocolContext.create( + null, + null, + null, + (pc, ps) -> setupContextWithValidators(validators), + new BadBlockManager()); final BftCoinbaseValidationRule coinbaseValidationRule = new BftCoinbaseValidationRule(); diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCommitSealsValidationRuleTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCommitSealsValidationRuleTest.java index 84d59397bcd..e1ecf10c4c6 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCommitSealsValidationRuleTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCommitSealsValidationRuleTest.java @@ -59,7 +59,7 @@ public void correctlyConstructedHeaderPassesValidation() { final BftContext bftContext = setupContextWithValidators(committerAddresses); final ProtocolContext context = - new ProtocolContext(null, null, bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())).thenReturn(committerAddresses); assertThat(commitSealsValidationRule.validate(blockHeader, null, context)).isTrue(); @@ -74,7 +74,7 @@ public void insufficientCommitSealsFailsValidation() { final List
validators = singletonList(committerAddress); final BftContext bftContext = setupContextWithValidators(validators); final ProtocolContext context = - new ProtocolContext(null, null, bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())).thenReturn(emptyList()); assertThat(commitSealsValidationRule.validate(blockHeader, null, context)).isFalse(); @@ -92,7 +92,7 @@ public void committerNotInValidatorListFailsValidation() { final BftContext bftContext = setupContextWithValidators(validators); final ProtocolContext context = - new ProtocolContext(null, null, bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())) .thenReturn(singletonList(Util.publicKeyToAddress(nonValidatorNodeKey.getPublicKey()))); @@ -140,7 +140,7 @@ public void headerContainsDuplicateSealsFailsValidation() { final BftContext bftContext = setupContextWithValidators(validators); final ProtocolContext context = - new ProtocolContext(null, null, bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())) .thenReturn(List.of(committerAddress, committerAddress)); @@ -160,7 +160,7 @@ private boolean subExecution(final int validatorCount, final int committerCount) final BftContext bftContext = setupContextWithValidators(validators); final ProtocolContext context = - new ProtocolContext(null, null, bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())) .thenReturn(validators.subList(0, committerCount)); diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftValidatorsValidationRuleTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftValidatorsValidationRuleTest.java index 8ffd5633456..f9380fc38c0 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftValidatorsValidationRuleTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftValidatorsValidationRuleTest.java @@ -45,10 +45,11 @@ public void correctlyConstructedHeaderPassesValidation() { AddressHelpers.ofValue(1), AddressHelpers.ofValue(2), AddressHelpers.ofValue(3)); final ProtocolContext context = - new ProtocolContext( + ProtocolContext.create( null, null, - setupContextWithBftExtraData(validators, bftExtraData), + null, + (pc, ps) -> setupContextWithBftExtraData(validators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(validators); @@ -63,10 +64,11 @@ public void validatorsInNonAscendingOrderFailValidation() { AddressHelpers.ofValue(1), AddressHelpers.ofValue(2), AddressHelpers.ofValue(3)); final ProtocolContext context = - new ProtocolContext( + ProtocolContext.create( + null, null, null, - setupContextWithBftExtraData(validators, bftExtraData), + (pc, ps) -> setupContextWithBftExtraData(validators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(Lists.reverse(validators)); @@ -84,10 +86,11 @@ public void mismatchingReportedValidatorsVsLocallyStoredListFailsValidation() { AddressHelpers.ofValue(2), AddressHelpers.ofValue(3), AddressHelpers.ofValue(4)); final ProtocolContext context = - new ProtocolContext( + ProtocolContext.create( + null, null, null, - setupContextWithBftExtraData(storedValidators, bftExtraData), + (pc, ps) -> setupContextWithBftExtraData(storedValidators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(Lists.reverse(reportedValidators)); diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftVanityDataValidationRuleTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftVanityDataValidationRuleTest.java index 39f296a9937..06c05fcebcd 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftVanityDataValidationRuleTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftVanityDataValidationRuleTest.java @@ -45,10 +45,11 @@ public boolean headerWithVanityDataOfSize(final int extraDataSize) { new BftExtraData(Bytes.wrap(new byte[extraDataSize]), emptyList(), empty(), 0, emptyList()); final ProtocolContext context = - new ProtocolContext( + ProtocolContext.create( null, null, - setupContextWithBftExtraData(emptyList(), extraData), + null, + (pc, ps) -> setupContextWithBftExtraData(emptyList(), extraData), new BadBlockManager()); return validationRule.validate(blockHeader, null, context); } 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 8896733548d..4264e78b7a7 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 @@ -350,10 +350,11 @@ private static ControllerAndState createControllerAndFinalState( blockChain, epochManager, blockInterface); final ProtocolContext protocolContext = - new ProtocolContext( + ProtocolContext.create( blockChain, worldStateArchive, - new BftContext(validatorProvider, epochManager, blockInterface), + null, + (pc, ps) -> new BftContext(validatorProvider, epochManager, blockInterface), new BadBlockManager()); final TransactionPoolConfiguration poolConf = ImmutableTransactionPoolConfiguration.builder().txPoolMaxSize(1).build(); diff --git a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/tests/round/IbftRoundIntegrationTest.java b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/tests/round/IbftRoundIntegrationTest.java index 6a2199f7138..7b180b99cbe 100644 --- a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/tests/round/IbftRoundIntegrationTest.java +++ b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/tests/round/IbftRoundIntegrationTest.java @@ -124,10 +124,11 @@ public void setup() { when(blockImporter.importBlock(any(), any(), any())).thenReturn(new BlockImportResult(true)); protocolContext = - new ProtocolContext( + ProtocolContext.create( blockChain, worldStateArchive, - setupContextWithBftExtraDataEncoder(emptyList(), bftExtraDataEncoder), + null, + (pc, ps) -> setupContextWithBftExtraDataEncoder(emptyList(), bftExtraDataEncoder), new BadBlockManager()); } diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactoryTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactoryTest.java index 160fc2a2f39..9c6a6eb6f2b 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactoryTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactoryTest.java @@ -49,10 +49,11 @@ public class IbftBlockHeaderValidationRulesetFactoryTest { private ProtocolContext protocolContext(final Collection
validators) { - return new ProtocolContext( + return ProtocolContext.create( null, null, - setupContextWithBftExtraDataEncoder(validators, new IbftExtraDataCodec()), + null, + (pc, ps) -> setupContextWithBftExtraDataEncoder(validators, new IbftExtraDataCodec()), new BadBlockManager()); } diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftProtocolScheduleTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftProtocolScheduleTest.java index e5551ff3f31..762a8f13bcf 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftProtocolScheduleTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftProtocolScheduleTest.java @@ -123,10 +123,12 @@ private boolean validateHeader( } private ProtocolContext protocolContext(final Collection
validators) { - return new ProtocolContext( + return ProtocolContext.create( null, null, - setupContextWithBftExtraDataEncoder(BftContext.class, validators, bftExtraDataCodec), + null, + (pc, ps) -> + setupContextWithBftExtraDataEncoder(BftContext.class, validators, bftExtraDataCodec), new BadBlockManager()); } } 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 5469717b13f..40c239ccb31 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 @@ -127,10 +127,12 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( false, new NoOpMetricsSystem()); final ProtocolContext protContext = - new ProtocolContext( + ProtocolContext.create( blockchain, createInMemoryWorldStateArchive(), - setupContextWithBftExtraDataEncoder(initialValidatorList, bftExtraDataEncoder), + null, + (pc, ps) -> + setupContextWithBftExtraDataEncoder(initialValidatorList, bftExtraDataEncoder), new BadBlockManager()); final TransactionPoolConfiguration poolConf = diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftBlockHeightManagerTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftBlockHeightManagerTest.java index b9f57debb6b..2f914d1a5ec 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftBlockHeightManagerTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftBlockHeightManagerTest.java @@ -174,8 +174,12 @@ public void setup() { .thenReturn(messageValidator); protocolContext = - new ProtocolContext( - blockchain, null, setupContextWithValidators(validators), new BadBlockManager()); + ProtocolContext.create( + blockchain, + null, + null, + (pc, ps) -> setupContextWithValidators(validators), + new BadBlockManager()); final ProtocolScheduleBuilder protocolScheduleBuilder = new ProtocolScheduleBuilder( diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftRoundTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftRoundTest.java index f4ee852a04f..68bd4dc23e7 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftRoundTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftRoundTest.java @@ -112,10 +112,11 @@ public class IbftRoundTest { @BeforeEach public void setup() { protocolContext = - new ProtocolContext( + ProtocolContext.create( blockChain, worldStateArchive, - setupContextWithBftExtraDataEncoder(emptyList(), new IbftExtraDataCodec()), + protocolSchedule, + (pc, ps) -> setupContextWithBftExtraDataEncoder(emptyList(), new IbftExtraDataCodec()), new BadBlockManager()); lenient().when(messageValidator.validateProposal(any())).thenReturn(true); diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/validation/MessageValidatorTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/validation/MessageValidatorTest.java index 2352642b87b..3ad090c58aa 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/validation/MessageValidatorTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/validation/MessageValidatorTest.java @@ -101,10 +101,11 @@ public void setup() { lenient().when(mockBftCtx.as(Mockito.any())).thenReturn(mockBftCtx); protocolContext = - new ProtocolContext( + ProtocolContext.create( mock(MutableBlockchain.class), mock(WorldStateArchive.class), - mockBftCtx, + protocolSchedule, + (pc, ps) -> mockBftCtx, new BadBlockManager()); lenient() diff --git a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/MergeProtocolSchedule.java b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/MergeProtocolSchedule.java index abbc3b130aa..169af3468b7 100644 --- a/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/MergeProtocolSchedule.java +++ b/consensus/merge/src/main/java/org/hyperledger/besu/consensus/merge/MergeProtocolSchedule.java @@ -129,7 +129,7 @@ private static ProtocolSpecBuilder applyParisSpecificModifications( gasCalculator, chainId.orElse(BigInteger.ZERO), EvmConfiguration.DEFAULT)) .blockHeaderValidatorBuilder(MergeProtocolSchedule::getBlockHeaderValidator) .blockReward(Wei.ZERO) - .difficultyCalculator((a, b, c) -> BigInteger.ZERO) + .difficultyCalculator((a, b) -> BigInteger.ZERO) .skipZeroBlockRewards(true) .isPoS(true) .name("Paris"); diff --git a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/MergeProtocolScheduleTest.java b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/MergeProtocolScheduleTest.java index 0d4aede3a14..b9e82192af7 100644 --- a/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/MergeProtocolScheduleTest.java +++ b/consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/MergeProtocolScheduleTest.java @@ -193,8 +193,7 @@ public void parametersAlignWithMainnetWithAdjustments() { private static void assertProofOfStakeConfigIsEnabled(final ProtocolSpec spec) { assertThat(spec.isPoS()).isTrue(); assertThat(spec.getEvm().getOperationsUnsafe()[0x44]).isInstanceOf(PrevRanDaoOperation.class); - assertThat(spec.getDifficultyCalculator().nextDifficulty(-1, null, null)) - .isEqualTo(BigInteger.ZERO); + assertThat(spec.getDifficultyCalculator().nextDifficulty(-1, null)).isEqualTo(BigInteger.ZERO); assertThat(spec.getBlockReward()).isEqualTo(Wei.ZERO); assertThat(spec.isSkipZeroBlockRewards()).isTrue(); assertThat(spec.getBlockProcessor()).isInstanceOf(MainnetBlockProcessor.class); 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 09c1b28af40..937d543f701 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 @@ -188,7 +188,12 @@ public void setUp() { .thenReturn(genesisState.getBlock().getHeader().getDifficulty().plus(1L)); protocolContext = - new ProtocolContext(blockchain, worldStateArchive, mergeContext, badBlockManager); + ProtocolContext.create( + blockchain, + worldStateArchive, + protocolSchedule, + (pc, ps) -> mergeContext, + badBlockManager); var mutable = worldStateArchive.getMutable(); genesisState.writeStateTo(mutable); mutable.persist(null); 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 7b111268e0f..f9b1431a8d4 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 @@ -76,7 +76,12 @@ public class MergeReorgTest implements MergeGenesisConfigHelper { private final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); private final EthScheduler ethScheduler = new DeterministicEthScheduler(); private final ProtocolContext protocolContext = - new ProtocolContext(blockchain, worldStateArchive, mergeContext, new BadBlockManager()); + ProtocolContext.create( + blockchain, + worldStateArchive, + mockProtocolSchedule, + (pc, ps) -> mergeContext, + new BadBlockManager()); private final Address coinbase = genesisAllocations(getPowGenesisConfigFile()).findFirst().get(); private final BlockHeaderTestFixture headerGenerator = new BlockHeaderTestFixture(); 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 d90d5a15277..762aad41a58 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 @@ -445,7 +445,7 @@ private static ControllerAndState createControllerAndFinalState( final BftValidatorOverrides validatorOverrides = convertBftForks(qbftForks); final TransactionSimulator transactionSimulator = - new TransactionSimulator(blockChain, worldStateArchive, protocolSchedule, 0L); + new TransactionSimulator(blockChain, worldStateArchive, protocolSchedule, miningParams, 0L); final BlockValidatorProvider blockValidatorProvider = BlockValidatorProvider.forkingValidatorProvider( @@ -458,10 +458,11 @@ private static ControllerAndState createControllerAndFinalState( blockChain, forksSchedule, blockValidatorProvider, transactionValidatorProvider); final ProtocolContext protocolContext = - new ProtocolContext( + ProtocolContext.create( blockChain, worldStateArchive, - new BftContext(validatorProvider, epochManager, blockInterface), + null, + (pc, ps) -> new BftContext(validatorProvider, epochManager, blockInterface), new BadBlockManager()); final TransactionPoolConfiguration poolConf = diff --git a/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/test/round/QbftRoundIntegrationTest.java b/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/test/round/QbftRoundIntegrationTest.java index 7dcca442a7f..eb6a260014e 100644 --- a/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/test/round/QbftRoundIntegrationTest.java +++ b/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/test/round/QbftRoundIntegrationTest.java @@ -126,11 +126,13 @@ public void setup() { when(blockImporter.importBlock(any(), any(), any())).thenReturn(new BlockImportResult(true)); protocolContext = - new ProtocolContext( + ProtocolContext.create( blockChain, worldStateArchive, - setupContextWithBftExtraDataEncoder( - BftContext.class, emptyList(), qbftExtraDataEncoder), + null, + (pc, ps) -> + setupContextWithBftExtraDataEncoder( + BftContext.class, emptyList(), qbftExtraDataEncoder), new BadBlockManager()); } diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftBlockHeaderValidationRulesetFactoryTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftBlockHeaderValidationRulesetFactoryTest.java index ae1fbc0f19b..278733896fa 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftBlockHeaderValidationRulesetFactoryTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftBlockHeaderValidationRulesetFactoryTest.java @@ -44,10 +44,13 @@ public class QbftBlockHeaderValidationRulesetFactoryTest { private ProtocolContext protocolContext(final Collection
validators) { - return new ProtocolContext( + return ProtocolContext.create( null, null, - setupContextWithBftExtraDataEncoder(BftContext.class, validators, new QbftExtraDataCodec()), + null, + (pc, ps) -> + setupContextWithBftExtraDataEncoder( + BftContext.class, validators, new QbftExtraDataCodec()), new BadBlockManager()); } diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftProtocolScheduleTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftProtocolScheduleTest.java index 020d6e0e5ae..e3e41d79e89 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftProtocolScheduleTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftProtocolScheduleTest.java @@ -57,10 +57,13 @@ public class QbftProtocolScheduleTest { private final List
validators = singletonList(proposerAddress); private ProtocolContext protocolContext(final Collection
validators) { - return new ProtocolContext( + return ProtocolContext.create( null, null, - setupContextWithBftExtraDataEncoder(BftContext.class, validators, new QbftExtraDataCodec()), + null, + (pc, ps) -> + setupContextWithBftExtraDataEncoder( + BftContext.class, validators, new QbftExtraDataCodec()), new BadBlockManager()); } diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/headervalidationrules/QbftValidatorsValidationRuleTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/headervalidationrules/QbftValidatorsValidationRuleTest.java index 28ec8fc3a33..ead37f40092 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/headervalidationrules/QbftValidatorsValidationRuleTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/headervalidationrules/QbftValidatorsValidationRuleTest.java @@ -44,10 +44,13 @@ public void validationPassesIfValidatorsAndVoteAreEmpty() { final QbftValidatorsValidationRule qbftValidatorsValidationRule = new QbftValidatorsValidationRule(true); final ProtocolContext context = - new ProtocolContext( + ProtocolContext.create( null, null, - setupContextWithBftExtraData(BftContext.class, Collections.emptyList(), bftExtraData), + null, + (pc, ps) -> + setupContextWithBftExtraData( + BftContext.class, Collections.emptyList(), bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(Collections.emptyList()); when(bftExtraData.getVote()).thenReturn(Optional.empty()); @@ -63,10 +66,11 @@ public void validationIsDelegatedWhenConstructorFlagIsFalse() { AddressHelpers.ofValue(1), AddressHelpers.ofValue(2), AddressHelpers.ofValue(3)); final ProtocolContext context = - new ProtocolContext( + ProtocolContext.create( + null, null, null, - setupContextWithBftExtraData(BftContext.class, validators, bftExtraData), + (pc, ps) -> setupContextWithBftExtraData(BftContext.class, validators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(validators); assertThat(qbftValidatorsValidationRule.validate(blockHeader, null, context)).isTrue(); @@ -81,10 +85,11 @@ public void validationFailsIfValidatorsAreNotEmpty() { AddressHelpers.ofValue(1), AddressHelpers.ofValue(2), AddressHelpers.ofValue(3)); final ProtocolContext context = - new ProtocolContext( + ProtocolContext.create( null, null, - setupContextWithBftExtraData(BftContext.class, validators, bftExtraData), + null, + (pc, ps) -> setupContextWithBftExtraData(BftContext.class, validators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(validators); assertThat(qbftValidatorsValidationRule.validate(blockHeader, null, context)).isFalse(); @@ -95,10 +100,13 @@ public void validationFailsIfVoteIsPresent() { final QbftValidatorsValidationRule qbftValidatorsValidationRule = new QbftValidatorsValidationRule(true); final ProtocolContext context = - new ProtocolContext( + ProtocolContext.create( + null, null, null, - setupContextWithBftExtraData(BftContext.class, Collections.emptyList(), bftExtraData), + (pc, ps) -> + setupContextWithBftExtraData( + BftContext.class, Collections.emptyList(), bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(Collections.emptyList()); when(bftExtraData.getVote()).thenReturn(Optional.of(mock(Vote.class))); diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftBlockHeightManagerTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftBlockHeightManagerTest.java index 190c87e020f..0cdb4ac2838 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftBlockHeightManagerTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftBlockHeightManagerTest.java @@ -172,11 +172,13 @@ public void setup() { when(messageValidatorFactory.createMessageValidator(any(), any())).thenReturn(messageValidator); protocolContext = - new ProtocolContext( + ProtocolContext.create( blockchain, null, - setupContextWithBftExtraDataEncoder( - BftContext.class, validators, new QbftExtraDataCodec()), + null, + (pc, ps) -> + setupContextWithBftExtraDataEncoder( + BftContext.class, validators, new QbftExtraDataCodec()), new BadBlockManager()); final ProtocolScheduleBuilder protocolScheduleBuilder = diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftRoundTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftRoundTest.java index fb84c1c38fa..551e886d2a9 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftRoundTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftRoundTest.java @@ -118,11 +118,13 @@ public class QbftRoundTest { @BeforeEach public void setup() { protocolContext = - new ProtocolContext( + ProtocolContext.create( blockChain, worldStateArchive, - setupContextWithBftExtraDataEncoder( - BftContext.class, emptyList(), new QbftExtraDataCodec()), + protocolSchedule, + (pc, ps) -> + setupContextWithBftExtraDataEncoder( + BftContext.class, emptyList(), new QbftExtraDataCodec()), new BadBlockManager()); when(messageValidator.validateProposal(any())).thenReturn(true); diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalPayloadValidatorTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalPayloadValidatorTest.java index 09e9455d89e..e1913540c80 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalPayloadValidatorTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalPayloadValidatorTest.java @@ -71,10 +71,13 @@ public class ProposalPayloadValidatorTest { @BeforeEach public void setup() { protocolContext = - new ProtocolContext( + ProtocolContext.create( blockChain, worldStateArchive, - setupContextWithBftExtraDataEncoder(BftContext.class, emptyList(), bftExtraDataCodec), + null, + (pc, ps) -> + setupContextWithBftExtraDataEncoder( + BftContext.class, emptyList(), bftExtraDataCodec), new BadBlockManager()); } diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalValidatorTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalValidatorTest.java index 43afff35018..8712ef62ef1 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalValidatorTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalValidatorTest.java @@ -99,10 +99,13 @@ public RoundSpecificItems( @BeforeEach public void setup() { protocolContext = - new ProtocolContext( + ProtocolContext.create( blockChain, worldStateArchive, - setupContextWithBftExtraDataEncoder(BftContext.class, emptyList(), bftExtraDataEncoder), + protocolSchedule, + (pc, ps) -> + setupContextWithBftExtraDataEncoder( + BftContext.class, emptyList(), bftExtraDataEncoder), new BadBlockManager()); // typically tests require the blockValidation to be successful diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/RoundChangeMessageValidatorTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/RoundChangeMessageValidatorTest.java index 82e8fb5c7a8..a2ae67c3c14 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/RoundChangeMessageValidatorTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/RoundChangeMessageValidatorTest.java @@ -81,10 +81,13 @@ public class RoundChangeMessageValidatorTest { @BeforeEach public void setup() { protocolContext = - new ProtocolContext( + ProtocolContext.create( blockChain, worldStateArchive, - setupContextWithBftExtraDataEncoder(BftContext.class, emptyList(), bftExtraDataEncoder), + protocolSchedule, + (pc, ps) -> + setupContextWithBftExtraDataEncoder( + BftContext.class, emptyList(), bftExtraDataEncoder), new BadBlockManager()); lenient().when(protocolSchedule.getByBlockHeader(any())).thenReturn(protocolSpec); 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 c7ba5a4f934..16bc63d6328 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 @@ -44,6 +44,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.metrics.ObservableMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; @@ -76,13 +77,16 @@ public class JsonRpcTestMethodsFactory { private final BlockchainQueries blockchainQueries; private final Synchronizer synchronizer; private final ProtocolSchedule protocolSchedule; + private final TransactionSimulator transactionSimulator; public JsonRpcTestMethodsFactory(final BlockchainImporter importer) { this.importer = importer; this.blockchain = createInMemoryBlockchain(importer.getGenesisBlock()); this.stateArchive = createInMemoryWorldStateArchive(); this.importer.getGenesisState().writeStateTo(stateArchive.getMutable()); - this.context = new ProtocolContext(blockchain, stateArchive, null, new BadBlockManager()); + this.context = + ProtocolContext.create( + blockchain, stateArchive, null, (pc, ps) -> null, new BadBlockManager()); this.protocolSchedule = importer.getProtocolSchedule(); this.synchronizer = mock(Synchronizer.class); @@ -92,9 +96,12 @@ public JsonRpcTestMethodsFactory(final BlockchainImporter importer) { final BlockImporter blockImporter = protocolSpec.getBlockImporter(); blockImporter.importBlock(context, block, HeaderValidationMode.FULL); } + final var miningParameters = MiningParameters.newDefault(); this.blockchainQueries = - new BlockchainQueries( - protocolSchedule, blockchain, stateArchive, MiningParameters.newDefault()); + new BlockchainQueries(protocolSchedule, blockchain, stateArchive, miningParameters); + + this.transactionSimulator = + new TransactionSimulator(blockchain, stateArchive, protocolSchedule, miningParameters, 0L); } public JsonRpcTestMethodsFactory( @@ -107,13 +114,13 @@ public JsonRpcTestMethodsFactory( this.stateArchive = stateArchive; this.context = context; this.protocolSchedule = importer.getProtocolSchedule(); + final var miningParameters = MiningParameters.newDefault(); this.blockchainQueries = new BlockchainQueries( - importer.getProtocolSchedule(), - blockchain, - stateArchive, - MiningParameters.newDefault()); + importer.getProtocolSchedule(), blockchain, stateArchive, miningParameters); this.synchronizer = mock(Synchronizer.class); + this.transactionSimulator = + new TransactionSimulator(blockchain, stateArchive, protocolSchedule, miningParameters, 0L); } public JsonRpcTestMethodsFactory( @@ -128,12 +135,12 @@ public JsonRpcTestMethodsFactory( this.context = context; this.synchronizer = synchronizer; this.protocolSchedule = importer.getProtocolSchedule(); + final var miningParameters = MiningParameters.newDefault(); this.blockchainQueries = new BlockchainQueries( - importer.getProtocolSchedule(), - blockchain, - stateArchive, - MiningParameters.newDefault()); + importer.getProtocolSchedule(), blockchain, stateArchive, miningParameters); + this.transactionSimulator = + new TransactionSimulator(blockchain, stateArchive, protocolSchedule, miningParameters, 0L); } public BlockchainQueries getBlockchainQueries() { @@ -216,6 +223,7 @@ public Map methods() { ethPeers, Vertx.vertx(new VertxOptions().setWorkerPoolSize(1)), ImmutableApiConfiguration.builder().build(), - Optional.empty()); + Optional.empty(), + transactionSimulator); } } diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthGetBlockByNumberLatestDesyncIntegrationTest.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthGetBlockByNumberLatestDesyncIntegrationTest.java index 088eff85007..29949468f52 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthGetBlockByNumberLatestDesyncIntegrationTest.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthGetBlockByNumberLatestDesyncIntegrationTest.java @@ -67,7 +67,8 @@ public static void setUpOnce() throws Exception { InMemoryKeyValueStorageProvider.createInMemoryBlockchain(importer.getGenesisBlock()); WorldStateArchive state = InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive(); importer.getGenesisState().writeStateTo(state.getMutable()); - ProtocolContext context = new ProtocolContext(chain, state, null, new BadBlockManager()); + ProtocolContext context = + ProtocolContext.create(chain, state, null, (pc, ps) -> null, new BadBlockManager()); for (final Block block : importer.getBlocks()) { final ProtocolSchedule protocolSchedule = importer.getProtocolSchedule(); diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/GraphQLContextType.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/GraphQLContextType.java index c12f7578c6c..fd05165968a 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/GraphQLContextType.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/GraphQLContextType.java @@ -42,5 +42,8 @@ public enum GraphQLContextType { CHAIN_ID, /** Represents gas cap context. */ - GAS_CAP + GAS_CAP, + + /** Represents the transaction simulator. */ + TRANSACTION_SIMULATOR } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/BlockAdapterBase.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/BlockAdapterBase.java index 6d5b696353a..ea76fddd5ee 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/BlockAdapterBase.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/BlockAdapterBase.java @@ -334,8 +334,7 @@ private Optional executeCall(final DataFetchingEnvironment environme final long bn = header.getNumber(); final long gasCap = environment.getGraphQlContext().get(GraphQLContextType.GAS_CAP); final TransactionSimulator transactionSimulator = - new TransactionSimulator( - query.getBlockchain(), query.getWorldStateArchive(), protocolSchedule, gasCap); + environment.getGraphQlContext().get(GraphQLContextType.TRANSACTION_SIMULATOR); long gasParam = -1; Wei gasPriceParam = null; diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/PendingStateAdapter.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/PendingStateAdapter.java index 49f6bc890f9..7474496bdd8 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/PendingStateAdapter.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/PendingStateAdapter.java @@ -147,8 +147,7 @@ public Optional getCall(final DataFetchingEnvironment environment) { environment.getGraphQlContext().get(GraphQLContextType.PROTOCOL_SCHEDULE); final long gasCap = environment.getGraphQlContext().get(GraphQLContextType.GAS_CAP); final TransactionSimulator transactionSimulator = - new TransactionSimulator( - query.getBlockchain(), query.getWorldStateArchive(), protocolSchedule, gasCap); + environment.getGraphQlContext().get(GraphQLContextType.TRANSACTION_SIMULATOR); long gasParam = -1; Wei gasPriceParam = null; diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractEstimateGas.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractEstimateGas.java index 8e826caf9e4..1716b8a3c1d 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractEstimateGas.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractEstimateGas.java @@ -28,6 +28,8 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.core.BlockHeader; +import org.hyperledger.besu.ethereum.mainnet.ImmutableTransactionValidationParams; +import org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams; import org.hyperledger.besu.ethereum.mainnet.ValidationResult; import org.hyperledger.besu.ethereum.processing.TransactionProcessingResult; import org.hyperledger.besu.ethereum.transaction.CallParameter; @@ -35,10 +37,16 @@ import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.ethereum.transaction.TransactionSimulatorResult; import org.hyperledger.besu.evm.tracing.EstimateGasOperationTracer; +import org.hyperledger.besu.evm.tracing.OperationTracer; import java.util.Optional; public abstract class AbstractEstimateGas extends AbstractBlockParameterMethod { + protected static final TransactionValidationParams ALLOW_EXCEEDING_BALANCE_VALIDATION_PARAMETERS = + ImmutableTransactionValidationParams.builder() + .from(TransactionValidationParams.transactionSimulator()) + .isAllowExceedingBalance(true) + .build(); private static final double SUB_CALL_REMAINING_GAS_RATIO = 65D / 64D; @@ -60,7 +68,48 @@ protected BlockParameter blockParameter(final JsonRpcRequestContext request) { } } - protected Optional blockHeader(final long blockNumber) { + protected abstract Object simulate( + final JsonRpcRequestContext requestContext, + final CallParameter callParams, + final long gasLimit, + final TransactionSimulationFunction simulationFunction); + + @Override + protected Object pendingResult(final JsonRpcRequestContext requestContext) { + final JsonCallParameter jsonCallParameter = validateAndGetCallParams(requestContext); + final var validationParams = getTransactionValidationParams(jsonCallParameter); + final var pendingBlockHeader = transactionSimulator.simulatePendingBlockHeader(); + final TransactionSimulationFunction simulationFunction = + (cp, op) -> + transactionSimulator.processOnPending(cp, validationParams, op, pendingBlockHeader); + return simulate( + requestContext, jsonCallParameter, pendingBlockHeader.getGasLimit(), simulationFunction); + } + + @Override + protected Object resultByBlockNumber( + final JsonRpcRequestContext requestContext, final long blockNumber) { + final JsonCallParameter jsonCallParameter = validateAndGetCallParams(requestContext); + final Optional maybeBlockHeader = blockHeader(blockNumber); + final Optional jsonRpcError = validateBlockHeader(maybeBlockHeader); + if (jsonRpcError.isPresent()) { + return errorResponse(requestContext, jsonRpcError.get()); + } + return resultByBlockHeader(requestContext, jsonCallParameter, maybeBlockHeader.get()); + } + + private Object resultByBlockHeader( + final JsonRpcRequestContext requestContext, + final JsonCallParameter jsonCallParameter, + final BlockHeader blockHeader) { + final var validationParams = getTransactionValidationParams(jsonCallParameter); + final TransactionSimulationFunction simulationFunction = + (cp, op) -> transactionSimulator.processOnPending(cp, validationParams, op, blockHeader); + return simulate( + requestContext, jsonCallParameter, blockHeader.getGasLimit(), simulationFunction); + } + + private Optional blockHeader(final long blockNumber) { if (getBlockchainQueries().headBlockNumber() == blockNumber) { // chain head header if cached, and we can return it form memory return Optional.of(getBlockchainQueries().getBlockchain().getChainHeadHeader()); @@ -68,8 +117,7 @@ protected Optional blockHeader(final long blockNumber) { return getBlockchainQueries().getBlockHeaderByNumber(blockNumber); } - protected Optional validateBlockHeader( - final Optional maybeBlockHeader) { + private Optional validateBlockHeader(final Optional maybeBlockHeader) { if (maybeBlockHeader.isEmpty()) { return Optional.of(RpcErrorType.BLOCK_NOT_FOUND); } @@ -83,25 +131,7 @@ protected Optional validateBlockHeader( return Optional.empty(); } - @Override - protected Object resultByBlockNumber( - final JsonRpcRequestContext requestContext, final long blockNumber) { - final JsonCallParameter jsonCallParameter = validateAndGetCallParams(requestContext); - final Optional maybeBlockHeader = blockHeader(blockNumber); - final Optional jsonRpcError = validateBlockHeader(maybeBlockHeader); - if (jsonRpcError.isPresent()) { - return errorResponse(requestContext, jsonRpcError.get()); - } - return resultByBlockHeader(requestContext, jsonCallParameter, maybeBlockHeader.get()); - } - - protected abstract Object resultByBlockHeader( - final JsonRpcRequestContext requestContext, - final JsonCallParameter jsonCallParameter, - final BlockHeader blockHeader); - - protected CallParameter overrideGasLimitAndPrice( - final JsonCallParameter callParams, final long gasLimit) { + protected CallParameter overrideGasLimit(final CallParameter callParams, final long gasLimit) { return new CallParameter( callParams.getChainId(), callParams.getFrom(), @@ -142,7 +172,7 @@ protected JsonRpcErrorResponse errorResponse( final ValidationResult validationResult = result.getValidationResult(); if (validationResult != null && !validationResult.isValid()) { - if (validationResult.getErrorMessage().length() > 0) { + if (!validationResult.getErrorMessage().isEmpty()) { return errorResponse(request, JsonRpcError.from(validationResult)); } return errorResponse( @@ -170,4 +200,19 @@ protected JsonRpcErrorResponse errorResponse( final JsonRpcRequestContext request, final JsonRpcError jsonRpcError) { return new JsonRpcErrorResponse(request.getRequest().getId(), jsonRpcError); } + + protected static TransactionValidationParams getTransactionValidationParams( + final JsonCallParameter callParams) { + final boolean isAllowExceedingBalance = !callParams.isMaybeStrict().orElse(Boolean.FALSE); + + if (isAllowExceedingBalance) { + return ALLOW_EXCEEDING_BALANCE_VALIDATION_PARAMETERS; + } + return TransactionValidationParams.transactionSimulator(); + } + + protected interface TransactionSimulationFunction { + Optional simulate( + final CallParameter callParams, final OperationTracer operationTracer); + } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessList.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessList.java index 2b8e79a81e9..b4870b555ec 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessList.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessList.java @@ -18,13 +18,9 @@ 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.parameters.JsonCallParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.CreateAccessListResult; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; -import org.hyperledger.besu.ethereum.core.BlockHeader; -import org.hyperledger.besu.ethereum.mainnet.ImmutableTransactionValidationParams; -import org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams; import org.hyperledger.besu.ethereum.transaction.CallParameter; import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.ethereum.transaction.TransactionSimulatorResult; @@ -48,20 +44,24 @@ public String getName() { } @Override - protected Object resultByBlockHeader( + protected Object simulate( final JsonRpcRequestContext requestContext, - final JsonCallParameter jsonCallParameter, - final BlockHeader blockHeader) { - final AccessListSimulatorResult maybeResult = - processTransaction(jsonCallParameter, blockHeader); + final CallParameter callParams, + final long gasLimit, + final TransactionSimulationFunction simulationFunction) { + + final AccessListOperationTracer tracer = AccessListOperationTracer.create(); + final Optional firstResult = + simulationFunction.simulate(callParams, tracer); + // if the call accessList is different from the simulation result, calculate gas and return - if (shouldProcessWithAccessListOverride(jsonCallParameter, maybeResult.tracer())) { + if (shouldProcessWithAccessListOverride(callParams, tracer)) { final AccessListSimulatorResult result = processTransactionWithAccessListOverride( - jsonCallParameter, blockHeader, maybeResult.tracer().getAccessList()); + callParams, gasLimit, tracer.getAccessList(), simulationFunction); return createResponse(requestContext, result); } else { - return createResponse(requestContext, maybeResult); + return createResponse(requestContext, new AccessListSimulatorResult(firstResult, tracer)); } } @@ -73,16 +73,8 @@ private Object createResponse( .orElseGet(() -> errorResponse(requestContext, RpcErrorType.INTERNAL_ERROR)); } - private TransactionValidationParams transactionValidationParams( - final boolean isAllowExceedingBalance) { - return ImmutableTransactionValidationParams.builder() - .from(TransactionValidationParams.transactionSimulator()) - .isAllowExceedingBalance(isAllowExceedingBalance) - .build(); - } - private boolean shouldProcessWithAccessListOverride( - final JsonCallParameter parameters, final AccessListOperationTracer tracer) { + final CallParameter parameters, final AccessListOperationTracer tracer) { // if empty, transaction did not access any storage, does not need to reprocess if (tracer.getAccessList().isEmpty()) { @@ -107,39 +99,23 @@ private Function createResponse( : errorResponse(request, result); } - private AccessListSimulatorResult processTransaction( - final JsonCallParameter jsonCallParameter, final BlockHeader blockHeader) { - final TransactionValidationParams transactionValidationParams = - transactionValidationParams(!jsonCallParameter.isMaybeStrict().orElse(Boolean.FALSE)); - - final CallParameter callParams = - overrideGasLimitAndPrice(jsonCallParameter, blockHeader.getGasLimit()); - - final AccessListOperationTracer tracer = AccessListOperationTracer.create(); - final Optional result = - transactionSimulator.process(callParams, transactionValidationParams, tracer, blockHeader); - return new AccessListSimulatorResult(result, tracer); - } - private AccessListSimulatorResult processTransactionWithAccessListOverride( - final JsonCallParameter jsonCallParameter, - final BlockHeader blockHeader, - final List accessList) { - final TransactionValidationParams transactionValidationParams = - transactionValidationParams(!jsonCallParameter.isMaybeStrict().orElse(Boolean.FALSE)); + final CallParameter callParameter, + final long gasLimit, + final List accessList, + final TransactionSimulationFunction simulationFunction) { final AccessListOperationTracer tracer = AccessListOperationTracer.create(); - final CallParameter callParameter = - overrideAccessList(jsonCallParameter, blockHeader.getGasLimit(), accessList); + final CallParameter modifiedCallParameter = + overrideAccessList(callParameter, gasLimit, accessList); final Optional result = - transactionSimulator.process( - callParameter, transactionValidationParams, tracer, blockHeader); + simulationFunction.simulate(modifiedCallParameter, tracer); return new AccessListSimulatorResult(result, tracer); } - protected CallParameter overrideAccessList( - final JsonCallParameter callParams, + private CallParameter overrideAccessList( + final CallParameter callParams, final long gasLimit, final List accessListEntries) { return new CallParameter( @@ -151,7 +127,7 @@ protected CallParameter overrideAccessList( callParams.getMaxFeePerGas(), callParams.getValue(), callParams.getPayload(), - Optional.ofNullable(accessListEntries)); + Optional.of(accessListEntries)); } private record AccessListSimulatorResult( diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthEstimateGas.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthEstimateGas.java index c713ea20a7b..05d5f78e0ff 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthEstimateGas.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthEstimateGas.java @@ -16,14 +16,10 @@ 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.parameters.JsonCallParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.Quantity; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; -import org.hyperledger.besu.ethereum.core.BlockHeader; -import org.hyperledger.besu.ethereum.mainnet.ImmutableTransactionValidationParams; -import org.hyperledger.besu.ethereum.mainnet.TransactionValidationParams; import org.hyperledger.besu.ethereum.transaction.CallParameter; import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.ethereum.transaction.TransactionSimulatorResult; @@ -48,27 +44,17 @@ public String getName() { } @Override - protected Object resultByBlockHeader( + protected Object simulate( final JsonRpcRequestContext requestContext, - final JsonCallParameter callParams, - final BlockHeader blockHeader) { - - final CallParameter modifiedCallParams = - overrideGasLimitAndPrice(callParams, blockHeader.getGasLimit()); - - final boolean isAllowExceedingBalance = !callParams.isMaybeStrict().orElse(Boolean.FALSE); + final CallParameter callParams, + final long gasLimit, + final TransactionSimulationFunction simulationFunction) { final EstimateGasOperationTracer operationTracer = new EstimateGasOperationTracer(); - final var transactionValidationParams = - ImmutableTransactionValidationParams.builder() - .from(TransactionValidationParams.transactionSimulator()) - .isAllowExceedingBalance(isAllowExceedingBalance) - .build(); - LOG.debug("Processing transaction with params: {}", modifiedCallParams); + LOG.debug("Processing transaction with params: {}", callParams); final var maybeResult = - transactionSimulator.process( - modifiedCallParams, transactionValidationParams, operationTracer, blockHeader); + simulationFunction.simulate(overrideGasLimit(callParams, gasLimit), operationTracer); final Optional maybeErrorResponse = validateSimulationResult(requestContext, maybeResult); @@ -79,11 +65,7 @@ protected Object resultByBlockHeader( final var result = maybeResult.get(); long low = result.result().getEstimateGasUsedByTransaction(); final var lowResult = - transactionSimulator.process( - overrideGasLimitAndPrice(callParams, low), - transactionValidationParams, - operationTracer, - blockHeader); + simulationFunction.simulate(overrideGasLimit(callParams, low), operationTracer); if (lowResult.isPresent() && lowResult.get().isSuccessful()) { return Quantity.create(low); @@ -95,11 +77,7 @@ protected Object resultByBlockHeader( while (low + 1 < high) { mid = (low + high) / 2; var binarySearchResult = - transactionSimulator.process( - overrideGasLimitAndPrice(callParams, mid), - transactionValidationParams, - operationTracer, - blockHeader); + simulationFunction.simulate(overrideGasLimit(callParams, mid), operationTracer); if (binarySearchResult.isEmpty() || !binarySearchResult.get().isSuccessful()) { low = mid; diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceCallMany.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceCallMany.java index 10d4018bce2..34b40f72dc0 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceCallMany.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceCallMany.java @@ -116,8 +116,7 @@ protected Object resultByBlockNumber( .getAndMapWorldState( blockHeader.getBlockHash(), ws -> { - final WorldUpdater updater = - transactionSimulator.getEffectiveWorldStateUpdater(blockHeader, ws); + final WorldUpdater updater = transactionSimulator.getEffectiveWorldStateUpdater(ws); try { Arrays.stream(transactionsAndTraceTypeParameters) .forEachOrdered( @@ -158,9 +157,19 @@ private JsonNode getSingleCallResult( final Set traceTypes = traceTypeParameter.getTraceTypes(); final DebugOperationTracer tracer = new DebugOperationTracer(buildTraceOptions(traceTypes), false); + final var miningBeneficiary = + protocolSchedule + .getByBlockHeader(header) + .getMiningBeneficiaryCalculator() + .calculateBeneficiary(header); final Optional maybeSimulatorResult = transactionSimulator.processWithWorldUpdater( - callParameter, buildTransactionValidationParams(), tracer, header, worldUpdater); + callParameter, + buildTransactionValidationParams(), + tracer, + header, + worldUpdater, + miningBeneficiary); LOG.trace("Executing {} call for transaction {}", traceTypeParameter, callParameter); if (maybeSimulatorResult.isEmpty()) { diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/DebugJsonRpcMethods.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/DebugJsonRpcMethods.java index 90ae97c5c4f..9ca0bb6c1a4 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/DebugJsonRpcMethods.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/DebugJsonRpcMethods.java @@ -15,7 +15,6 @@ package org.hyperledger.besu.ethereum.api.jsonrpc.methods; import org.hyperledger.besu.ethereum.ProtocolContext; -import org.hyperledger.besu.ethereum.api.ApiConfiguration; import org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.DebugReplayBlock; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.DebugAccountAt; @@ -64,7 +63,7 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods { private final TransactionPool transactionPool; private final Synchronizer synchronizer; private final Path dataDir; - private final ApiConfiguration apiConfiguration; + private final TransactionSimulator transactionSimulator; DebugJsonRpcMethods( final BlockchainQueries blockchainQueries, @@ -74,7 +73,7 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods { final TransactionPool transactionPool, final Synchronizer synchronizer, final Path dataDir, - final ApiConfiguration apiConfiguration) { + final TransactionSimulator transactionSimulator) { this.blockchainQueries = blockchainQueries; this.protocolContext = protocolContext; this.protocolSchedule = protocolSchedule; @@ -82,7 +81,7 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods { this.transactionPool = transactionPool; this.synchronizer = synchronizer; this.dataDir = dataDir; - this.apiConfiguration = apiConfiguration; + this.transactionSimulator = transactionSimulator; } @Override @@ -120,13 +119,6 @@ protected Map create() { new DebugGetRawBlock(blockchainQueries), new DebugGetRawReceipts(blockchainQueries), new DebugGetRawTransaction(blockchainQueries), - new DebugTraceCall( - blockchainQueries, - protocolSchedule, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap()))); + new DebugTraceCall(blockchainQueries, protocolSchedule, transactionSimulator)); } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthJsonRpcMethods.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthJsonRpcMethods.java index de5662692ff..0ddcb564963 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthJsonRpcMethods.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthJsonRpcMethods.java @@ -89,6 +89,7 @@ public class EthJsonRpcMethods extends ApiGroupJsonRpcMethods { private final MiningCoordinator miningCoordinator; private final Set supportedCapabilities; private final ApiConfiguration apiConfiguration; + private final TransactionSimulator transactionSimulator; public EthJsonRpcMethods( final BlockchainQueries blockchainQueries, @@ -98,7 +99,8 @@ public EthJsonRpcMethods( final TransactionPool transactionPool, final MiningCoordinator miningCoordinator, final Set supportedCapabilities, - final ApiConfiguration apiConfiguration) { + final ApiConfiguration apiConfiguration, + final TransactionSimulator transactionSimulator) { this.blockchainQueries = blockchainQueries; this.synchronizer = synchronizer; this.protocolSchedule = protocolSchedule; @@ -107,6 +109,7 @@ public EthJsonRpcMethods( this.miningCoordinator = miningCoordinator; this.supportedCapabilities = supportedCapabilities; this.apiConfiguration = apiConfiguration; + this.transactionSimulator = transactionSimulator; } @Override @@ -125,13 +128,7 @@ protected Map create() { new EthGetBlockReceipts(blockchainQueries, protocolSchedule), new EthGetBlockTransactionCountByNumber(blockchainQueries), new EthGetBlockTransactionCountByHash(blockchainQueries), - new EthCall( - blockchainQueries, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), + new EthCall(blockchainQueries, transactionSimulator), new EthFeeHistory(protocolSchedule, blockchainQueries, miningCoordinator, apiConfiguration), new EthGetCode(blockchainQueries), new EthGetLogs(blockchainQueries, apiConfiguration.getMaxLogsRange()), @@ -155,20 +152,8 @@ protected Map create() { new EthGetStorageAt(blockchainQueries), new EthSendRawTransaction(transactionPool), new EthSendTransaction(), - new EthEstimateGas( - blockchainQueries, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), - new EthCreateAccessList( - blockchainQueries, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), + new EthEstimateGas(blockchainQueries, transactionSimulator), + new EthCreateAccessList(blockchainQueries, transactionSimulator), new EthMining(miningCoordinator), new EthCoinbase(miningCoordinator), new EthProtocolVersion(supportedCapabilities), 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 cdf4440bde9..2b4eaf8f576 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 @@ -36,6 +36,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.ObservableMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -85,7 +86,8 @@ public Map methods( final EthPeers ethPeers, final Vertx consensusEngineServer, final ApiConfiguration apiConfiguration, - final Optional enodeDnsConfiguration) { + final Optional enodeDnsConfiguration, + final TransactionSimulator transactionSimulator) { final Map enabled = new HashMap<>(); if (!rpcApis.isEmpty()) { final JsonRpcMethod modules = new RpcModules(rpcApis); @@ -111,7 +113,7 @@ public Map methods( transactionPool, synchronizer, dataDir, - apiConfiguration), + transactionSimulator), new EeaJsonRpcMethods( blockchainQueries, protocolSchedule, transactionPool, privacyParameters), new ExecutionEngineJsonRpcMethods( @@ -131,7 +133,8 @@ public Map methods( transactionPool, miningCoordinator, supportedCapabilities, - apiConfiguration), + apiConfiguration, + transactionSimulator), new NetJsonRpcMethods( p2pNetwork, networkId, @@ -151,7 +154,11 @@ public Map methods( blockchainQueries, protocolSchedule, transactionPool, privacyParameters), new Web3JsonRpcMethods(clientNodeName), new TraceJsonRpcMethods( - blockchainQueries, protocolSchedule, protocolContext, apiConfiguration), + blockchainQueries, + protocolSchedule, + protocolContext, + apiConfiguration, + transactionSimulator), new TxPoolJsonRpcMethods(transactionPool), new PluginsJsonRpcMethods(namedPlugins)); diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/TraceJsonRpcMethods.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/TraceJsonRpcMethods.java index 6a36bebfcd5..9cbe6378cd6 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/TraceJsonRpcMethods.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/TraceJsonRpcMethods.java @@ -38,19 +38,21 @@ public class TraceJsonRpcMethods extends ApiGroupJsonRpcMethods { private final BlockchainQueries blockchainQueries; private final ProtocolSchedule protocolSchedule; - private final ApiConfiguration apiConfiguration; private final ProtocolContext protocolContext; + private final TransactionSimulator transactionSimulator; TraceJsonRpcMethods( final BlockchainQueries blockchainQueries, final ProtocolSchedule protocolSchedule, final ProtocolContext protocolContext, - final ApiConfiguration apiConfiguration) { + final ApiConfiguration apiConfiguration, + final TransactionSimulator transactionSimulator) { this.blockchainQueries = blockchainQueries; this.protocolSchedule = protocolSchedule; this.protocolContext = protocolContext; this.apiConfiguration = apiConfiguration; + this.transactionSimulator = transactionSimulator; } @Override @@ -73,29 +75,8 @@ protected Map create() { new TraceTransaction( () -> new BlockTracer(blockReplay), protocolSchedule, blockchainQueries), new TraceBlock(protocolSchedule, blockchainQueries), - new TraceCall( - blockchainQueries, - protocolSchedule, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), - new TraceCallMany( - blockchainQueries, - protocolSchedule, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), - new TraceRawTransaction( - protocolSchedule, - blockchainQueries, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap()))); + new TraceCall(blockchainQueries, protocolSchedule, transactionSimulator), + new TraceCallMany(blockchainQueries, protocolSchedule, transactionSimulator), + new TraceRawTransaction(protocolSchedule, blockchainQueries, transactionSimulator)); } } 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 5a1c23d40ee..4ff63841f4c 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 @@ -109,8 +109,12 @@ public void setupTest() throws Exception { final MutableBlockchain blockchain = blockchainSetupUtil.getBlockchain(); ProtocolContext context = - new ProtocolContext( - blockchain, blockchainSetupUtil.getWorldArchive(), null, new BadBlockManager()); + ProtocolContext.create( + blockchain, + blockchainSetupUtil.getWorldArchive(), + blockchainSetupUtil.getProtocolSchedule(), + (pc, ps) -> null, + new BadBlockManager()); final BlockchainQueries blockchainQueries = new BlockchainQueries( blockchainSetupUtil.getProtocolSchedule(), 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 d504e3bb0d4..d9cd72a927d 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 @@ -46,6 +46,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -201,7 +202,8 @@ protected Map getRpcMethods( mock(EthPeers.class), syncVertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); } protected void startService() throws Exception { 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 022aa244220..8cefc8c993a 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 @@ -41,6 +41,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -138,7 +139,8 @@ public void initServerAndClient() throws Exception { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); service = createJsonRpcHttpService(); service.start().join(); 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 f9dba0bc260..a85085d71bc 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 @@ -46,6 +46,7 @@ import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -169,7 +170,8 @@ public static void initServerAndClient() throws Exception { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); service = createJsonRpcHttpService(); jwtAuth = service.authenticationService.get().getJwtAuthProvider(); service.start().join(); 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 63ae1b8bfb2..8f3d06200aa 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 @@ -51,6 +51,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -235,7 +236,8 @@ private JsonRpcHttpService createJsonRpcHttpServiceWithRpcApis(final JsonRpcConf mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); final JsonRpcHttpService jsonRpcHttpService = new JsonRpcHttpService( vertx, @@ -346,7 +348,8 @@ private JsonRpcHttpService createJsonRpcHttpService( mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); final JsonRpcHttpService jsonRpcHttpService = new JsonRpcHttpService( vertx, 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 5a439fa1947..5d614ba8e50 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 @@ -41,6 +41,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.evm.internal.EvmConfiguration; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; @@ -147,7 +148,8 @@ public static void initServerAndClient() throws Exception { ethPeersMock, vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); disabledRpcMethods = new HashMap<>(); addedRpcMethods = new HashSet<>(); 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 28474d3c536..86ebae6e7a8 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 @@ -48,6 +48,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -152,7 +153,8 @@ public void initServer() throws Exception { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); System.setProperty("javax.net.ssl.trustStore", CLIENT_AS_CA_CERT.getKeyStoreFile().toString()); System.setProperty( 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 15df60230b6..658a218cadf 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 @@ -47,6 +47,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -140,7 +141,8 @@ public void beforeEach() { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); } @AfterEach 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 6f7ce4e1d66..cb179681f61 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 @@ -47,6 +47,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -141,7 +142,8 @@ public void initServer() throws Exception { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); service = createJsonRpcHttpService(createJsonRpcConfig()); service.start().join(); baseUrl = service.url(); 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 47a16135ffd..f65d8a897ea 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 @@ -54,6 +54,7 @@ import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -205,7 +206,8 @@ public void before() throws URISyntaxException { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty())); + Optional.empty(), + mock(TransactionSimulator.class))); websocketMethods.putAll(rpcMethods); webSocketMessageHandlerSpy = 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 b843389c0d3..12ff53d8deb 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 @@ -14,6 +14,7 @@ */ package org.hyperledger.besu.ethereum.blockcreation; +import static org.hyperledger.besu.ethereum.core.BlockHeaderBuilder.createPending; import static org.hyperledger.besu.ethereum.mainnet.feemarket.ExcessBlobGasCalculator.calculateExcessBlobGasForParent; import org.hyperledger.besu.datatypes.Address; @@ -29,7 +30,6 @@ 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.Difficulty; import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.MutableWorldState; import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader; @@ -41,15 +41,12 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.AbstractBlockProcessor; import org.hyperledger.besu.ethereum.mainnet.BodyValidation; -import org.hyperledger.besu.ethereum.mainnet.DifficultyCalculator; import org.hyperledger.besu.ethereum.mainnet.MainnetTransactionProcessor; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec; import org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions; import org.hyperledger.besu.ethereum.mainnet.WithdrawalsProcessor; -import org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket; import org.hyperledger.besu.ethereum.mainnet.feemarket.ExcessBlobGasCalculator; -import org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket; import org.hyperledger.besu.ethereum.mainnet.requests.ProcessRequestContext; import org.hyperledger.besu.ethereum.mainnet.requests.RequestProcessorCoordinator; import org.hyperledger.besu.ethereum.vm.CachingBlockHashLookup; @@ -60,7 +57,6 @@ import org.hyperledger.besu.plugin.services.tracer.BlockAwareOperationTracer; import org.hyperledger.besu.plugin.services.txselection.PluginTransactionSelector; -import java.math.BigInteger; import java.util.List; import java.util.Optional; import java.util.concurrent.CancellationException; @@ -198,12 +194,15 @@ protected BlockCreationResult createBlock( protocolSchedule.getForNextBlockHeader(parentHeader, timestamp); final ProcessableBlockHeader processableBlockHeader = - createPendingBlockHeader( - timestamp, - maybePrevRandao, - maybeParentBeaconBlockRoot, - newProtocolSpec, - parentHeader); + createPending( + newProtocolSpec, + parentHeader, + miningParameters, + timestamp, + maybePrevRandao, + maybeParentBeaconBlockRoot) + .buildProcessableBlockHeader(); + final Address miningBeneficiary = miningBeneficiaryCalculator.getMiningBeneficiary(processableBlockHeader.getNumber()); @@ -422,53 +421,6 @@ private List selectOmmers() { return Lists.newArrayList(); } - private ProcessableBlockHeader createPendingBlockHeader( - final long timestamp, - final Optional maybePrevRandao, - final Optional maybeParentBeaconBlockRoot, - final ProtocolSpec protocolSpec, - final BlockHeader parentHeader) { - final long newBlockNumber = parentHeader.getNumber() + 1; - long gasLimit = - protocolSpec - .getGasLimitCalculator() - .nextGasLimit( - parentHeader.getGasLimit(), - miningParameters.getTargetGasLimit().orElse(parentHeader.getGasLimit()), - newBlockNumber); - - final DifficultyCalculator difficultyCalculator = protocolSpec.getDifficultyCalculator(); - final BigInteger difficulty = - difficultyCalculator.nextDifficulty(timestamp, parentHeader, protocolContext); - - final Wei baseFee = - Optional.of(protocolSpec.getFeeMarket()) - .filter(FeeMarket::implementsBaseFee) - .map(BaseFeeMarket.class::cast) - .map( - feeMarket -> - feeMarket.computeBaseFee( - newBlockNumber, - parentHeader.getBaseFee().orElse(Wei.ZERO), - parentHeader.getGasUsed(), - feeMarket.targetGasUsed(parentHeader))) - .orElse(null); - - final Bytes32 prevRandao = maybePrevRandao.orElse(null); - final Bytes32 parentBeaconBlockRoot = maybeParentBeaconBlockRoot.orElse(null); - return BlockHeaderBuilder.create() - .parentHash(parentHeader.getHash()) - .coinbase(miningParameters.getCoinbase().orElseThrow()) - .difficulty(Difficulty.of(difficulty)) - .number(newBlockNumber) - .gasLimit(gasLimit) - .timestamp(timestamp) - .baseFee(baseFee) - .prevRandao(prevRandao) - .parentBeaconBlockRoot(parentBeaconBlockRoot) - .buildProcessableBlockHeader(); - } - @Override public void cancel() { isCancelled.set(true); diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockMinerTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockMinerTest.java index e5b46925aad..81195c23d1c 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockMinerTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockMinerTest.java @@ -58,7 +58,7 @@ public void blockCreatedIsAddedToBlockChain() throws InterruptedException { headerBuilder.buildHeader(), new BlockBody(Lists.newArrayList(), Lists.newArrayList())); final ProtocolContext protocolContext = - new ProtocolContext(null, null, null, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> null, new BadBlockManager()); final PoWBlockCreator blockCreator = mock(PoWBlockCreator.class); final Function blockCreatorSupplier = @@ -102,7 +102,7 @@ public void failureToImportDoesNotTriggerObservers() throws InterruptedException headerBuilder.buildHeader(), new BlockBody(Lists.newArrayList(), Lists.newArrayList())); final ProtocolContext protocolContext = - new ProtocolContext(null, null, null, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> null, new BadBlockManager()); final PoWBlockCreator blockCreator = mock(PoWBlockCreator.class); final Function blockCreatorSupplier = @@ -150,7 +150,7 @@ public void blockValidationFailureBeforeImportDoesNotImportBlock() throws Interr headerBuilder.buildHeader(), new BlockBody(Lists.newArrayList(), Lists.newArrayList())); final ProtocolContext protocolContext = - new ProtocolContext(null, null, null, new BadBlockManager()); + ProtocolContext.create(null, null, null, (pc, ps) -> null, new BadBlockManager()); final PoWBlockCreator blockCreator = mock(PoWBlockCreator.class); final Function blockCreatorSupplier = diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ConsensusContextFactory.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ConsensusContextFactory.java index a9381fa199f..d92777ee8f9 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ConsensusContextFactory.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ConsensusContextFactory.java @@ -14,25 +14,21 @@ */ package org.hyperledger.besu.ethereum; -import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; -import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; /** The ConsensusContextFactory interface defines a method for creating a consensus context. */ @FunctionalInterface public interface ConsensusContextFactory { + /** Helper for when you do not need a consensus context */ + ConsensusContextFactory NULL = (pc, ps) -> null; /** * Creates a consensus context with the given blockchain, world state archive, and protocol * schedule. * - * @param blockchain the blockchain - * @param worldStateArchive the world state archive + * @param protocolContext the protocol context * @param protocolSchedule the protocol schedule * @return the created consensus context */ - ConsensusContext create( - Blockchain blockchain, - WorldStateArchive worldStateArchive, - ProtocolSchedule protocolSchedule); + ConsensusContext create(ProtocolContext protocolContext, ProtocolSchedule protocolSchedule); } diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java index e5ec5ae0921..f1a49c44fc2 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java @@ -31,7 +31,7 @@ public class ProtocolContext { private final MutableBlockchain blockchain; private final WorldStateArchive worldStateArchive; private final BadBlockManager badBlockManager; - private final ConsensusContext consensusContext; + private ConsensusContext consensusContext; private Optional synchronizer; @@ -41,43 +41,43 @@ public class ProtocolContext { * * @param blockchain the blockchain of the protocol context * @param worldStateArchive the world state archive of the protocol context - * @param consensusContext the consensus context of the protocol context * @param badBlockManager the bad block manager of the protocol context */ - public ProtocolContext( + protected ProtocolContext( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, - final ConsensusContext consensusContext, final BadBlockManager badBlockManager) { this.blockchain = blockchain; this.worldStateArchive = worldStateArchive; - this.consensusContext = consensusContext; this.synchronizer = Optional.empty(); this.badBlockManager = badBlockManager; } /** - * Initializes a new ProtocolContext with the given blockchain, world state archive, protocol - * schedule, consensus context factory, and bad block manager. + * Create a new ProtocolContext with the given blockchain, world state archive, protocol schedule, + * consensus context factory, and bad block manager. * * @param blockchain the blockchain of the protocol context * @param worldStateArchive the world state archive of the protocol context * @param protocolSchedule the protocol schedule of the protocol context * @param consensusContextFactory the consensus context factory of the protocol context * @param badBlockManager the bad block manager of the protocol context - * @return the initialized ProtocolContext + * @return the new ProtocolContext */ - public static ProtocolContext init( + public static ProtocolContext create( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, final ProtocolSchedule protocolSchedule, final ConsensusContextFactory consensusContextFactory, final BadBlockManager badBlockManager) { - return new ProtocolContext( - blockchain, - worldStateArchive, - consensusContextFactory.create(blockchain, worldStateArchive, protocolSchedule), - badBlockManager); + final var protocolContext = new ProtocolContext(blockchain, worldStateArchive, badBlockManager); + protocolContext.setConsensusContext( + consensusContextFactory.create(protocolContext, protocolSchedule)); + return protocolContext; + } + + private void setConsensusContext(final ConsensusContext consensusContext) { + this.consensusContext = consensusContext; } /** diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/BlockHeaderBuilder.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/BlockHeaderBuilder.java index 6f485d19ced..a14fdd632fb 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/BlockHeaderBuilder.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/core/BlockHeaderBuilder.java @@ -22,10 +22,14 @@ import org.hyperledger.besu.datatypes.BlobGas; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.mainnet.DifficultyCalculator; import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions; +import org.hyperledger.besu.ethereum.mainnet.ProtocolSpec; +import org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket; import org.hyperledger.besu.evm.log.LogsBloomFilter; import java.time.Instant; +import java.util.Optional; import java.util.OptionalLong; import org.apache.tuweni.bytes.Bytes; @@ -154,6 +158,55 @@ public static BlockHeaderBuilder fromBuilder(final BlockHeaderBuilder fromBuilde return toBuilder; } + public static BlockHeaderBuilder createPending( + final ProtocolSpec protocolSpec, + final BlockHeader parentHeader, + final MiningParameters miningParameters, + final long timestamp, + final Optional maybePrevRandao, + final Optional maybeParentBeaconBlockRoot) { + + final long newBlockNumber = parentHeader.getNumber() + 1; + final long gasLimit = + protocolSpec + .getGasLimitCalculator() + .nextGasLimit( + parentHeader.getGasLimit(), + miningParameters.getTargetGasLimit().orElse(parentHeader.getGasLimit()), + newBlockNumber); + + final DifficultyCalculator difficultyCalculator = protocolSpec.getDifficultyCalculator(); + final var difficulty = + Difficulty.of(difficultyCalculator.nextDifficulty(timestamp, parentHeader)); + + final Wei baseFee; + if (protocolSpec.getFeeMarket().implementsBaseFee()) { + final var baseFeeMarket = (BaseFeeMarket) protocolSpec.getFeeMarket(); + baseFee = + baseFeeMarket.computeBaseFee( + newBlockNumber, + parentHeader.getBaseFee().orElse(Wei.ZERO), + parentHeader.getGasUsed(), + baseFeeMarket.targetGasUsed(parentHeader)); + } else { + baseFee = null; + } + + final Bytes32 prevRandao = maybePrevRandao.orElse(null); + final Bytes32 parentBeaconBlockRoot = maybeParentBeaconBlockRoot.orElse(null); + + return BlockHeaderBuilder.create() + .parentHash(parentHeader.getHash()) + .coinbase(miningParameters.getCoinbase().orElseThrow()) + .difficulty(difficulty) + .number(newBlockNumber) + .gasLimit(gasLimit) + .timestamp(timestamp) + .baseFee(baseFee) + .prevRandao(prevRandao) + .parentBeaconBlockRoot(parentBeaconBlockRoot); + } + public BlockHeader buildBlockHeader() { validateBlockHeader(); diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedDifficultyCalculators.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedDifficultyCalculators.java index ceaf06e3530..692d3810c31 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedDifficultyCalculators.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedDifficultyCalculators.java @@ -34,6 +34,6 @@ public static boolean isFixedDifficultyInConfig(final GenesisConfigOptions confi public static DifficultyCalculator calculator(final GenesisConfigOptions config) { long difficulty = config.getEthashConfigOptions().getFixedDifficulty().getAsLong(); - return (time, parent, context) -> BigInteger.valueOf(difficulty); + return (time, parent) -> BigInteger.valueOf(difficulty); } } diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/ClassicDifficultyCalculators.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/ClassicDifficultyCalculators.java index 9a8f30d01f4..6e15eb87e09 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/ClassicDifficultyCalculators.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/ClassicDifficultyCalculators.java @@ -32,7 +32,7 @@ public abstract class ClassicDifficultyCalculators { private static final long DELAY = (CONTINUE_BLOCK - PAUSE_BLOCK) / EXPONENTIAL_DIFF_PERIOD; public static DifficultyCalculator DIFFICULTY_BOMB_PAUSED = - (time, parent, protocolContext) -> { + (time, parent) -> { final BigInteger parentDifficulty = difficulty(parent.getDifficulty()); final BigInteger difficulty = ensureMinimumDifficulty( @@ -43,7 +43,7 @@ public abstract class ClassicDifficultyCalculators { }; public static DifficultyCalculator DIFFICULTY_BOMB_DELAYED = - (time, parent, protocolContext) -> { + (time, parent) -> { final BigInteger parentDifficulty = difficulty(parent.getDifficulty()); final BigInteger difficulty = ensureMinimumDifficulty( @@ -55,7 +55,7 @@ public abstract class ClassicDifficultyCalculators { }; public static DifficultyCalculator DIFFICULTY_BOMB_REMOVED = - (time, parent, protocolContext) -> { + (time, parent) -> { final BigInteger parentDifficulty = difficulty(parent.getDifficulty()); final BigInteger difficulty = ensureMinimumDifficulty( @@ -66,7 +66,7 @@ public abstract class ClassicDifficultyCalculators { }; public static DifficultyCalculator EIP100 = - (time, parent, protocolContext) -> { + (time, parent) -> { final BigInteger parentDifficulty = difficulty(parent.getDifficulty()); final boolean hasOmmers = !parent.getOmmersHash().equals(Hash.EMPTY_LIST_HASH); final BigInteger difficulty = diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculator.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculator.java index d03bede977d..408f83cb510 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculator.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculator.java @@ -14,7 +14,6 @@ */ package org.hyperledger.besu.ethereum.mainnet; -import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.core.BlockHeader; import java.math.BigInteger; @@ -28,8 +27,7 @@ public interface DifficultyCalculator { * * @param time the time the block was generated * @param parent the block's parent block header - * @param context the context in which the difficulty calculator should operate * @return the block difficulty */ - BigInteger nextDifficulty(long time, BlockHeader parent, ProtocolContext context); + BigInteger nextDifficulty(long time, BlockHeader parent); } diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/MainnetDifficultyCalculators.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/MainnetDifficultyCalculators.java index 46f0a05e5dc..2129b10d5d0 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/MainnetDifficultyCalculators.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/MainnetDifficultyCalculators.java @@ -45,7 +45,7 @@ public abstract class MainnetDifficultyCalculators { private MainnetDifficultyCalculators() {} static final DifficultyCalculator FRONTIER = - (time, parent, protocolContext) -> { + (time, parent) -> { final BigInteger parentDifficulty = difficulty(parent.getDifficulty()); final BigInteger adjust = parentDifficulty.divide(DIFFICULTY_BOUND_DIVISOR); BigInteger difficulty; @@ -60,7 +60,7 @@ private MainnetDifficultyCalculators() {} }; static final DifficultyCalculator HOMESTEAD = - (time, parent, protocolContext) -> { + (time, parent) -> { final BigInteger parentDifficulty = difficulty(parent.getDifficulty()); final BigInteger difficulty = ensureMinimumDifficulty( @@ -72,35 +72,28 @@ private MainnetDifficultyCalculators() {} }; static final DifficultyCalculator BYZANTIUM = - (time, parent, protocolContext) -> - calculateThawedDifficulty(time, parent, BYZANTIUM_FAKE_BLOCK_OFFSET); + (time, parent) -> calculateThawedDifficulty(time, parent, BYZANTIUM_FAKE_BLOCK_OFFSET); static final DifficultyCalculator CONSTANTINOPLE = - (time, parent, protocolContext) -> - calculateThawedDifficulty(time, parent, CONSTANTINOPLE_FAKE_BLOCK_OFFSET); + (time, parent) -> calculateThawedDifficulty(time, parent, CONSTANTINOPLE_FAKE_BLOCK_OFFSET); static final DifficultyCalculator MUIR_GLACIER = - (time, parent, protocolContext) -> - calculateThawedDifficulty(time, parent, MUIR_GLACIER_FAKE_BLOCK_OFFSET); + (time, parent) -> calculateThawedDifficulty(time, parent, MUIR_GLACIER_FAKE_BLOCK_OFFSET); // As per https://eips.ethereum.org/EIPS/eip-3554 static final DifficultyCalculator LONDON = - (time, parent, protocolContext) -> - calculateThawedDifficulty(time, parent, LONDON_FAKE_BLOCK_OFFSET); + (time, parent) -> calculateThawedDifficulty(time, parent, LONDON_FAKE_BLOCK_OFFSET); // As per https://eips.ethereum.org/EIPS/eip-4345 static final DifficultyCalculator ARROW_GLACIER = - (time, parent, protocolContext) -> - calculateThawedDifficulty(time, parent, ARROW_GLACIER_FAKE_BLOCK_OFFSET); + (time, parent) -> calculateThawedDifficulty(time, parent, ARROW_GLACIER_FAKE_BLOCK_OFFSET); // As per https://eips.ethereum.org/EIPS/eip-5133 static final DifficultyCalculator GRAY_GLACIER = - (time, parent, protocolContext) -> - calculateThawedDifficulty(time, parent, GRAY_GLACIER_FAKE_BLOCK_OFFSET); + (time, parent) -> calculateThawedDifficulty(time, parent, GRAY_GLACIER_FAKE_BLOCK_OFFSET); // Proof-of-Stake difficulty must not be altered - static final DifficultyCalculator PROOF_OF_STAKE_DIFFICULTY = - (time, parent, protocolContext) -> BigInteger.ZERO; + static final DifficultyCalculator PROOF_OF_STAKE_DIFFICULTY = (time, parent) -> BigInteger.ZERO; private static BigInteger calculateThawedDifficulty( final long time, final BlockHeader parent, final long fakeBlockOffset) { diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/headervalidationrules/CalculatedDifficultyValidationRule.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/headervalidationrules/CalculatedDifficultyValidationRule.java index bcc4e213586..1eb4f044c2f 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/headervalidationrules/CalculatedDifficultyValidationRule.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/headervalidationrules/CalculatedDifficultyValidationRule.java @@ -39,7 +39,7 @@ public boolean validate( final BigInteger actualDifficulty = new BigInteger(1, header.getDifficulty().toArray()); final BigInteger expectedDifficulty = - difficultyCalculator.nextDifficulty(header.getTimestamp(), parent, context); + difficultyCalculator.nextDifficulty(header.getTimestamp(), parent); if (actualDifficulty.compareTo(expectedDifficulty) != 0) { LOG.info( diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulator.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulator.java index 321dc965ecd..576745cfc54 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulator.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulator.java @@ -26,7 +26,9 @@ import org.hyperledger.besu.ethereum.chain.Blockchain; 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.MutableWorldState; +import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.mainnet.ImmutableTransactionValidationParams; import org.hyperledger.besu.ethereum.mainnet.MainnetTransactionProcessor; @@ -79,16 +81,19 @@ public class TransactionSimulator { private final Blockchain blockchain; private final WorldStateArchive worldStateArchive; private final ProtocolSchedule protocolSchedule; + private final MiningParameters miningParameters; private final long rpcGasCap; public TransactionSimulator( final Blockchain blockchain, final WorldStateArchive worldStateArchive, final ProtocolSchedule protocolSchedule, + final MiningParameters miningParameters, final long rpcGasCap) { this.blockchain = blockchain; this.worldStateArchive = worldStateArchive; this.protocolSchedule = protocolSchedule; + this.miningParameters = miningParameters; this.rpcGasCap = rpcGasCap; } @@ -119,6 +124,70 @@ public Optional process( blockHeader); } + public Optional processOnPending( + final CallParameter callParams, + final TransactionValidationParams transactionValidationParams, + final OperationTracer operationTracer, + final ProcessableBlockHeader pendingBlockHeader) { + + try (final MutableWorldState disposableWorldState = + duplicateWorldStateAtParent(pendingBlockHeader.getParentHash())) { + WorldUpdater updater = getEffectiveWorldStateUpdater(disposableWorldState); + + // in order to trace the state diff we need to make sure that + // the world updater always has a parent + if (operationTracer instanceof DebugOperationTracer) { + updater = updater.parentUpdater().isPresent() ? updater : updater.updater(); + } + + return processWithWorldUpdater( + callParams, + transactionValidationParams, + operationTracer, + pendingBlockHeader, + updater, + Address.ZERO); + } catch (Exception e) { + throw new RuntimeException(e); + } + } + + public ProcessableBlockHeader simulatePendingBlockHeader() { + final long timestamp = System.currentTimeMillis(); + final var chainHeadHeader = blockchain.getChainHeadHeader(); + final ProtocolSpec protocolSpec = + protocolSchedule.getForNextBlockHeader(chainHeadHeader, timestamp); + + return BlockHeaderBuilder.createPending( + protocolSpec, + chainHeadHeader, + miningParameters, + timestamp, + Optional.empty(), + Optional.empty()) + .buildProcessableBlockHeader(); + } + + private MutableWorldState duplicateWorldStateAtParent(final Hash parentHash) { + final var parentHeader = + blockchain + .getBlockHeader(parentHash) + .orElseThrow( + () -> + new IllegalStateException("Block with hash " + parentHash + " not available")); + + final Hash parentStateRoot = parentHeader.getStateRoot(); + return worldStateArchive + .getMutable(parentHeader, false) + .orElseThrow( + () -> + new IllegalArgumentException( + "World state not available for block " + + parentHeader.getNumber() + + " with state root " + + parentStateRoot)); + } + public Optional processAtHead(final CallParameter callParams) { final var chainHeadHash = blockchain.getChainHeadHash(); return process( @@ -158,7 +227,7 @@ public Optional process( try (final MutableWorldState ws = getWorldState(header)) { - WorldUpdater updater = getEffectiveWorldStateUpdater(header, ws); + WorldUpdater updater = getEffectiveWorldStateUpdater(ws); // in order to trace the state diff we need to make sure that // the world updater always has a parent @@ -166,10 +235,21 @@ public Optional process( updater = updater.parentUpdater().isPresent() ? updater : updater.updater(); } + final var miningBeneficiary = + protocolSchedule + .getByBlockHeader(header) + .getMiningBeneficiaryCalculator() + .calculateBeneficiary(header); + return preWorldStateCloseGuard.apply( ws, processWithWorldUpdater( - callParams, transactionValidationParams, operationTracer, header, updater)); + callParams, + transactionValidationParams, + operationTracer, + header, + updater, + miningBeneficiary)); } catch (final Exception e) { return Optional.empty(); @@ -210,21 +290,25 @@ public Optional processWithWorldUpdater( final CallParameter callParams, final TransactionValidationParams transactionValidationParams, final OperationTracer operationTracer, - final BlockHeader header, - final WorldUpdater updater) { - final ProtocolSpec protocolSpec = protocolSchedule.getByBlockHeader(header); + final ProcessableBlockHeader processableHeader, + final WorldUpdater updater, + final Address miningBeneficiary) { + final ProtocolSpec protocolSpec = protocolSchedule.getByBlockHeader(processableHeader); final Address senderAddress = callParams.getFrom() != null ? callParams.getFrom() : DEFAULT_FROM; - BlockHeader blockHeaderToProcess = header; - - if (transactionValidationParams.isAllowExceedingBalance() && header.getBaseFee().isPresent()) { + final ProcessableBlockHeader blockHeaderToProcess; + if (transactionValidationParams.isAllowExceedingBalance() + && processableHeader.getBaseFee().isPresent()) { blockHeaderToProcess = - BlockHeaderBuilder.fromHeader(header) + new BlockHeaderBuilder() + .populateFrom(processableHeader) .baseFee(Wei.ZERO) .blockHeaderFunctions(protocolSpec.getBlockHeaderFunctions()) - .buildBlockHeader(); + .buildProcessableBlockHeader(); + } else { + blockHeaderToProcess = processableHeader; } final Account sender = updater.get(senderAddress); @@ -255,7 +339,7 @@ public Optional processWithWorldUpdater( buildTransaction( callParams, transactionValidationParams, - header, + processableHeader, senderAddress, nonce, simulationGasCap, @@ -272,9 +356,7 @@ public Optional processWithWorldUpdater( updater, blockHeaderToProcess, transaction, - protocolSpec - .getMiningBeneficiaryCalculator() - .calculateBeneficiary(blockHeaderToProcess), + miningBeneficiary, new CachingBlockHashLookup(blockHeaderToProcess, blockchain), false, transactionValidationParams, @@ -319,7 +401,7 @@ private long calculateSimulationGasCap( private Optional buildTransaction( final CallParameter callParams, final TransactionValidationParams transactionValidationParams, - final BlockHeader header, + final ProcessableBlockHeader processableHeader, final Address senderAddress, final long nonce, final long gasLimit, @@ -356,7 +438,7 @@ private Optional buildTransaction( maxPriorityFeePerGas = callParams.getMaxPriorityFeePerGas().orElse(gasPrice); maxFeePerBlobGas = callParams.getMaxFeePerBlobGas().orElse(blobGasPrice); } - if (header.getBaseFee().isEmpty()) { + if (processableHeader.getBaseFee().isEmpty()) { transactionBuilder.gasPrice(gasPrice); } else if (protocolSchedule.getChainId().isPresent()) { transactionBuilder.maxFeePerGas(maxFeePerGas).maxPriorityFeePerGas(maxPriorityFeePerGas); @@ -382,8 +464,7 @@ private Optional buildTransaction( return Optional.ofNullable(transaction); } - public WorldUpdater getEffectiveWorldStateUpdater( - final BlockHeader header, final MutableWorldState publicWorldState) { + public WorldUpdater getEffectiveWorldStateUpdater(final MutableWorldState publicWorldState) { return publicWorldState.updater(); } diff --git a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java index 62d670c07ab..6f08a6dd59e 100644 --- a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java +++ b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java @@ -21,7 +21,6 @@ import static org.mockito.Mockito.mock; import org.hyperledger.besu.config.GenesisConfigFile; -import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.Blockchain; @@ -160,16 +159,8 @@ private static ProtocolSchedule mainnetProtocolScheduleProvider( private static ProtocolContext mainnetProtocolContextProvider( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive) { - return new ProtocolContext( - blockchain, - worldStateArchive, - new ConsensusContext() { - @Override - public C as(final Class klass) { - return null; - } - }, - new BadBlockManager()); + return ProtocolContext.create( + blockchain, worldStateArchive, null, (pc, ps) -> null, new BadBlockManager()); } private static BlockchainSetupUtil create( diff --git a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java index 511b94d3ae5..0226394dab5 100644 --- a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java +++ b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java @@ -76,7 +76,8 @@ private ExecutionContextTestFixture( else this.stateArchive = createInMemoryWorldStateArchive(); this.protocolSchedule = protocolSchedule; this.protocolContext = - new ProtocolContext(blockchain, stateArchive, null, new BadBlockManager()); + ProtocolContext.create( + blockchain, stateArchive, protocolSchedule, (pc, ps) -> null, new BadBlockManager()); genesisState.writeStateTo(stateArchive.getMutable()); } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java index 7969ab6824a..bcbe7a48592 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/difficulty/fixed/FixedProtocolScheduleTest.java @@ -49,21 +49,21 @@ public void reportedDifficultyForAllBlocksIsAFixedValue() { schedule .getByBlockHeader(blockHeader(0)) .getDifficultyCalculator() - .nextDifficulty(1, parentHeader, null)) + .nextDifficulty(1, parentHeader)) .isEqualTo(FixedDifficultyCalculators.DEFAULT_DIFFICULTY); assertThat( schedule .getByBlockHeader(blockHeader(500)) .getDifficultyCalculator() - .nextDifficulty(1, parentHeader, null)) + .nextDifficulty(1, parentHeader)) .isEqualTo(FixedDifficultyCalculators.DEFAULT_DIFFICULTY); assertThat( schedule .getByBlockHeader(blockHeader(500_000)) .getDifficultyCalculator() - .nextDifficulty(1, parentHeader, null)) + .nextDifficulty(1, parentHeader)) .isEqualTo(FixedDifficultyCalculators.DEFAULT_DIFFICULTY); } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulatorTest.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulatorTest.java index c6c676c4151..108bad86f0a 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulatorTest.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/transaction/TransactionSimulatorTest.java @@ -36,6 +36,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderFunctions; 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.MutableWorldState; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.mainnet.ImmutableTransactionValidationParams; @@ -94,10 +95,13 @@ public class TransactionSimulatorTest { @BeforeEach public void setUp() { + final var miningParameters = MiningParameters.newDefault(); this.transactionSimulator = - new TransactionSimulator(blockchain, worldStateArchive, protocolSchedule, 0); + new TransactionSimulator( + blockchain, worldStateArchive, protocolSchedule, miningParameters, 0); this.cappedTransactionSimulator = - new TransactionSimulator(blockchain, worldStateArchive, protocolSchedule, GAS_CAP); + new TransactionSimulator( + blockchain, worldStateArchive, protocolSchedule, miningParameters, GAS_CAP); } @Test diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java index dd9257441e8..13c155510f6 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java @@ -170,7 +170,8 @@ public void createStorage() { EvmConfiguration.DEFAULT); var ws = archive.getMutable(); genesisState.writeStateTo(ws); - protocolContext = new ProtocolContext(blockchain, archive, null, new BadBlockManager()); + protocolContext = + ProtocolContext.create(blockchain, archive, null, (pc, ps) -> null, new BadBlockManager()); ethContext = mock(EthContext.class, RETURNS_DEEP_STUBS); when(ethContext.getEthPeers().subscribeConnect(any())).thenReturn(1L); transactionPool = diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/AbstractBlockPropagationManagerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/AbstractBlockPropagationManagerTest.java index c576b7f8e26..c9a28a97294 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/AbstractBlockPropagationManagerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/AbstractBlockPropagationManagerTest.java @@ -104,10 +104,11 @@ protected void setup(final DataStorageFormat dataStorageFormat) { protocolSchedule = blockchainUtil.getProtocolSchedule(); final ProtocolContext tempProtocolContext = blockchainUtil.getProtocolContext(); protocolContext = - new ProtocolContext( + ProtocolContext.create( blockchain, tempProtocolContext.getWorldStateArchive(), - tempProtocolContext.getConsensusContext(ConsensusContext.class), + null, + (pc, ps) -> tempProtocolContext.getConsensusContext(ConsensusContext.class), new BadBlockManager()); ethProtocolManager = EthProtocolManagerTestUtil.create( diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncTargetManagerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncTargetManagerTest.java index 027bd270d29..c42cf3f8114 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncTargetManagerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncTargetManagerTest.java @@ -77,7 +77,8 @@ public void setup(final DataStorageFormat storageFormat) { final ProtocolSchedule protocolSchedule = ProtocolScheduleFixture.MAINNET; final ProtocolContext protocolContext = - new ProtocolContext(localBlockchain, localWorldState, null, new BadBlockManager()); + ProtocolContext.create( + localBlockchain, localWorldState, null, (pc, ps) -> null, new BadBlockManager()); ethProtocolManager = EthProtocolManagerTestUtil.create( protocolSchedule, diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskParameterizedTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskParameterizedTest.java index 73d5e5138b4..605b4d79fd5 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskParameterizedTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskParameterizedTest.java @@ -151,7 +151,8 @@ public void searchesAgainstNetwork(final int headerRequestSize, final int common final EthContext ethContext = ethProtocolManager.ethContext(); final ProtocolContext protocolContext = - new ProtocolContext(localBlockchain, worldStateArchive, null, new BadBlockManager()); + ProtocolContext.create( + localBlockchain, worldStateArchive, null, (pc, ps) -> null, new BadBlockManager()); final EthTask task = DetermineCommonAncestorTask.create( diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java index 1b19a076d2c..1de4fb74efd 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java @@ -88,7 +88,8 @@ public void setup() { EthProtocolConfiguration.defaultConfig()); ethContext = ethProtocolManager.ethContext(); protocolContext = - new ProtocolContext(localBlockchain, worldStateArchive, null, new BadBlockManager()); + ProtocolContext.create( + localBlockchain, worldStateArchive, null, (pc, ps) -> null, new BadBlockManager()); } @Test 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 c679183b0ff..e642916936a 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 @@ -135,7 +135,8 @@ public TestNode( final WorldStateArchive worldStateArchive = createInMemoryWorldStateArchive(); genesisState.writeStateTo(worldStateArchive.getMutable()); final ProtocolContext protocolContext = - new ProtocolContext(blockchain, worldStateArchive, null, new BadBlockManager()); + ProtocolContext.create( + blockchain, worldStateArchive, null, (pc, ps) -> null, new BadBlockManager()); final SyncState syncState = mock(SyncState.class); final SynchronizerConfiguration syncConfig = mock(SynchronizerConfiguration.class); diff --git a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/NodeSmartContractPermissioningControllerTest.java b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/NodeSmartContractPermissioningControllerTest.java index a9c97b1cc4e..08ecd9c210d 100644 --- a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/NodeSmartContractPermissioningControllerTest.java +++ b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/NodeSmartContractPermissioningControllerTest.java @@ -28,6 +28,7 @@ import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; +import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.ProtocolScheduleFixture; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.peers.EnodeURLImpl; @@ -70,7 +71,8 @@ private NodeSmartContractPermissioningController setupController( genesisState.writeStateTo(worldArchive.getMutable()); final TransactionSimulator ts = - new TransactionSimulator(blockchain, worldArchive, protocolSchedule, 0L); + new TransactionSimulator( + blockchain, worldArchive, protocolSchedule, MiningParameters.newDefault(), 0L); final Address contractAddress = Address.fromHexString(contractAddressString); when(metricsSystem.createCounter( diff --git a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java index 1fd4f58a4bd..881fa31b1cd 100644 --- a/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java +++ b/ethereum/permissioning/src/test/java/org/hyperledger/besu/ethereum/permissioning/TransactionSmartContractPermissioningControllerTest.java @@ -29,6 +29,7 @@ import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; +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.mainnet.ProtocolSchedule; @@ -69,7 +70,8 @@ private TransactionSmartContractPermissioningController setupController( genesisState.writeStateTo(worldArchive.getMutable()); final TransactionSimulator ts = - new TransactionSimulator(blockchain, worldArchive, protocolSchedule, 0L); + new TransactionSimulator( + blockchain, worldArchive, protocolSchedule, MiningParameters.newDefault(), 0L); final Address contractAddress = Address.fromHexString(contractAddressString); when(metricsSystem.createCounter( diff --git a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/BlockchainReferenceTestCaseSpec.java b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/BlockchainReferenceTestCaseSpec.java index a30401e17ce..bedaf26670f 100644 --- a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/BlockchainReferenceTestCaseSpec.java +++ b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/BlockchainReferenceTestCaseSpec.java @@ -20,6 +20,7 @@ import org.hyperledger.besu.datatypes.BlobGas; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.ConsensusContextFactory; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; @@ -109,7 +110,12 @@ public BlockchainReferenceTestCaseSpec( this.blockchain = buildBlockchain(genesisBlockHeader); this.sealEngine = sealEngine; this.protocolContext = - new ProtocolContext(this.blockchain, this.worldStateArchive, null, new BadBlockManager()); + ProtocolContext.create( + this.blockchain, + this.worldStateArchive, + null, + ConsensusContextFactory.NULL, + new BadBlockManager()); } public String getNetwork() { diff --git a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestEnv.java b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestEnv.java index 636e23f8786..47e3281e0d1 100644 --- a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestEnv.java +++ b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestEnv.java @@ -223,8 +223,7 @@ public BlockHeader parentBlockHeader(final ProtocolSpec protocolSpec) { BlockHeaderBuilder.createDefault() .difficulty(Difficulty.fromHexOrDecimalString(parentDifficulty)) .number(number - 1) - .buildBlockHeader(), - null))); + .buildBlockHeader()))); } if (parentExcessBlobGas != null && parentBlobGasUsed != null) { builder.excessBlobGas(BlobGas.of(Long.decode(parentExcessBlobGas))); diff --git a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculatorTests.java b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculatorTests.java index cfb56d1ebc1..102bac6ebef 100644 --- a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculatorTests.java +++ b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/mainnet/DifficultyCalculatorTests.java @@ -18,7 +18,6 @@ import static org.assertj.core.api.Assertions.assertThat; -import org.checkerframework.checker.units.qual.N; import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.config.StubGenesisConfigOptions; @@ -34,7 +33,6 @@ import java.io.IOException; import java.nio.charset.StandardCharsets; -import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.stream.Stream; @@ -183,7 +181,7 @@ private void testDifficulty( UInt256.fromHexString(value.get("currentDifficulty").asText()); final var spec = protocolSchedule.getByBlockHeader(testHeader); final var calculator = spec.getDifficultyCalculator(); - assertThat(UInt256.valueOf(calculator.nextDifficulty(currentTime, testHeader, null))) + assertThat(UInt256.valueOf(calculator.nextDifficulty(currentTime, testHeader))) .describedAs("File %s Test %s", testFile, entry.getKey()) .isEqualTo(currentDifficulty); } 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 32d4e0bab10..3b85fda3dd9 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 @@ -187,7 +187,9 @@ private boolean buildContext( genesisState.writeStateTo(worldState); blockchain = createInMemoryBlockchain(genesisState.getBlock()); - protocolContext = new ProtocolContext(blockchain, worldStateArchive, null, badBlockManager); + protocolContext = + ProtocolContext.create( + blockchain, worldStateArchive, protocolSchedule, (pc, ps) -> null, badBlockManager); blockchainQueries = new BlockchainQueries( diff --git a/evm/src/main/java/org/hyperledger/besu/evm/tracing/AccessListOperationTracer.java b/evm/src/main/java/org/hyperledger/besu/evm/tracing/AccessListOperationTracer.java index 20b2db47cb3..a94c098bf8d 100644 --- a/evm/src/main/java/org/hyperledger/besu/evm/tracing/AccessListOperationTracer.java +++ b/evm/src/main/java/org/hyperledger/besu/evm/tracing/AccessListOperationTracer.java @@ -47,15 +47,16 @@ public void tracePostExecution(final MessageFrame frame, final OperationResult o * @return the access list */ public List getAccessList() { - final List list = new ArrayList<>(); if (warmedUpStorage != null && !warmedUpStorage.isEmpty()) { + final List list = new ArrayList<>(warmedUpStorage.size()); warmedUpStorage .rowMap() .forEach( (address, storageKeys) -> list.add(new AccessListEntry(address, new ArrayList<>(storageKeys.keySet())))); + return list; } - return list; + return List.of(); } /** diff --git a/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/TransactionSimulationService.java b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/TransactionSimulationService.java index dffdb0cfe51..6c4cc44bc1e 100644 --- a/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/TransactionSimulationService.java +++ b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/TransactionSimulationService.java @@ -29,14 +29,14 @@ public interface TransactionSimulationService extends BesuService { * Simulate transaction execution at the block identified by the hash * * @param transaction tx - * @param blockHash the hash of the block + * @param maybeBlockHash optional hash of the block, empty to simulate on pending block * @param operationTracer the tracer * @param isAllowExceedingBalance should ignore the sender balance during the simulation? * @return the result of the simulation */ Optional simulate( Transaction transaction, - Hash blockHash, + Optional maybeBlockHash, OperationTracer operationTracer, boolean isAllowExceedingBalance); } From 96d4f05854eb44881c2580793c9d02bea05956cd Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Mon, 21 Oct 2024 12:30:52 +0200 Subject: [PATCH 2/7] Cleanup: Synchronizer is always present in protocol context Signed-off-by: Fabio Di Fabio --- .../besu/controller/BesuControllerBuilder.java | 2 +- .../besu/ethereum/MainnetBlockValidator.java | 11 +---------- .../hyperledger/besu/ethereum/ProtocolContext.java | 10 ++++------ .../besu/ethereum/eth/manager/snap/SnapServer.java | 11 ++++------- 4 files changed, 10 insertions(+), 24 deletions(-) diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java index ac490d4ca45..2375e8f06c2 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java @@ -717,7 +717,7 @@ public BesuController build() { ethPeers.snapServerPeersNeeded(false); } - protocolContext.setSynchronizer(Optional.of(synchronizer)); + protocolContext.setSynchronizer(synchronizer); final Optional maybeSnapProtocolManager = createSnapProtocolManager( diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/MainnetBlockValidator.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/MainnetBlockValidator.java index 0c56a419e35..9cd014f25aa 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/MainnetBlockValidator.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/MainnetBlockValidator.java @@ -181,16 +181,7 @@ public BlockProcessingResult validateAndProcessBlock( Optional.of(new BlockProcessingOutputs(worldState, receipts, maybeRequests))); } } catch (MerkleTrieException ex) { - context - .getSynchronizer() - .ifPresentOrElse( - synchronizer -> synchronizer.healWorldState(ex.getMaybeAddress(), ex.getLocation()), - () -> - handleFailedBlockProcessing( - block, - new BlockProcessingResult(Optional.empty(), ex), - // Do not record bad black due to missing data - false)); + context.getSynchronizer().healWorldState(ex.getMaybeAddress(), ex.getLocation()); return new BlockProcessingResult(Optional.empty(), ex); } catch (StorageException ex) { var retval = new BlockProcessingResult(Optional.empty(), ex); diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java index f1a49c44fc2..3c7e837f33d 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java @@ -32,8 +32,7 @@ public class ProtocolContext { private final WorldStateArchive worldStateArchive; private final BadBlockManager badBlockManager; private ConsensusContext consensusContext; - - private Optional synchronizer; + private Synchronizer synchronizer; /** * Constructs a new ProtocolContext with the given blockchain, world state archive, consensus @@ -49,7 +48,6 @@ protected ProtocolContext( final BadBlockManager badBlockManager) { this.blockchain = blockchain; this.worldStateArchive = worldStateArchive; - this.synchronizer = Optional.empty(); this.badBlockManager = badBlockManager; } @@ -76,7 +74,7 @@ public static ProtocolContext create( return protocolContext; } - private void setConsensusContext(final ConsensusContext consensusContext) { + public void setConsensusContext(final ConsensusContext consensusContext) { this.consensusContext = consensusContext; } @@ -85,7 +83,7 @@ private void setConsensusContext(final ConsensusContext consensusContext) { * * @return the synchronizer of the protocol context */ - public Optional getSynchronizer() { + public Synchronizer getSynchronizer() { return synchronizer; } @@ -94,7 +92,7 @@ public Optional getSynchronizer() { * * @param synchronizer the synchronizer to set */ - public void setSynchronizer(final Optional synchronizer) { + public void setSynchronizer(final Synchronizer synchronizer) { this.synchronizer = synchronizer; } diff --git a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/snap/SnapServer.java b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/snap/SnapServer.java index 7de933e1370..2a8048ad44f 100644 --- a/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/snap/SnapServer.java +++ b/ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/manager/snap/SnapServer.java @@ -112,13 +112,10 @@ class SnapServer implements BesuEvents.InitialSyncCompletionListener { registerResponseConstructors(); // subscribe to initial sync completed events to start/stop snap server: - this.protocolContext - .flatMap(ProtocolContext::getSynchronizer) - .filter(z -> z instanceof DefaultSynchronizer) - .map(DefaultSynchronizer.class::cast) - .ifPresentOrElse( - z -> this.listenerId.set(z.subscribeInitialSync(this)), - () -> LOGGER.warn("SnapServer created without reference to sync status")); + final var synchronizer = protocolContext.getSynchronizer(); + if (synchronizer instanceof DefaultSynchronizer) { + this.listenerId.set(((DefaultSynchronizer) synchronizer).subscribeInitialSync(this)); + } } /** From d914178cf7352733dbbf1b144c97a5ab28fc6d9f Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Mon, 21 Oct 2024 16:56:20 +0200 Subject: [PATCH 3/7] Create ConsensusContext before ProtocolContext Signed-off-by: Fabio Di Fabio --- .../controller/BesuControllerBuilder.java | 23 ++++++++-------- .../CliqueBesuControllerBuilder.java | 9 ++++--- ...onsensusScheduleBesuControllerBuilder.java | 23 +++++++++------- .../controller/IbftBesuControllerBuilder.java | 10 +++---- .../MainnetBesuControllerBuilder.java | 5 +++- .../MergeBesuControllerBuilder.java | 6 +++-- .../controller/QbftBesuControllerBuilder.java | 25 ++++++----------- .../TransitionBesuControllerBuilder.java | 17 ++++++------ ...nsusScheduleBesuControllerBuilderTest.java | 21 ++++++++------- .../MergeBesuControllerBuilderTest.java | 22 +++++++-------- .../clique/NodeCanProduceNextBlockTest.java | 21 +++++---------- .../blockcreation/CliqueBlockCreatorTest.java | 3 +-- .../blockcreation/CliqueBlockMinerTest.java | 4 +-- .../CliqueMinerExecutorTest.java | 2 +- .../CliqueDifficultyValidationRuleTest.java | 2 +- .../CliqueExtraDataValidationRuleTest.java | 2 +- ...xt.java => MigratingConsensusContext.java} | 4 +-- .../common/MigratingProtocolContext.java | 27 +++++++------------ .../common/MigratingProtocolContextTest.java | 10 +++---- .../BftCoinbaseValidationRuleTest.java | 12 ++------- .../BftCommitSealsValidationRuleTest.java | 10 +++---- .../BftValidatorsValidationRuleTest.java | 9 +++---- .../BftVanityDataValidationRuleTest.java | 3 +-- .../ibft/support/TestContextBuilder.java | 3 +-- .../tests/round/IbftRoundIntegrationTest.java | 3 +-- ...ockHeaderValidationRulesetFactoryTest.java | 3 +-- .../ibft/IbftProtocolScheduleTest.java | 4 +-- .../blockcreation/BftBlockCreatorTest.java | 4 +-- .../IbftBlockHeightManagerTest.java | 6 +---- .../ibft/statemachine/IbftRoundTest.java | 3 +-- .../ibft/validation/MessageValidatorTest.java | 3 +-- .../blockcreation/MergeCoordinatorTest.java | 7 +---- .../merge/blockcreation/MergeReorgTest.java | 7 +---- .../qbft/support/TestContextBuilder.java | 3 +-- .../test/round/QbftRoundIntegrationTest.java | 6 ++--- ...ockHeaderValidationRulesetFactoryTest.java | 5 +--- .../qbft/QbftProtocolScheduleTest.java | 5 +--- .../QbftValidatorsValidationRuleTest.java | 16 +++-------- .../QbftBlockHeightManagerTest.java | 6 ++--- .../qbft/statemachine/QbftRoundTest.java | 6 ++--- .../ProposalPayloadValidatorTest.java | 5 +--- .../validation/ProposalValidatorTest.java | 5 +--- .../RoundChangeMessageValidatorTest.java | 5 +--- .../jsonrpc/JsonRpcTestMethodsFactory.java | 3 ++- ...ckByNumberLatestDesyncIntegrationTest.java | 3 ++- .../AbstractEthGraphQLHttpServiceTest.java | 4 +-- .../blockcreation/BlockMinerTest.java | 7 ++--- .../besu/ethereum/ProtocolContext.java | 22 ++++++--------- .../ethereum/core/BlockchainSetupUtil.java | 2 +- .../core/ConsensusContextFixture.java | 24 +++++++++++++++++ .../core/ExecutionContextTestFixture.java | 2 +- .../bonsai/AbstractIsolationTests.java | 4 ++- .../AbstractBlockPropagationManagerTest.java | 3 +-- .../fullsync/FullSyncTargetManagerTest.java | 3 ++- ...neCommonAncestorTaskParameterizedTest.java | 6 ++++- .../DetermineCommonAncestorTaskTest.java | 6 ++++- .../ethereum/eth/transactions/TestNode.java | 3 ++- .../BlockchainReferenceTestCaseSpec.java | 5 ++-- ethereum/retesteth/build.gradle | 1 + .../ethereum/retesteth/RetestethContext.java | 3 ++- 60 files changed, 216 insertions(+), 260 deletions(-) rename consensus/common/src/main/java/org/hyperledger/besu/consensus/common/{MigratingContext.java => MigratingConsensusContext.java} (88%) create mode 100644 ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ConsensusContextFixture.java diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java index 2375e8f06c2..8bc86937eea 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java @@ -26,7 +26,6 @@ import org.hyperledger.besu.cryptoservices.NodeKey; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.ethereum.ConsensusContext; -import org.hyperledger.besu.ethereum.ConsensusContextFactory; import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.api.jsonrpc.methods.JsonRpcMethods; @@ -594,9 +593,11 @@ public BesuController build() { genesisState.writeStateTo(worldStateArchive.getMutable()); } + final var consensusContext = + createConsensusContext(blockchain, worldStateArchive, protocolSchedule); + final ProtocolContext protocolContext = - createProtocolContext( - blockchain, worldStateArchive, protocolSchedule, this::createConsensusContext); + createProtocolContext(blockchain, worldStateArchive, consensusContext); validateContext(protocolContext); protocolSchedule.setPublicWorldStateArchiveForPrivacyBlockProcessor( @@ -989,12 +990,15 @@ protected void validateContext(final ProtocolContext context) {} /** * Create consensus context consensus context. * - * @param protocolContext the protocol context + * @param blockchain the blockchain + * @param worldStateArchive the world state archive * @param protocolSchedule the protocol schedule * @return the consensus context */ protected abstract ConsensusContext createConsensusContext( - ProtocolContext protocolContext, ProtocolSchedule protocolSchedule); + final Blockchain blockchain, + final WorldStateArchive worldStateArchive, + final ProtocolSchedule protocolSchedule); /** * Gets supported protocol. @@ -1054,17 +1058,14 @@ protected EthProtocolManager createEthProtocolManager( * * @param blockchain the blockchain * @param worldStateArchive the world state archive - * @param protocolSchedule the protocol schedule - * @param consensusContextFactory the consensus context factory + * @param consensusContext the consensus context * @return the protocol context */ protected ProtocolContext createProtocolContext( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule, - final ConsensusContextFactory consensusContextFactory) { - return ProtocolContext.create( - blockchain, worldStateArchive, protocolSchedule, consensusContextFactory, badBlockManager); + final ConsensusContext consensusContext) { + return ProtocolContext.create(blockchain, worldStateArchive, consensusContext, badBlockManager); } private Optional createSnapProtocolManager( 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 89f02c7dd86..1cdc2f3788b 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java @@ -43,6 +43,7 @@ import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import java.util.concurrent.atomic.AtomicReference; @@ -162,11 +163,13 @@ protected PluginServiceFactory createAdditionalPluginServices( @Override protected CliqueContext createConsensusContext( - final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { - validatorProviderRef.set(createValidatorProvider(protocolContext.getBlockchain())); + final Blockchain blockchain, + final WorldStateArchive worldStateArchive, + final ProtocolSchedule protocolSchedule) { + validatorProviderRef.set(createValidatorProvider(blockchain)); final CliqueContext cliqueContext = new CliqueContext(validatorProviderRef.get(), epochManager, blockInterface); - installCliqueBlockChoiceRule(protocolContext.getBlockchain(), cliqueContext); + installCliqueBlockChoiceRule(blockchain, cliqueContext); return cliqueContext; } diff --git a/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java index 2780dbd73d0..ba931d71f48 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java @@ -20,13 +20,12 @@ import org.hyperledger.besu.consensus.common.CombinedProtocolScheduleFactory; import org.hyperledger.besu.consensus.common.ForkSpec; import org.hyperledger.besu.consensus.common.ForksSchedule; -import org.hyperledger.besu.consensus.common.MigratingContext; +import org.hyperledger.besu.consensus.common.MigratingConsensusContext; import org.hyperledger.besu.consensus.common.MigratingMiningCoordinator; import org.hyperledger.besu.consensus.common.MigratingProtocolContext; import org.hyperledger.besu.cryptoservices.NodeKey; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.ethereum.ConsensusContext; -import org.hyperledger.besu.ethereum.ConsensusContextFactory; import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.api.jsonrpc.methods.JsonRpcMethods; @@ -168,26 +167,32 @@ protected ProtocolSchedule createProtocolSchedule() { protected ProtocolContext createProtocolContext( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule, - final ConsensusContextFactory consensusContextFactory) { - return MigratingProtocolContext.init( - blockchain, worldStateArchive, protocolSchedule, consensusContextFactory, badBlockManager); + final ConsensusContext consensusContext) { + return MigratingProtocolContext.create( + blockchain, + worldStateArchive, + consensusContext.as(MigratingConsensusContext.class), + badBlockManager); } @Override protected ConsensusContext createConsensusContext( - final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { + final Blockchain blockchain, + final WorldStateArchive worldStateArchive, + final ProtocolSchedule protocolSchedule) { final List> consensusContextSpecs = besuControllerBuilderSchedule.entrySet().stream() .map( e -> new ForkSpec<>( e.getKey(), - e.getValue().createConsensusContext(protocolContext, protocolSchedule))) + e.getValue() + .createConsensusContext( + blockchain, worldStateArchive, protocolSchedule))) .toList(); final ForksSchedule consensusContextsSchedule = new ForksSchedule<>(consensusContextSpecs); - return new MigratingContext(consensusContextsSchedule); + return new MigratingConsensusContext(consensusContextsSchedule); } @Override 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 1b1bc212ec1..738dcfc5963 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java @@ -70,6 +70,7 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.plugin.services.BesuEvents; import org.hyperledger.besu.util.Subscribers; @@ -319,7 +320,9 @@ protected void validateContext(final ProtocolContext context) { @Override protected BftContext createConsensusContext( - final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { + final Blockchain blockchain, + final WorldStateArchive worldStateArchive, + final ProtocolSchedule protocolSchedule) { final BftConfigOptions ibftConfig = genesisConfigOptions.getBftConfigOptions(); final EpochManager epochManager = new EpochManager(ibftConfig.getEpochLength()); @@ -328,10 +331,7 @@ protected BftContext createConsensusContext( return new BftContext( BlockValidatorProvider.forkingValidatorProvider( - protocolContext.getBlockchain(), - epochManager, - bftBlockInterface().get(), - validatorOverrides), + blockchain, epochManager, bftBlockInterface().get(), validatorOverrides), epochManager, bftBlockInterface().get()); } 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 7ac1d8c35da..e0fbed608ab 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java @@ -29,6 +29,7 @@ import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderValidator; import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; /** The Mainnet besu controller builder. */ public class MainnetBesuControllerBuilder extends BesuControllerBuilder { @@ -78,7 +79,9 @@ protected MiningCoordinator createMiningCoordinator( @Override protected ConsensusContext createConsensusContext( - final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { + final Blockchain blockchain, + final WorldStateArchive worldStateArchive, + final ProtocolSchedule protocolSchedule) { return null; } diff --git a/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java index 03079de42fe..f5fc75959e1 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java @@ -44,6 +44,7 @@ import org.hyperledger.besu.ethereum.forkid.ForkIdManager; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ScheduleBasedBlockHeaderFunctions; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import java.util.List; import java.util.Optional; @@ -183,9 +184,10 @@ protected ProtocolSchedule createProtocolSchedule() { @Override protected MergeContext createConsensusContext( - final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { + final Blockchain blockchain, + final WorldStateArchive worldStateArchive, + final ProtocolSchedule protocolSchedule) { - final var blockchain = protocolContext.getBlockchain(); final OptionalLong terminalBlockNumber = genesisConfigOptions.getTerminalBlockNumber(); final Optional terminalBlockHash = genesisConfigOptions.getTerminalBlockHash(); final boolean isPostMergeAtGenesis = diff --git a/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java index c5c0f5c6720..d4a6c5c1fa1 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java @@ -80,6 +80,7 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.plugin.services.BesuEvents; import org.hyperledger.besu.util.Subscribers; @@ -387,37 +388,27 @@ private boolean signersExistIn(final BlockHeader genesisBlockHeader) { @Override protected BftContext createConsensusContext( - final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { + final Blockchain blockchain, + final WorldStateArchive worldStateArchive, + final ProtocolSchedule protocolSchedule) { final EpochManager epochManager = new EpochManager(qbftConfig.getEpochLength()); final BftValidatorOverrides validatorOverrides = convertBftForks(genesisConfigOptions.getTransitions().getQbftForks()); final BlockValidatorProvider blockValidatorProvider = BlockValidatorProvider.forkingValidatorProvider( - protocolContext.getBlockchain(), - epochManager, - bftBlockInterface().get(), - validatorOverrides); + blockchain, epochManager, bftBlockInterface().get(), validatorOverrides); final TransactionSimulator transactionSimulator = new TransactionSimulator( - protocolContext.getBlockchain(), - protocolContext.getWorldStateArchive(), - protocolSchedule, - miningParameters, - 0L); + blockchain, worldStateArchive, protocolSchedule, miningParameters, 0L); transactionValidatorProvider = new TransactionValidatorProvider( - protocolContext.getBlockchain(), - new ValidatorContractController(transactionSimulator), - qbftForksSchedule); + blockchain, new ValidatorContractController(transactionSimulator), qbftForksSchedule); final ValidatorProvider validatorProvider = new ForkingValidatorProvider( - protocolContext.getBlockchain(), - qbftForksSchedule, - blockValidatorProvider, - transactionValidatorProvider); + blockchain, qbftForksSchedule, blockValidatorProvider, transactionValidatorProvider); return new BftContext(validatorProvider, epochManager, bftBlockInterface().get()); } 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 cbe5e4454f8..3a45135e2a1 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java @@ -24,7 +24,6 @@ import org.hyperledger.besu.cryptoservices.NodeKey; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.ethereum.ConsensusContext; -import org.hyperledger.besu.ethereum.ConsensusContextFactory; import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; @@ -192,21 +191,23 @@ protected ProtocolSchedule createProtocolSchedule() { protected ProtocolContext createProtocolContext( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule, - final ConsensusContextFactory consensusContextFactory) { + final ConsensusContext consensusContext) { final ProtocolContext protocolContext = - super.createProtocolContext( - blockchain, worldStateArchive, protocolSchedule, consensusContextFactory); + super.createProtocolContext(blockchain, worldStateArchive, consensusContext); transitionProtocolSchedule.setProtocolContext(protocolContext); return protocolContext; } @Override protected ConsensusContext createConsensusContext( - final ProtocolContext protocolContext, final ProtocolSchedule protocolSchedule) { + final Blockchain blockchain, + final WorldStateArchive worldStateArchive, + final ProtocolSchedule protocolSchedule) { return new TransitionContext( - preMergeBesuControllerBuilder.createConsensusContext(protocolContext, protocolSchedule), - mergeBesuControllerBuilder.createConsensusContext(protocolContext, protocolSchedule)); + preMergeBesuControllerBuilder.createConsensusContext( + blockchain, worldStateArchive, protocolSchedule), + mergeBesuControllerBuilder.createConsensusContext( + blockchain, worldStateArchive, protocolSchedule)); } @Override diff --git a/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java index 401cdcdab31..e08d1510ddd 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilderTest.java @@ -24,18 +24,20 @@ import org.hyperledger.besu.config.StubGenesisConfigOptions; import org.hyperledger.besu.consensus.common.ForkSpec; import org.hyperledger.besu.consensus.common.ForksSchedule; -import org.hyperledger.besu.consensus.common.MigratingContext; +import org.hyperledger.besu.consensus.common.MigratingConsensusContext; import org.hyperledger.besu.consensus.common.MigratingMiningCoordinator; import org.hyperledger.besu.consensus.common.bft.blockcreation.BftMiningCoordinator; import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; 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.MiningParameters; import org.hyperledger.besu.ethereum.eth.manager.EthProtocolManager; import org.hyperledger.besu.ethereum.eth.sync.state.SyncState; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import java.math.BigInteger; import java.util.Collections; @@ -164,27 +166,28 @@ public void createsMigratingMiningCoordinator() { @Test public void createsMigratingContext() { - final ConsensusContext context1 = Mockito.mock(ConsensusContext.class); - final ConsensusContext context2 = Mockito.mock(ConsensusContext.class); + final ConsensusContext context1 = mock(ConsensusContext.class); + final ConsensusContext context2 = mock(ConsensusContext.class); final Map besuControllerBuilderSchedule = new TreeMap<>(); besuControllerBuilderSchedule.put(0L, besuControllerBuilder1); besuControllerBuilderSchedule.put(10L, besuControllerBuilder2); - when(besuControllerBuilder1.createConsensusContext(any(), any())).thenReturn(context1); - when(besuControllerBuilder2.createConsensusContext(any(), any())).thenReturn(context2); + when(besuControllerBuilder1.createConsensusContext(any(), any(), any())).thenReturn(context1); + when(besuControllerBuilder2.createConsensusContext(any(), any(), any())).thenReturn(context2); final ConsensusScheduleBesuControllerBuilder controllerBuilder = new ConsensusScheduleBesuControllerBuilder(besuControllerBuilderSchedule); final ConsensusContext consensusContext = controllerBuilder.createConsensusContext( - Mockito.mock(ProtocolContext.class), Mockito.mock(ProtocolSchedule.class)); + mock(Blockchain.class), mock(WorldStateArchive.class), mock(ProtocolSchedule.class)); - assertThat(consensusContext).isInstanceOf(MigratingContext.class); - final MigratingContext migratingContext = (MigratingContext) consensusContext; + assertThat(consensusContext).isInstanceOf(MigratingConsensusContext.class); + final MigratingConsensusContext migratingConsensusContext = + (MigratingConsensusContext) consensusContext; final ForksSchedule contextSchedule = - migratingContext.getConsensusContextSchedule(); + migratingConsensusContext.getConsensusContextSchedule(); final NavigableSet> expectedConsensusContextSpecs = new TreeSet<>(ForkSpec.COMPARATOR); 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 5bff87b8b2f..52f961699a0 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java @@ -33,7 +33,6 @@ import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; -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.Block; @@ -55,6 +54,7 @@ import org.hyperledger.besu.ethereum.storage.keyvalue.VariablesKeyValueStorage; import org.hyperledger.besu.ethereum.trie.forest.storage.ForestWorldStateKeyValueStorage; import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; +import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.ethereum.worldstate.WorldStatePreimageStorage; import org.hyperledger.besu.ethereum.worldstate.WorldStateStorageCoordinator; import org.hyperledger.besu.evm.internal.EvmConfiguration; @@ -212,11 +212,10 @@ public void assertTerminalTotalDifficultyInMergeContext() { public void assertConfiguredBlock() { final MutableBlockchain mockChain = mock(MutableBlockchain.class); when(mockChain.getBlockHeader(anyLong())).thenReturn(Optional.of(mock(BlockHeader.class))); - final ProtocolContext mockContext = mock(ProtocolContext.class); - when(mockContext.getBlockchain()).thenReturn(mockChain); + final WorldStateArchive mockState = mock(WorldStateArchive.class); final MergeContext mergeContext = besuControllerBuilder.createConsensusContext( - mockContext, this.besuControllerBuilder.createProtocolSchedule()); + mockChain, mockState, this.besuControllerBuilder.createProtocolSchedule()); assertThat(mergeContext).isNotNull(); assertThat(mergeContext.getTerminalPoWBlock()).isPresent(); } @@ -227,12 +226,11 @@ public void assertBuiltContextMonitorsTTD() { GenesisState.fromConfig( genesisConfigFile, this.besuControllerBuilder.createProtocolSchedule()); final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); - final ProtocolContext mockContext = mock(ProtocolContext.class); - when(mockContext.getBlockchain()).thenReturn(blockchain); + final WorldStateArchive mockState = mock(WorldStateArchive.class); final MergeContext mergeContext = spy( besuControllerBuilder.createConsensusContext( - mockContext, this.besuControllerBuilder.createProtocolSchedule())); + blockchain, mockState, this.besuControllerBuilder.createProtocolSchedule())); assertThat(mergeContext).isNotNull(); final Difficulty over = Difficulty.of(10000L); final Difficulty under = Difficulty.of(10L); @@ -264,11 +262,10 @@ public void assertBuiltContextMonitorsTTD() { public void assertNoFinalizedBlockWhenNotStored() { final MutableBlockchain mockChain = mock(MutableBlockchain.class); when(mockChain.getFinalized()).thenReturn(Optional.empty()); - final ProtocolContext mockContext = mock(ProtocolContext.class); - when(mockContext.getBlockchain()).thenReturn(mockChain); + final WorldStateArchive mockState = mock(WorldStateArchive.class); final MergeContext mergeContext = besuControllerBuilder.createConsensusContext( - mockContext, this.besuControllerBuilder.createProtocolSchedule()); + mockChain, mockState, this.besuControllerBuilder.createProtocolSchedule()); assertThat(mergeContext).isNotNull(); assertThat(mergeContext.getFinalized()).isEmpty(); } @@ -281,11 +278,10 @@ public void assertFinalizedBlockIsPresentWhenStored() { when(mockChain.getFinalized()).thenReturn(Optional.of(finalizedHeader.getHash())); when(mockChain.getBlockHeader(finalizedHeader.getHash())) .thenReturn(Optional.of(finalizedHeader)); - final ProtocolContext mockContext = mock(ProtocolContext.class); - when(mockContext.getBlockchain()).thenReturn(mockChain); + final WorldStateArchive mockState = mock(WorldStateArchive.class); final MergeContext mergeContext = besuControllerBuilder.createConsensusContext( - mockContext, this.besuControllerBuilder.createProtocolSchedule()); + mockChain, mockState, this.besuControllerBuilder.createProtocolSchedule()); assertThat(mergeContext).isNotNull(); assertThat(mergeContext.getFinalized().get()).isEqualTo(finalizedHeader); } diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/NodeCanProduceNextBlockTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/NodeCanProduceNextBlockTest.java index f53b308a0ad..fe12fc33bdc 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/NodeCanProduceNextBlockTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/NodeCanProduceNextBlockTest.java @@ -81,8 +81,7 @@ public void networkWithOneValidatorIsAllowedToCreateConsecutiveBlocks() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create( - blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(blockChain, null, cliqueContext, new BadBlockManager()); headerBuilder.number(1).parentHash(genesisBlock.getHash()); final Block block_1 = createEmptyBlock(proposerKeyPair); @@ -107,8 +106,7 @@ public void networkWithTwoValidatorsIsAllowedToProduceBlockIfNotPreviousBlockPro when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create( - blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(blockChain, null, cliqueContext, new BadBlockManager()); headerBuilder.number(1).parentHash(genesisBlock.getHash()); final Block block_1 = createEmptyBlock(proposerKeyPair); @@ -142,8 +140,7 @@ public void networkWithTwoValidatorsIsNotAllowedToProduceBlockIfIsPreviousBlockP when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create( - blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(blockChain, null, cliqueContext, new BadBlockManager()); headerBuilder.parentHash(genesisBlock.getHash()).number(1); final Block block_1 = createEmptyBlock(proposerKeyPair); @@ -173,8 +170,7 @@ public void withThreeValidatorsMustHaveOneBlockBetweenSignings() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create( - blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(blockChain, null, cliqueContext, new BadBlockManager()); headerBuilder.parentHash(genesisBlock.getHash()).number(1); final Block block_1 = createEmptyBlock(proposerKeyPair); @@ -219,8 +215,7 @@ public void signerIsValidIfInsufficientBlocksExistInHistory() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create( - blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(blockChain, null, cliqueContext, new BadBlockManager()); headerBuilder.parentHash(genesisBlock.getHash()).number(1); final Block block_1 = createEmptyBlock(otherNodeKeyPair); @@ -249,8 +244,7 @@ public void exceptionIsThrownIfOnAnOrphanedChain() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create( - blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(blockChain, null, cliqueContext, new BadBlockManager()); headerBuilder.parentHash(Hash.ZERO).number(3); final BlockHeader parentHeader = @@ -274,8 +268,7 @@ public void nonValidatorIsNotAllowedToCreateABlock() { when(validatorProvider.getValidatorsAfterBlock(any())).thenReturn(validatorList); final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create( - blockChain, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(blockChain, null, cliqueContext, new BadBlockManager()); headerBuilder.parentHash(Hash.ZERO).number(3); final BlockHeader parentHeader = headerBuilder.buildHeader(); 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 065320103bc..7f9884637a5 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 @@ -128,8 +128,7 @@ void setup() { GenesisState.fromConfig(GenesisConfigFile.mainnet(), protocolSchedule).getBlock(); blockchain = createInMemoryBlockchain(genesis); protocolContext = - ProtocolContext.create( - blockchain, stateArchive, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(blockchain, stateArchive, cliqueContext, new BadBlockManager()); epochManager = new EpochManager(10); // Add a block above the genesis diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockMinerTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockMinerTest.java index 3d4d65ab7fa..574cf3a86f8 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockMinerTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/blockcreation/CliqueBlockMinerTest.java @@ -86,7 +86,7 @@ void doesNotMineBlockIfNoTransactionsWhenEmptyBlocksNotAllowed() throws Interrup final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, null); final ProtocolContext protocolContext = - ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(null, null, cliqueContext, new BadBlockManager()); final CliqueBlockCreator blockCreator = mock(CliqueBlockCreator.class); final Function blockCreatorSupplier = @@ -142,7 +142,7 @@ void minesBlockIfHasTransactionsWhenEmptyBlocksNotAllowed() throws InterruptedEx final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, null); final ProtocolContext protocolContext = - ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(null, null, cliqueContext, new BadBlockManager()); final CliqueBlockCreator blockCreator = mock(CliqueBlockCreator.class); final Function blockCreatorSupplier = 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 1c97dbaab73..91b35f5154d 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 @@ -99,7 +99,7 @@ public void setup() { final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(null, null, cliqueContext, new BadBlockManager()); cliqueProtocolSchedule = CliqueProtocolSchedule.create( GENESIS_CONFIG_OPTIONS, diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRuleTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRuleTest.java index a62433653c9..372ac0eca90 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRuleTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueDifficultyValidationRuleTest.java @@ -59,7 +59,7 @@ public void setup() { final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(null, null, cliqueContext, new BadBlockManager()); blockHeaderBuilder = new BlockHeaderTestFixture(); } diff --git a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueExtraDataValidationRuleTest.java b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueExtraDataValidationRuleTest.java index 917034221b2..971b40f5873 100644 --- a/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueExtraDataValidationRuleTest.java +++ b/consensus/clique/src/test/java/org/hyperledger/besu/consensus/clique/headervalidationrules/CliqueExtraDataValidationRuleTest.java @@ -63,7 +63,7 @@ public void setup() { final CliqueContext cliqueContext = new CliqueContext(validatorProvider, null, blockInterface); cliqueProtocolContext = - ProtocolContext.create(null, null, null, (pc, ps) -> cliqueContext, new BadBlockManager()); + ProtocolContext.create(null, null, cliqueContext, new BadBlockManager()); } @Test diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingContext.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingConsensusContext.java similarity index 88% rename from consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingContext.java rename to consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingConsensusContext.java index f71e3ac7f36..91ace1a04b3 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingContext.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingConsensusContext.java @@ -17,7 +17,7 @@ import org.hyperledger.besu.ethereum.ConsensusContext; /** The Migrating context. */ -public class MigratingContext implements ConsensusContext { +public class MigratingConsensusContext implements ConsensusContext { private final ForksSchedule consensusContextSchedule; @@ -26,7 +26,7 @@ public class MigratingContext implements ConsensusContext { * * @param consensusContextSchedule the consensus context schedule */ - public MigratingContext(final ForksSchedule consensusContextSchedule) { + public MigratingConsensusContext(final ForksSchedule consensusContextSchedule) { this.consensusContextSchedule = consensusContextSchedule; } diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingProtocolContext.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingProtocolContext.java index 7651e3c9910..6e22ca1e2cd 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingProtocolContext.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/MigratingProtocolContext.java @@ -15,11 +15,9 @@ package org.hyperledger.besu.consensus.common; import org.hyperledger.besu.ethereum.ConsensusContext; -import org.hyperledger.besu.ethereum.ConsensusContextFactory; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; -import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; /** The Migrating protocol context. */ @@ -32,13 +30,16 @@ public class MigratingProtocolContext extends ProtocolContext { * * @param blockchain the blockchain * @param worldStateArchive the world state archive + * @param migratingConsensusContext the consensus context * @param badBlockManager the cache to use to keep invalid blocks */ private MigratingProtocolContext( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, + final MigratingConsensusContext migratingConsensusContext, final BadBlockManager badBlockManager) { - super(blockchain, worldStateArchive, badBlockManager); + super(blockchain, worldStateArchive, migratingConsensusContext, badBlockManager); + this.consensusContextSchedule = migratingConsensusContext.getConsensusContextSchedule(); } /** @@ -46,29 +47,19 @@ private MigratingProtocolContext( * * @param blockchain the blockchain * @param worldStateArchive the world state archive - * @param protocolSchedule the protocol schedule - * @param consensusContextFactory the consensus context factory * @param badBlockManager the cache to use to keep invalid blocks * @return the protocol context */ - public static MigratingProtocolContext init( + public static MigratingProtocolContext create( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule, - final ConsensusContextFactory consensusContextFactory, + final MigratingConsensusContext migratingConsensusContext, final BadBlockManager badBlockManager) { - final var migratingProtocolContext = - new MigratingProtocolContext(blockchain, worldStateArchive, badBlockManager); - - final ConsensusContext consensusContext = - consensusContextFactory.create(migratingProtocolContext, protocolSchedule); - final MigratingContext migratingContext = consensusContext.as(MigratingContext.class); - migratingProtocolContext.setConsensusContextSchedule( - migratingContext.getConsensusContextSchedule()); - return migratingProtocolContext; + return new MigratingProtocolContext( + blockchain, worldStateArchive, migratingConsensusContext, badBlockManager); } - private void setConsensusContextSchedule( + public void setConsensusContextSchedule( final ForksSchedule consensusContextSchedule) { this.consensusContextSchedule = consensusContextSchedule; } diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/MigratingProtocolContextTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/MigratingProtocolContextTest.java index 0aa60bfcce3..a8807846692 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/MigratingProtocolContextTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/MigratingProtocolContextTest.java @@ -19,7 +19,6 @@ import static org.mockito.Mockito.when; import org.hyperledger.besu.ethereum.ConsensusContext; -import org.hyperledger.besu.ethereum.ConsensusContextFactory; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; @@ -44,12 +43,13 @@ public void returnsContextForSpecificChainHeight() { final ForksSchedule contextSchedule = new ForksSchedule<>(List.of(new ForkSpec<>(0L, context1), new ForkSpec<>(10L, context2))); - final ConsensusContextFactory consensusContextFactory = - (pc, ps) -> new MigratingContext(contextSchedule); final MigratingProtocolContext migratingProtocolContext = - MigratingProtocolContext.init( - blockchain, worldStateArchive, null, consensusContextFactory, new BadBlockManager()); + MigratingProtocolContext.create( + blockchain, + worldStateArchive, + new MigratingConsensusContext(contextSchedule), + new BadBlockManager()); assertThat(migratingProtocolContext.getConsensusContext(ConsensusContext.class)) .isSameAs(context1); diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCoinbaseValidationRuleTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCoinbaseValidationRuleTest.java index a34ad401da8..5f02998aea2 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCoinbaseValidationRuleTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCoinbaseValidationRuleTest.java @@ -52,11 +52,7 @@ public void proposerInValidatorListPassesValidation() { final ProtocolContext context = ProtocolContext.create( - null, - null, - null, - (pc, ps) -> setupContextWithValidators(validators), - new BadBlockManager()); + null, null, setupContextWithValidators(validators), new BadBlockManager()); final BftCoinbaseValidationRule coinbaseValidationRule = new BftCoinbaseValidationRule(); @@ -77,11 +73,7 @@ public void proposerNotInValidatorListFailsValidation() { final ProtocolContext context = ProtocolContext.create( - null, - null, - null, - (pc, ps) -> setupContextWithValidators(validators), - new BadBlockManager()); + null, null, setupContextWithValidators(validators), new BadBlockManager()); final BftCoinbaseValidationRule coinbaseValidationRule = new BftCoinbaseValidationRule(); diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCommitSealsValidationRuleTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCommitSealsValidationRuleTest.java index e1ecf10c4c6..a75701cd481 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCommitSealsValidationRuleTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftCommitSealsValidationRuleTest.java @@ -59,7 +59,7 @@ public void correctlyConstructedHeaderPassesValidation() { final BftContext bftContext = setupContextWithValidators(committerAddresses); final ProtocolContext context = - ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())).thenReturn(committerAddresses); assertThat(commitSealsValidationRule.validate(blockHeader, null, context)).isTrue(); @@ -74,7 +74,7 @@ public void insufficientCommitSealsFailsValidation() { final List
validators = singletonList(committerAddress); final BftContext bftContext = setupContextWithValidators(validators); final ProtocolContext context = - ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())).thenReturn(emptyList()); assertThat(commitSealsValidationRule.validate(blockHeader, null, context)).isFalse(); @@ -92,7 +92,7 @@ public void committerNotInValidatorListFailsValidation() { final BftContext bftContext = setupContextWithValidators(validators); final ProtocolContext context = - ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())) .thenReturn(singletonList(Util.publicKeyToAddress(nonValidatorNodeKey.getPublicKey()))); @@ -140,7 +140,7 @@ public void headerContainsDuplicateSealsFailsValidation() { final BftContext bftContext = setupContextWithValidators(validators); final ProtocolContext context = - ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())) .thenReturn(List.of(committerAddress, committerAddress)); @@ -160,7 +160,7 @@ private boolean subExecution(final int validatorCount, final int committerCount) final BftContext bftContext = setupContextWithValidators(validators); final ProtocolContext context = - ProtocolContext.create(null, null, null, (pc, ps) -> bftContext, new BadBlockManager()); + ProtocolContext.create(null, null, bftContext, new BadBlockManager()); when(bftContext.getBlockInterface().getCommitters(any())) .thenReturn(validators.subList(0, committerCount)); diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftValidatorsValidationRuleTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftValidatorsValidationRuleTest.java index f9380fc38c0..b03220d2f48 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftValidatorsValidationRuleTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftValidatorsValidationRuleTest.java @@ -48,8 +48,7 @@ public void correctlyConstructedHeaderPassesValidation() { ProtocolContext.create( null, null, - null, - (pc, ps) -> setupContextWithBftExtraData(validators, bftExtraData), + setupContextWithBftExtraData(validators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(validators); @@ -67,8 +66,7 @@ public void validatorsInNonAscendingOrderFailValidation() { ProtocolContext.create( null, null, - null, - (pc, ps) -> setupContextWithBftExtraData(validators, bftExtraData), + setupContextWithBftExtraData(validators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(Lists.reverse(validators)); @@ -89,8 +87,7 @@ public void mismatchingReportedValidatorsVsLocallyStoredListFailsValidation() { ProtocolContext.create( null, null, - null, - (pc, ps) -> setupContextWithBftExtraData(storedValidators, bftExtraData), + setupContextWithBftExtraData(storedValidators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(Lists.reverse(reportedValidators)); diff --git a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftVanityDataValidationRuleTest.java b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftVanityDataValidationRuleTest.java index 06c05fcebcd..49fdf3a237e 100644 --- a/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftVanityDataValidationRuleTest.java +++ b/consensus/common/src/test/java/org/hyperledger/besu/consensus/common/bft/headervalidationrules/BftVanityDataValidationRuleTest.java @@ -48,8 +48,7 @@ public boolean headerWithVanityDataOfSize(final int extraDataSize) { ProtocolContext.create( null, null, - null, - (pc, ps) -> setupContextWithBftExtraData(emptyList(), extraData), + setupContextWithBftExtraData(emptyList(), extraData), new BadBlockManager()); return validationRule.validate(blockHeader, null, context); } 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 4264e78b7a7..424f1b91f5a 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 @@ -353,8 +353,7 @@ private static ControllerAndState createControllerAndFinalState( ProtocolContext.create( blockChain, worldStateArchive, - null, - (pc, ps) -> new BftContext(validatorProvider, epochManager, blockInterface), + new BftContext(validatorProvider, epochManager, blockInterface), new BadBlockManager()); final TransactionPoolConfiguration poolConf = ImmutableTransactionPoolConfiguration.builder().txPoolMaxSize(1).build(); diff --git a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/tests/round/IbftRoundIntegrationTest.java b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/tests/round/IbftRoundIntegrationTest.java index 7b180b99cbe..33492a3f69b 100644 --- a/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/tests/round/IbftRoundIntegrationTest.java +++ b/consensus/ibft/src/integration-test/java/org/hyperledger/besu/consensus/ibft/tests/round/IbftRoundIntegrationTest.java @@ -127,8 +127,7 @@ public void setup() { ProtocolContext.create( blockChain, worldStateArchive, - null, - (pc, ps) -> setupContextWithBftExtraDataEncoder(emptyList(), bftExtraDataEncoder), + setupContextWithBftExtraDataEncoder(emptyList(), bftExtraDataEncoder), new BadBlockManager()); } diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactoryTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactoryTest.java index 9c6a6eb6f2b..8fd637d22ad 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactoryTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftBlockHeaderValidationRulesetFactoryTest.java @@ -52,8 +52,7 @@ private ProtocolContext protocolContext(final Collection
validators) { return ProtocolContext.create( null, null, - null, - (pc, ps) -> setupContextWithBftExtraDataEncoder(validators, new IbftExtraDataCodec()), + setupContextWithBftExtraDataEncoder(validators, new IbftExtraDataCodec()), new BadBlockManager()); } diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftProtocolScheduleTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftProtocolScheduleTest.java index 762a8f13bcf..8c9c1255d97 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftProtocolScheduleTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/IbftProtocolScheduleTest.java @@ -126,9 +126,7 @@ private ProtocolContext protocolContext(final Collection
validators) { return ProtocolContext.create( null, null, - null, - (pc, ps) -> - setupContextWithBftExtraDataEncoder(BftContext.class, validators, bftExtraDataCodec), + setupContextWithBftExtraDataEncoder(BftContext.class, validators, bftExtraDataCodec), new BadBlockManager()); } } 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 40c239ccb31..783baf05ddf 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 @@ -130,9 +130,7 @@ public BlockHeaderValidator.Builder createBlockHeaderRuleset( ProtocolContext.create( blockchain, createInMemoryWorldStateArchive(), - null, - (pc, ps) -> - setupContextWithBftExtraDataEncoder(initialValidatorList, bftExtraDataEncoder), + setupContextWithBftExtraDataEncoder(initialValidatorList, bftExtraDataEncoder), new BadBlockManager()); final TransactionPoolConfiguration poolConf = diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftBlockHeightManagerTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftBlockHeightManagerTest.java index 2f914d1a5ec..17cdbff3a27 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftBlockHeightManagerTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftBlockHeightManagerTest.java @@ -175,11 +175,7 @@ public void setup() { protocolContext = ProtocolContext.create( - blockchain, - null, - null, - (pc, ps) -> setupContextWithValidators(validators), - new BadBlockManager()); + blockchain, null, setupContextWithValidators(validators), new BadBlockManager()); final ProtocolScheduleBuilder protocolScheduleBuilder = new ProtocolScheduleBuilder( diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftRoundTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftRoundTest.java index 68bd4dc23e7..6ff99580594 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftRoundTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/statemachine/IbftRoundTest.java @@ -115,8 +115,7 @@ public void setup() { ProtocolContext.create( blockChain, worldStateArchive, - protocolSchedule, - (pc, ps) -> setupContextWithBftExtraDataEncoder(emptyList(), new IbftExtraDataCodec()), + setupContextWithBftExtraDataEncoder(emptyList(), new IbftExtraDataCodec()), new BadBlockManager()); lenient().when(messageValidator.validateProposal(any())).thenReturn(true); diff --git a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/validation/MessageValidatorTest.java b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/validation/MessageValidatorTest.java index 3ad090c58aa..cdba0e6edec 100644 --- a/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/validation/MessageValidatorTest.java +++ b/consensus/ibft/src/test/java/org/hyperledger/besu/consensus/ibft/validation/MessageValidatorTest.java @@ -104,8 +104,7 @@ public void setup() { ProtocolContext.create( mock(MutableBlockchain.class), mock(WorldStateArchive.class), - protocolSchedule, - (pc, ps) -> mockBftCtx, + mockBftCtx, new BadBlockManager()); lenient() 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 937d543f701..d533bd4e8e9 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 @@ -188,12 +188,7 @@ public void setUp() { .thenReturn(genesisState.getBlock().getHeader().getDifficulty().plus(1L)); protocolContext = - ProtocolContext.create( - blockchain, - worldStateArchive, - protocolSchedule, - (pc, ps) -> mergeContext, - badBlockManager); + ProtocolContext.create(blockchain, worldStateArchive, mergeContext, badBlockManager); var mutable = worldStateArchive.getMutable(); genesisState.writeStateTo(mutable); mutable.persist(null); 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 f9b1431a8d4..17111ec2210 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 @@ -76,12 +76,7 @@ public class MergeReorgTest implements MergeGenesisConfigHelper { private final MutableBlockchain blockchain = createInMemoryBlockchain(genesisState.getBlock()); private final EthScheduler ethScheduler = new DeterministicEthScheduler(); private final ProtocolContext protocolContext = - ProtocolContext.create( - blockchain, - worldStateArchive, - mockProtocolSchedule, - (pc, ps) -> mergeContext, - new BadBlockManager()); + ProtocolContext.create(blockchain, worldStateArchive, mergeContext, new BadBlockManager()); private final Address coinbase = genesisAllocations(getPowGenesisConfigFile()).findFirst().get(); private final BlockHeaderTestFixture headerGenerator = new BlockHeaderTestFixture(); 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 762aad41a58..3b0f860100f 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 @@ -461,8 +461,7 @@ private static ControllerAndState createControllerAndFinalState( ProtocolContext.create( blockChain, worldStateArchive, - null, - (pc, ps) -> new BftContext(validatorProvider, epochManager, blockInterface), + new BftContext(validatorProvider, epochManager, blockInterface), new BadBlockManager()); final TransactionPoolConfiguration poolConf = diff --git a/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/test/round/QbftRoundIntegrationTest.java b/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/test/round/QbftRoundIntegrationTest.java index eb6a260014e..80739ee3589 100644 --- a/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/test/round/QbftRoundIntegrationTest.java +++ b/consensus/qbft/src/integration-test/java/org/hyperledger/besu/consensus/qbft/test/round/QbftRoundIntegrationTest.java @@ -129,10 +129,8 @@ public void setup() { ProtocolContext.create( blockChain, worldStateArchive, - null, - (pc, ps) -> - setupContextWithBftExtraDataEncoder( - BftContext.class, emptyList(), qbftExtraDataEncoder), + setupContextWithBftExtraDataEncoder( + BftContext.class, emptyList(), qbftExtraDataEncoder), new BadBlockManager()); } diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftBlockHeaderValidationRulesetFactoryTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftBlockHeaderValidationRulesetFactoryTest.java index 278733896fa..952aa7ad37a 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftBlockHeaderValidationRulesetFactoryTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftBlockHeaderValidationRulesetFactoryTest.java @@ -47,10 +47,7 @@ private ProtocolContext protocolContext(final Collection
validators) { return ProtocolContext.create( null, null, - null, - (pc, ps) -> - setupContextWithBftExtraDataEncoder( - BftContext.class, validators, new QbftExtraDataCodec()), + setupContextWithBftExtraDataEncoder(BftContext.class, validators, new QbftExtraDataCodec()), new BadBlockManager()); } diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftProtocolScheduleTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftProtocolScheduleTest.java index e3e41d79e89..14fe24fe042 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftProtocolScheduleTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/QbftProtocolScheduleTest.java @@ -60,10 +60,7 @@ private ProtocolContext protocolContext(final Collection
validators) { return ProtocolContext.create( null, null, - null, - (pc, ps) -> - setupContextWithBftExtraDataEncoder( - BftContext.class, validators, new QbftExtraDataCodec()), + setupContextWithBftExtraDataEncoder(BftContext.class, validators, new QbftExtraDataCodec()), new BadBlockManager()); } diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/headervalidationrules/QbftValidatorsValidationRuleTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/headervalidationrules/QbftValidatorsValidationRuleTest.java index ead37f40092..062eec6084c 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/headervalidationrules/QbftValidatorsValidationRuleTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/headervalidationrules/QbftValidatorsValidationRuleTest.java @@ -47,10 +47,7 @@ public void validationPassesIfValidatorsAndVoteAreEmpty() { ProtocolContext.create( null, null, - null, - (pc, ps) -> - setupContextWithBftExtraData( - BftContext.class, Collections.emptyList(), bftExtraData), + setupContextWithBftExtraData(BftContext.class, Collections.emptyList(), bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(Collections.emptyList()); when(bftExtraData.getVote()).thenReturn(Optional.empty()); @@ -69,8 +66,7 @@ public void validationIsDelegatedWhenConstructorFlagIsFalse() { ProtocolContext.create( null, null, - null, - (pc, ps) -> setupContextWithBftExtraData(BftContext.class, validators, bftExtraData), + setupContextWithBftExtraData(BftContext.class, validators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(validators); assertThat(qbftValidatorsValidationRule.validate(blockHeader, null, context)).isTrue(); @@ -88,8 +84,7 @@ public void validationFailsIfValidatorsAreNotEmpty() { ProtocolContext.create( null, null, - null, - (pc, ps) -> setupContextWithBftExtraData(BftContext.class, validators, bftExtraData), + setupContextWithBftExtraData(BftContext.class, validators, bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(validators); assertThat(qbftValidatorsValidationRule.validate(blockHeader, null, context)).isFalse(); @@ -103,10 +98,7 @@ public void validationFailsIfVoteIsPresent() { ProtocolContext.create( null, null, - null, - (pc, ps) -> - setupContextWithBftExtraData( - BftContext.class, Collections.emptyList(), bftExtraData), + setupContextWithBftExtraData(BftContext.class, Collections.emptyList(), bftExtraData), new BadBlockManager()); when(bftExtraData.getValidators()).thenReturn(Collections.emptyList()); when(bftExtraData.getVote()).thenReturn(Optional.of(mock(Vote.class))); diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftBlockHeightManagerTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftBlockHeightManagerTest.java index 0cdb4ac2838..86f268cf6d4 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftBlockHeightManagerTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftBlockHeightManagerTest.java @@ -175,10 +175,8 @@ public void setup() { ProtocolContext.create( blockchain, null, - null, - (pc, ps) -> - setupContextWithBftExtraDataEncoder( - BftContext.class, validators, new QbftExtraDataCodec()), + setupContextWithBftExtraDataEncoder( + BftContext.class, validators, new QbftExtraDataCodec()), new BadBlockManager()); final ProtocolScheduleBuilder protocolScheduleBuilder = diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftRoundTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftRoundTest.java index 551e886d2a9..614e28cdffc 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftRoundTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/statemachine/QbftRoundTest.java @@ -121,10 +121,8 @@ public void setup() { ProtocolContext.create( blockChain, worldStateArchive, - protocolSchedule, - (pc, ps) -> - setupContextWithBftExtraDataEncoder( - BftContext.class, emptyList(), new QbftExtraDataCodec()), + setupContextWithBftExtraDataEncoder( + BftContext.class, emptyList(), new QbftExtraDataCodec()), new BadBlockManager()); when(messageValidator.validateProposal(any())).thenReturn(true); diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalPayloadValidatorTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalPayloadValidatorTest.java index e1913540c80..d3af2b63f5e 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalPayloadValidatorTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalPayloadValidatorTest.java @@ -74,10 +74,7 @@ public void setup() { ProtocolContext.create( blockChain, worldStateArchive, - null, - (pc, ps) -> - setupContextWithBftExtraDataEncoder( - BftContext.class, emptyList(), bftExtraDataCodec), + setupContextWithBftExtraDataEncoder(BftContext.class, emptyList(), bftExtraDataCodec), new BadBlockManager()); } diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalValidatorTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalValidatorTest.java index 8712ef62ef1..f543bacc35f 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalValidatorTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/ProposalValidatorTest.java @@ -102,10 +102,7 @@ public void setup() { ProtocolContext.create( blockChain, worldStateArchive, - protocolSchedule, - (pc, ps) -> - setupContextWithBftExtraDataEncoder( - BftContext.class, emptyList(), bftExtraDataEncoder), + setupContextWithBftExtraDataEncoder(BftContext.class, emptyList(), bftExtraDataEncoder), new BadBlockManager()); // typically tests require the blockValidation to be successful diff --git a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/RoundChangeMessageValidatorTest.java b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/RoundChangeMessageValidatorTest.java index a2ae67c3c14..674d7ca0a5f 100644 --- a/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/RoundChangeMessageValidatorTest.java +++ b/consensus/qbft/src/test/java/org/hyperledger/besu/consensus/qbft/validation/RoundChangeMessageValidatorTest.java @@ -84,10 +84,7 @@ public void setup() { ProtocolContext.create( blockChain, worldStateArchive, - protocolSchedule, - (pc, ps) -> - setupContextWithBftExtraDataEncoder( - BftContext.class, emptyList(), bftExtraDataEncoder), + setupContextWithBftExtraDataEncoder(BftContext.class, emptyList(), bftExtraDataEncoder), new BadBlockManager()); lenient().when(protocolSchedule.getByBlockHeader(any())).thenReturn(protocolSpec); 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 16bc63d6328..65938ccdd27 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 @@ -19,6 +19,7 @@ import static org.mockito.Mockito.mock; import org.hyperledger.besu.config.StubGenesisConfigOptions; +import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.api.graphql.GraphQLConfiguration; @@ -86,7 +87,7 @@ public JsonRpcTestMethodsFactory(final BlockchainImporter importer) { this.importer.getGenesisState().writeStateTo(stateArchive.getMutable()); this.context = ProtocolContext.create( - blockchain, stateArchive, null, (pc, ps) -> null, new BadBlockManager()); + blockchain, stateArchive, mock(ConsensusContext.class), new BadBlockManager()); this.protocolSchedule = importer.getProtocolSchedule(); this.synchronizer = mock(Synchronizer.class); diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthGetBlockByNumberLatestDesyncIntegrationTest.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthGetBlockByNumberLatestDesyncIntegrationTest.java index 29949468f52..fe3bc88fe55 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthGetBlockByNumberLatestDesyncIntegrationTest.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthGetBlockByNumberLatestDesyncIntegrationTest.java @@ -20,6 +20,7 @@ import static org.mockito.Mockito.when; import org.hyperledger.besu.datatypes.Hash; +import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.api.jsonrpc.BlockchainImporter; import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcTestMethodsFactory; @@ -68,7 +69,7 @@ public static void setUpOnce() throws Exception { WorldStateArchive state = InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive(); importer.getGenesisState().writeStateTo(state.getMutable()); ProtocolContext context = - ProtocolContext.create(chain, state, null, (pc, ps) -> null, new BadBlockManager()); + ProtocolContext.create(chain, state, mock(ConsensusContext.class), new BadBlockManager()); for (final Block block : importer.getBlocks()) { final ProtocolSchedule protocolSchedule = importer.getProtocolSchedule(); 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 4ff63841f4c..2bc6b9afd29 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 @@ -19,6 +19,7 @@ import org.hyperledger.besu.datatypes.TransactionType; import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; @@ -112,8 +113,7 @@ public void setupTest() throws Exception { ProtocolContext.create( blockchain, blockchainSetupUtil.getWorldArchive(), - blockchainSetupUtil.getProtocolSchedule(), - (pc, ps) -> null, + mock(ConsensusContext.class), new BadBlockManager()); final BlockchainQueries blockchainQueries = new BlockchainQueries( diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockMinerTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockMinerTest.java index 81195c23d1c..0c67e729165 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockMinerTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/BlockMinerTest.java @@ -22,6 +22,7 @@ import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; +import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.blockcreation.BlockCreator.BlockCreationResult; import org.hyperledger.besu.ethereum.blockcreation.txselection.TransactionSelectionResults; @@ -58,7 +59,7 @@ public void blockCreatedIsAddedToBlockChain() throws InterruptedException { headerBuilder.buildHeader(), new BlockBody(Lists.newArrayList(), Lists.newArrayList())); final ProtocolContext protocolContext = - ProtocolContext.create(null, null, null, (pc, ps) -> null, new BadBlockManager()); + ProtocolContext.create(null, null, mock(ConsensusContext.class), new BadBlockManager()); final PoWBlockCreator blockCreator = mock(PoWBlockCreator.class); final Function blockCreatorSupplier = @@ -102,7 +103,7 @@ public void failureToImportDoesNotTriggerObservers() throws InterruptedException headerBuilder.buildHeader(), new BlockBody(Lists.newArrayList(), Lists.newArrayList())); final ProtocolContext protocolContext = - ProtocolContext.create(null, null, null, (pc, ps) -> null, new BadBlockManager()); + ProtocolContext.create(null, null, mock(ConsensusContext.class), new BadBlockManager()); final PoWBlockCreator blockCreator = mock(PoWBlockCreator.class); final Function blockCreatorSupplier = @@ -150,7 +151,7 @@ public void blockValidationFailureBeforeImportDoesNotImportBlock() throws Interr headerBuilder.buildHeader(), new BlockBody(Lists.newArrayList(), Lists.newArrayList())); final ProtocolContext protocolContext = - ProtocolContext.create(null, null, null, (pc, ps) -> null, new BadBlockManager()); + ProtocolContext.create(null, null, mock(ConsensusContext.class), new BadBlockManager()); final PoWBlockCreator blockCreator = mock(PoWBlockCreator.class); final Function blockCreatorSupplier = diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java index 3c7e837f33d..b22f2023d93 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/ProtocolContext.java @@ -17,7 +17,6 @@ import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; import org.hyperledger.besu.ethereum.core.Synchronizer; -import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import java.util.Optional; @@ -30,8 +29,9 @@ public class ProtocolContext { private final MutableBlockchain blockchain; private final WorldStateArchive worldStateArchive; + private final ConsensusContext consensusContext; private final BadBlockManager badBlockManager; - private ConsensusContext consensusContext; + private Synchronizer synchronizer; /** @@ -40,14 +40,17 @@ public class ProtocolContext { * * @param blockchain the blockchain of the protocol context * @param worldStateArchive the world state archive of the protocol context + * @param consensusContext the consensus context * @param badBlockManager the bad block manager of the protocol context */ protected ProtocolContext( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, + final ConsensusContext consensusContext, final BadBlockManager badBlockManager) { this.blockchain = blockchain; this.worldStateArchive = worldStateArchive; + this.consensusContext = consensusContext; this.badBlockManager = badBlockManager; } @@ -57,25 +60,16 @@ protected ProtocolContext( * * @param blockchain the blockchain of the protocol context * @param worldStateArchive the world state archive of the protocol context - * @param protocolSchedule the protocol schedule of the protocol context - * @param consensusContextFactory the consensus context factory of the protocol context + * @param consensusContext the consensus context * @param badBlockManager the bad block manager of the protocol context * @return the new ProtocolContext */ public static ProtocolContext create( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive, - final ProtocolSchedule protocolSchedule, - final ConsensusContextFactory consensusContextFactory, + final ConsensusContext consensusContext, final BadBlockManager badBlockManager) { - final var protocolContext = new ProtocolContext(blockchain, worldStateArchive, badBlockManager); - protocolContext.setConsensusContext( - consensusContextFactory.create(protocolContext, protocolSchedule)); - return protocolContext; - } - - public void setConsensusContext(final ConsensusContext consensusContext) { - this.consensusContext = consensusContext; + return new ProtocolContext(blockchain, worldStateArchive, consensusContext, badBlockManager); } /** diff --git a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java index 6f08a6dd59e..c996672cf41 100644 --- a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java +++ b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/BlockchainSetupUtil.java @@ -160,7 +160,7 @@ private static ProtocolSchedule mainnetProtocolScheduleProvider( private static ProtocolContext mainnetProtocolContextProvider( final MutableBlockchain blockchain, final WorldStateArchive worldStateArchive) { return ProtocolContext.create( - blockchain, worldStateArchive, null, (pc, ps) -> null, new BadBlockManager()); + blockchain, worldStateArchive, new ConsensusContextFixture(), new BadBlockManager()); } private static BlockchainSetupUtil create( diff --git a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ConsensusContextFixture.java b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ConsensusContextFixture.java new file mode 100644 index 00000000000..198b3ab8138 --- /dev/null +++ b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ConsensusContextFixture.java @@ -0,0 +1,24 @@ +/* + * Copyright contributors to Besu. + * + * 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.core; + +import org.hyperledger.besu.ethereum.ConsensusContext; + +public class ConsensusContextFixture implements ConsensusContext { + @Override + public C as(final Class klass) { + return klass.cast(this); + } +} diff --git a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java index 0226394dab5..b51e0c95eac 100644 --- a/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java +++ b/ethereum/core/src/test-support/java/org/hyperledger/besu/ethereum/core/ExecutionContextTestFixture.java @@ -77,7 +77,7 @@ private ExecutionContextTestFixture( this.protocolSchedule = protocolSchedule; this.protocolContext = ProtocolContext.create( - blockchain, stateArchive, protocolSchedule, (pc, ps) -> null, new BadBlockManager()); + blockchain, stateArchive, new ConsensusContextFixture(), new BadBlockManager()); genesisState.writeStateTo(stateArchive.getMutable()); } diff --git a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java index 13c155510f6..21277216966 100644 --- a/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java +++ b/ethereum/core/src/test/java/org/hyperledger/besu/ethereum/trie/diffbased/bonsai/AbstractIsolationTests.java @@ -29,6 +29,7 @@ import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.BlockProcessingResult; +import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.blockcreation.AbstractBlockCreator; import org.hyperledger.besu.ethereum.chain.BadBlockManager; @@ -171,7 +172,8 @@ public void createStorage() { var ws = archive.getMutable(); genesisState.writeStateTo(ws); protocolContext = - ProtocolContext.create(blockchain, archive, null, (pc, ps) -> null, new BadBlockManager()); + ProtocolContext.create( + blockchain, archive, mock(ConsensusContext.class), new BadBlockManager()); ethContext = mock(EthContext.class, RETURNS_DEEP_STUBS); when(ethContext.getEthPeers().subscribeConnect(any())).thenReturn(1L); transactionPool = diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/AbstractBlockPropagationManagerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/AbstractBlockPropagationManagerTest.java index c9a28a97294..15096d180b0 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/AbstractBlockPropagationManagerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/AbstractBlockPropagationManagerTest.java @@ -107,8 +107,7 @@ protected void setup(final DataStorageFormat dataStorageFormat) { ProtocolContext.create( blockchain, tempProtocolContext.getWorldStateArchive(), - null, - (pc, ps) -> tempProtocolContext.getConsensusContext(ConsensusContext.class), + tempProtocolContext.getConsensusContext(ConsensusContext.class), new BadBlockManager()); ethProtocolManager = EthProtocolManagerTestUtil.create( diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncTargetManagerTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncTargetManagerTest.java index c42cf3f8114..e7f382e9915 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncTargetManagerTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/fullsync/FullSyncTargetManagerTest.java @@ -18,6 +18,7 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; +import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.Blockchain; @@ -78,7 +79,7 @@ public void setup(final DataStorageFormat storageFormat) { final ProtocolSchedule protocolSchedule = ProtocolScheduleFixture.MAINNET; final ProtocolContext protocolContext = ProtocolContext.create( - localBlockchain, localWorldState, null, (pc, ps) -> null, new BadBlockManager()); + localBlockchain, localWorldState, mock(ConsensusContext.class), new BadBlockManager()); ethProtocolManager = EthProtocolManagerTestUtil.create( protocolSchedule, diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskParameterizedTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskParameterizedTest.java index 605b4d79fd5..36dd1da096d 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskParameterizedTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskParameterizedTest.java @@ -19,6 +19,7 @@ import static org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider.createInMemoryWorldStateArchive; import static org.mockito.Mockito.mock; +import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; @@ -152,7 +153,10 @@ public void searchesAgainstNetwork(final int headerRequestSize, final int common final EthContext ethContext = ethProtocolManager.ethContext(); final ProtocolContext protocolContext = ProtocolContext.create( - localBlockchain, worldStateArchive, null, (pc, ps) -> null, new BadBlockManager()); + localBlockchain, + worldStateArchive, + mock(ConsensusContext.class), + new BadBlockManager()); final EthTask task = DetermineCommonAncestorTask.create( diff --git a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java index 1de4fb74efd..16c55da6c8c 100644 --- a/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java +++ b/ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/sync/tasks/DetermineCommonAncestorTaskTest.java @@ -27,6 +27,7 @@ import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; +import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.Blockchain; @@ -89,7 +90,10 @@ public void setup() { ethContext = ethProtocolManager.ethContext(); protocolContext = ProtocolContext.create( - localBlockchain, worldStateArchive, null, (pc, ps) -> null, new BadBlockManager()); + localBlockchain, + worldStateArchive, + mock(ConsensusContext.class), + new BadBlockManager()); } @Test 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 e642916936a..bf138db2813 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 @@ -27,6 +27,7 @@ import org.hyperledger.besu.crypto.KeyPair; import org.hyperledger.besu.cryptoservices.NodeKey; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; +import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.GenesisState; @@ -136,7 +137,7 @@ public TestNode( genesisState.writeStateTo(worldStateArchive.getMutable()); final ProtocolContext protocolContext = ProtocolContext.create( - blockchain, worldStateArchive, null, (pc, ps) -> null, new BadBlockManager()); + blockchain, worldStateArchive, mock(ConsensusContext.class), new BadBlockManager()); final SyncState syncState = mock(SyncState.class); final SynchronizerConfiguration syncConfig = mock(SynchronizerConfiguration.class); diff --git a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/BlockchainReferenceTestCaseSpec.java b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/BlockchainReferenceTestCaseSpec.java index bedaf26670f..33d55f9778c 100644 --- a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/BlockchainReferenceTestCaseSpec.java +++ b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/BlockchainReferenceTestCaseSpec.java @@ -20,7 +20,6 @@ import org.hyperledger.besu.datatypes.BlobGas; import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; -import org.hyperledger.besu.ethereum.ConsensusContextFactory; import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.chain.BadBlockManager; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; @@ -28,6 +27,7 @@ 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.ConsensusContextFixture; import org.hyperledger.besu.ethereum.core.Difficulty; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.MutableWorldState; @@ -113,8 +113,7 @@ public BlockchainReferenceTestCaseSpec( ProtocolContext.create( this.blockchain, this.worldStateArchive, - null, - ConsensusContextFactory.NULL, + new ConsensusContextFixture(), new BadBlockManager()); } diff --git a/ethereum/retesteth/build.gradle b/ethereum/retesteth/build.gradle index 2fe2def4396..484953a3919 100644 --- a/ethereum/retesteth/build.gradle +++ b/ethereum/retesteth/build.gradle @@ -35,6 +35,7 @@ dependencies { implementation project(':ethereum:api') implementation project(':ethereum:blockcreation') implementation project(':ethereum:core') + implementation project(path: ':ethereum:core', configuration: 'testSupportArtifacts') implementation project(':ethereum:eth') implementation project(':ethereum:p2p') implementation project(':ethereum:rlp') 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 3b85fda3dd9..54ef11c1372 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.ConsensusContextFixture; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.MutableInitValues; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters.Unstable; @@ -189,7 +190,7 @@ private boolean buildContext( blockchain = createInMemoryBlockchain(genesisState.getBlock()); protocolContext = ProtocolContext.create( - blockchain, worldStateArchive, protocolSchedule, (pc, ps) -> null, badBlockManager); + blockchain, worldStateArchive, new ConsensusContextFixture(), badBlockManager); blockchainQueries = new BlockchainQueries( From d43737792d6a656fbe5aff7e5dc307d8c7d16292 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Mon, 25 Nov 2024 15:39:54 +0100 Subject: [PATCH 4/7] Fix tests Signed-off-by: Fabio Di Fabio --- .../besu/metrics/noop/NoOpMetricsSystem.java | 40 ++----------------- 1 file changed, 3 insertions(+), 37 deletions(-) diff --git a/metrics/core/src/main/java/org/hyperledger/besu/metrics/noop/NoOpMetricsSystem.java b/metrics/core/src/main/java/org/hyperledger/besu/metrics/noop/NoOpMetricsSystem.java index 68b5d52ffa3..f8c63cb2a6f 100644 --- a/metrics/core/src/main/java/org/hyperledger/besu/metrics/noop/NoOpMetricsSystem.java +++ b/metrics/core/src/main/java/org/hyperledger/besu/metrics/noop/NoOpMetricsSystem.java @@ -65,18 +65,6 @@ public class NoOpMetricsSystem implements ObservableMetricsSystem { public static final LabelledMetric NO_OP_LABELLED_1_OPERATION_TIMER = new LabelCountingNoOpMetric<>(1, NO_OP_OPERATION_TIMER); - /** The constant NO_OP_LABELLED_1_GAUGE. */ - public static final LabelledSuppliedMetric NO_OP_LABELLED_1_GAUGE = - new LabelledSuppliedNoOpMetric(1, NO_OP_GAUGE); - - /** The constant NO_OP_LABELLED_2_GAUGE. */ - public static final LabelledSuppliedMetric NO_OP_LABELLED_2_GAUGE = - new LabelledSuppliedNoOpMetric(2, NO_OP_GAUGE); - - /** The constant NO_OP_LABELLED_3_GAUGE. */ - public static final LabelledSuppliedMetric NO_OP_LABELLED_3_GAUGE = - new LabelledSuppliedNoOpMetric(3, NO_OP_GAUGE); - /** Default constructor */ public NoOpMetricsSystem() {} @@ -96,16 +84,7 @@ public LabelledMetric createLabelledCounter( * @return the counter labelled metric */ public static LabelledMetric getCounterLabelledMetric(final int labelCount) { - switch (labelCount) { - case 1: - return NO_OP_LABELLED_1_COUNTER; - case 2: - return NO_OP_LABELLED_2_COUNTER; - case 3: - return NO_OP_LABELLED_3_COUNTER; - default: - return new LabelCountingNoOpMetric<>(labelCount, NO_OP_COUNTER); - } + return new LabelCountingNoOpMetric<>(labelCount, NO_OP_COUNTER); } @Override @@ -141,11 +120,7 @@ public LabelledMetric createLabelledTimer( */ public static LabelledMetric getOperationTimerLabelledMetric( final int labelCount) { - if (labelCount == 1) { - return NO_OP_LABELLED_1_OPERATION_TIMER; - } else { - return new LabelCountingNoOpMetric<>(labelCount, NO_OP_OPERATION_TIMER); - } + return new LabelCountingNoOpMetric<>(labelCount, NO_OP_OPERATION_TIMER); } @Override @@ -184,16 +159,7 @@ public LabelledSuppliedMetric createLabelledSuppliedGauge( * @return the labelled gauge */ public static LabelledSuppliedMetric getLabelledSuppliedMetric(final int labelCount) { - switch (labelCount) { - case 1: - return NO_OP_LABELLED_1_GAUGE; - case 2: - return NO_OP_LABELLED_2_GAUGE; - case 3: - return NO_OP_LABELLED_3_GAUGE; - default: - return new LabelledSuppliedNoOpMetric(labelCount, NO_OP_GAUGE); - } + return new LabelledSuppliedNoOpMetric(labelCount, NO_OP_GAUGE); } @Override From 07ff9521d9e0b69ff689c11873e68c0f8def3e23 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Tue, 26 Nov 2024 15:35:58 +0100 Subject: [PATCH 5/7] TransactionSimulator can be a singleton Signed-off-by: Fabio Di Fabio --- .../dsl/node/ThreadBesuNodeRunner.java | 4 ++- .../org/hyperledger/besu/RunnerBuilder.java | 30 ++++++++++--------- .../org/hyperledger/besu/cli/BesuCommand.java | 20 ++++++------- .../besu/controller/BesuController.java | 17 +++++++++-- .../controller/BesuControllerBuilder.java | 27 ++++++++++++++++- .../controller/QbftBesuControllerBuilder.java | 3 -- .../besu/FlexGroupPrivacyTest.java | 2 ++ .../hyperledger/besu/PrivacyReorgTest.java | 2 ++ .../org/hyperledger/besu/PrivacyTest.java | 2 ++ .../java/org/hyperledger/besu/RunnerTest.java | 1 + .../chainexport/RlpBlockExporterTest.java | 2 ++ .../chainimport/JsonBlockImporterTest.java | 2 ++ .../chainimport/RlpBlockImporterTest.java | 4 +++ .../besu/cli/CommandTestAbstract.java | 1 + .../AbstractBftBesuControllerBuilderTest.java | 4 ++- .../CliqueBesuControllerBuilderTest.java | 4 ++- .../MergeBesuControllerBuilderTest.java | 4 ++- .../jsonrpc/JsonRpcTestMethodsFactory.java | 12 +++++++- .../api/graphql/GraphQLContextType.java | 4 +-- .../pojoadapter/BlockAdapterBase.java | 4 +-- .../pojoadapter/PendingStateAdapter.java | 4 +-- .../jsonrpc/methods/DebugJsonRpcMethods.java | 16 +++------- .../jsonrpc/methods/EthJsonRpcMethods.java | 29 +++++------------- .../methods/JsonRpcMethodsFactory.java | 10 +++++-- .../jsonrpc/methods/TraceJsonRpcMethods.java | 30 ++++--------------- .../AbstractEthGraphQLHttpServiceTest.java | 12 ++++++-- .../AbstractJsonRpcHttpServiceTest.java | 11 ++++++- .../JsonRpcHttpServiceHostAllowlistTest.java | 4 ++- .../jsonrpc/JsonRpcHttpServiceLoginTest.java | 4 ++- .../JsonRpcHttpServiceRpcApisTest.java | 7 +++-- .../jsonrpc/JsonRpcHttpServiceTestBase.java | 4 ++- .../JsonRpcHttpServiceTlsClientAuthTest.java | 4 ++- ...RpcHttpServiceTlsMisconfigurationTest.java | 4 ++- .../jsonrpc/JsonRpcHttpServiceTlsTest.java | 4 ++- .../websocket/WebSocketServiceLoginTest.java | 4 ++- 35 files changed, 180 insertions(+), 116 deletions(-) diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java index 9effaff4d44..0dafbf76fea 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ThreadBesuNodeRunner.java @@ -459,7 +459,8 @@ public BesuController provideBesuController( final BesuControllerBuilder builder, final MetricsSystem metricsSystem, final KeyValueStorageProvider storageProvider, - final MiningConfiguration miningConfiguration) { + final MiningConfiguration miningConfiguration, + final ApiConfiguration apiConfiguration) { builder .synchronizerConfiguration(synchronizerConfiguration) @@ -474,6 +475,7 @@ public BesuController provideBesuController( .maxRemotelyInitiatedPeers(15) .miningParameters(miningConfiguration) .randomPeerPriority(false) + .apiConfiguration(apiConfiguration) .besuComponent(null); return builder.build(); } diff --git a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java index 0f398fae1eb..f26ace21f18 100644 --- a/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java @@ -698,12 +698,7 @@ public Runner build() { final Synchronizer synchronizer = besuController.getSynchronizer(); - final TransactionSimulator transactionSimulator = - new TransactionSimulator( - context.getBlockchain(), - context.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap()); + final TransactionSimulator transactionSimulator = besuController.getTransactionSimulator(); final Bytes localNodeId = nodeKey.getPublicKey().getEncodedBytes(); final Optional nodePermissioningController = @@ -867,7 +862,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); jsonRpcHttpService = Optional.of( @@ -912,7 +908,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); final Optional authToUse = engineJsonRpcConfiguration.get().isAuthenticationEnabled() @@ -959,7 +956,7 @@ public Runner build() { graphQlContextMap.putIfAbsent(GraphQLContextType.SYNCHRONIZER, synchronizer); graphQlContextMap.putIfAbsent( GraphQLContextType.CHAIN_ID, protocolSchedule.getChainId().map(UInt256::valueOf)); - graphQlContextMap.putIfAbsent(GraphQLContextType.GAS_CAP, apiConfiguration.getGasCap()); + graphQlContextMap.putIfAbsent(GraphQLContextType.TRANSACTION_SIMULATOR, transactionSimulator); final GraphQL graphQL; try { graphQL = GraphQLProvider.buildGraphQL(fetchers); @@ -1007,7 +1004,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); createLogsSubscriptionService( context.getBlockchain(), subscriptionManager, privacyParameters, blockchainQueries); @@ -1087,7 +1085,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); jsonRpcIpcService = Optional.of( @@ -1126,7 +1125,8 @@ public Runner build() { natService, besuPluginContext.getNamedPlugins(), dataDir, - rpcEndpointServiceImpl); + rpcEndpointServiceImpl, + transactionSimulator); } else { inProcessRpcMethods = Map.of(); } @@ -1288,7 +1288,8 @@ private Map jsonRpcMethods( final NatService natService, final Map namedPlugins, final Path dataDir, - final RpcEndpointServiceImpl rpcEndpointServiceImpl) { + final RpcEndpointServiceImpl rpcEndpointServiceImpl, + final TransactionSimulator transactionSimulator) { // sync vertx for engine consensus API, to process requests in FIFO order; final Vertx consensusEngineServer = Vertx.vertx(new VertxOptions().setWorkerPoolSize(1)); @@ -1325,7 +1326,8 @@ private Map jsonRpcMethods( besuController.getProtocolManager().ethContext().getEthPeers(), consensusEngineServer, apiConfiguration, - enodeDnsConfiguration); + enodeDnsConfiguration, + transactionSimulator); methods.putAll(besuController.getAdditionalJsonRpcMethods(jsonRpcApis)); final var pluginMethods = 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 e2c657dd18d..4f5f8fbc7ca 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -136,7 +136,6 @@ import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueSegmentIdentifier; import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProvider; import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProviderBuilder; -import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; import org.hyperledger.besu.ethereum.worldstate.DiffBasedSubStorageConfiguration; import org.hyperledger.besu.ethereum.worldstate.ImmutableDataStorageConfiguration; @@ -342,6 +341,8 @@ public class BesuCommand implements DefaultCommandValues, Runnable { Suppliers.memoize(this::readGenesisConfigOptions); private final Supplier miningParametersSupplier = Suppliers.memoize(this::getMiningParameters); + private final Supplier apiConfigurationSupplier = + Suppliers.memoize(this::getApiConfiguration); private RocksDBPlugin rocksDBPlugin; @@ -717,7 +718,6 @@ static class PrivacyOptionGroup { private WebSocketConfiguration webSocketConfiguration; private JsonRpcIpcConfiguration jsonRpcIpcConfiguration; private InProcessRpcConfiguration inProcessRpcConfiguration; - private ApiConfiguration apiConfiguration; private MetricsConfiguration metricsConfiguration; private Optional permissioningConfiguration; private Optional p2pTLSConfiguration; @@ -1244,7 +1244,7 @@ private Runner buildRunner() { webSocketConfiguration, jsonRpcIpcConfiguration, inProcessRpcConfiguration, - apiConfiguration, + apiConfigurationSupplier.get(), metricsConfiguration, permissioningConfiguration, staticNodes, @@ -1256,11 +1256,7 @@ private void startPlugins(final Runner runner) { besuController.getProtocolContext().getBlockchain(), besuController.getProtocolSchedule()); transactionSimulationServiceImpl.init( besuController.getProtocolContext().getBlockchain(), - new TransactionSimulator( - besuController.getProtocolContext().getBlockchain(), - besuController.getProtocolContext().getWorldStateArchive(), - besuController.getProtocolSchedule(), - apiConfiguration.getGasCap())); + besuController.getTransactionSimulator()); rpcEndpointServiceImpl.init(runner.getInProcessRpcMethods()); besuPluginContext.addService( @@ -1454,7 +1450,6 @@ private void validateOptions() { validateTransactionPoolOptions(); validateDataStorageOptions(); validateGraphQlOptions(); - validateApiOptions(); validateConsensusSyncCompatibilityOptions(); validatePluginOptions(); p2pTLSConfigOptions.checkP2PTLSOptionsDependencies(logger, commandLine); @@ -1710,7 +1705,6 @@ private void configure() throws Exception { unstableIpcOptions.getIpcPath(), unstableIpcOptions.getRpcIpcApis()); inProcessRpcConfiguration = inProcessRpcOptions.toDomainObject(); - apiConfiguration = apiConfigurationOptions.apiConfiguration(); dataStorageConfiguration = getDataStorageConfiguration(); // hostsWhitelist is a hidden option. If it is specified, add the list to hostAllowlist if (!hostsWhitelist.isEmpty()) { @@ -1828,6 +1822,7 @@ public BesuControllerBuilder setupControllerBuilder() { .chainPruningConfiguration(unstableChainPruningOptions.toDomainObject()) .cacheLastBlocks(numberOfblocksToCache) .genesisStateHashCacheEnabled(genesisStateHashCacheEnabled) + .apiConfiguration(apiConfigurationSupplier.get()) .besuComponent(besuComponent); if (DataStorageFormat.BONSAI.equals(getDataStorageConfiguration().getDataStorageFormat())) { final DiffBasedSubStorageConfiguration subStorageConfiguration = @@ -2153,6 +2148,11 @@ private MiningConfiguration getMiningParameters() { return miningParameters; } + private ApiConfiguration getApiConfiguration() { + validateApiOptions(); + return apiConfigurationOptions.apiConfiguration(); + } + /** * Get the data storage configuration * diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java index 238e5c3c1c0..25a306d3a29 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuController.java @@ -35,6 +35,7 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; import org.hyperledger.besu.ethereum.storage.StorageProvider; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; import java.io.Closeable; @@ -66,7 +67,6 @@ public class BesuController implements java.io.Closeable { private final NodeKey nodeKey; private final Synchronizer synchronizer; private final JsonRpcMethods additionalJsonRpcMethodsFactory; - private final TransactionPool transactionPool; private final MiningCoordinator miningCoordinator; private final PrivacyParameters privacyParameters; @@ -77,6 +77,7 @@ public class BesuController implements java.io.Closeable { private final EthPeers ethPeers; private final StorageProvider storageProvider; private final DataStorageConfiguration dataStorageConfiguration; + private final TransactionSimulator transactionSimulator; /** * Instantiates a new Besu controller. @@ -99,6 +100,7 @@ public class BesuController implements java.io.Closeable { * @param ethPeers the eth peers * @param storageProvider the storage provider * @param dataStorageConfiguration the data storage configuration + * @param transactionSimulator the transaction simulator */ BesuController( final ProtocolSchedule protocolSchedule, @@ -118,7 +120,8 @@ public class BesuController implements java.io.Closeable { final PluginServiceFactory additionalPluginServices, final EthPeers ethPeers, final StorageProvider storageProvider, - final DataStorageConfiguration dataStorageConfiguration) { + final DataStorageConfiguration dataStorageConfiguration, + final TransactionSimulator transactionSimulator) { this.protocolSchedule = protocolSchedule; this.protocolContext = protocolContext; this.ethProtocolManager = ethProtocolManager; @@ -137,6 +140,7 @@ public class BesuController implements java.io.Closeable { this.ethPeers = ethPeers; this.storageProvider = storageProvider; this.dataStorageConfiguration = dataStorageConfiguration; + this.transactionSimulator = transactionSimulator; } /** @@ -307,6 +311,15 @@ public DataStorageConfiguration getDataStorageConfiguration() { return dataStorageConfiguration; } + /** + * Gets the transaction simulator + * + * @return the transaction simulator + */ + public TransactionSimulator getTransactionSimulator() { + return transactionSimulator; + } + /** The type Builder. */ public static class Builder { /** Instantiates a new Builder. */ diff --git a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java index 96de7a2af0c..fdce6a08e4a 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java @@ -28,6 +28,7 @@ import org.hyperledger.besu.ethereum.ConsensusContext; import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.ProtocolContext; +import org.hyperledger.besu.ethereum.api.ApiConfiguration; import org.hyperledger.besu.ethereum.api.jsonrpc.methods.JsonRpcMethods; import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; import org.hyperledger.besu.ethereum.chain.BadBlockManager; @@ -84,6 +85,7 @@ import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; import org.hyperledger.besu.ethereum.storage.StorageProvider; import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueSegmentIdentifier; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.BonsaiWorldStateProvider; import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.cache.BonsaiCachedMerkleTrieLoader; import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.storage.BonsaiWorldStateKeyValueStorage; @@ -211,6 +213,12 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides /** whether parallel transaction processing is enabled or not */ protected boolean isParallelTxProcessingEnabled; + /** The API configuration */ + protected ApiConfiguration apiConfiguration; + + /** The transaction simulator */ + protected TransactionSimulator transactionSimulator; + /** Instantiates a new Besu controller builder. */ protected BesuControllerBuilder() {} @@ -272,6 +280,17 @@ public BesuControllerBuilder synchronizerConfiguration( return this; } + /** + * API configuration besu controller builder. + * + * @param apiConfiguration the API config + * @return the besu controller builder + */ + public BesuControllerBuilder apiConfiguration(final ApiConfiguration apiConfiguration) { + this.apiConfiguration = apiConfiguration; + return this; + } + /** * Eth protocol configuration besu controller builder. * @@ -556,6 +575,7 @@ public BesuController build() { checkNotNull(gasLimitCalculator, "Missing gas limit calculator"); checkNotNull(evmConfiguration, "Missing evm config"); checkNotNull(networkingConfiguration, "Missing network configuration"); + checkNotNull(apiConfiguration, "Missing API configuration"); checkNotNull(dataStorageConfiguration, "Missing data storage configuration"); checkNotNull(besuComponent, "Must supply a BesuComponent"); prepForBuild(); @@ -604,6 +624,10 @@ public BesuController build() { genesisState.writeStateTo(worldStateArchive.getMutable()); } + transactionSimulator = + new TransactionSimulator( + blockchain, worldStateArchive, protocolSchedule, apiConfiguration.getGasCap()); + final var consensusContext = createConsensusContext(blockchain, worldStateArchive, protocolSchedule); @@ -795,7 +819,8 @@ public BesuController build() { additionalPluginServices, ethPeers, storageProvider, - dataStorageConfiguration); + dataStorageConfiguration, + transactionSimulator); } private GenesisState getGenesisState( diff --git a/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java b/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java index b6f579ea68e..e8c08d8a473 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java @@ -79,7 +79,6 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.config.SubProtocolConfiguration; -import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.plugin.services.BesuEvents; import org.hyperledger.besu.util.Subscribers; @@ -399,8 +398,6 @@ protected BftContext createConsensusContext( BlockValidatorProvider.forkingValidatorProvider( blockchain, epochManager, bftBlockInterface().get(), validatorOverrides); - final TransactionSimulator transactionSimulator = - new TransactionSimulator(blockchain, worldStateArchive, protocolSchedule, 0L); transactionValidatorProvider = new TransactionValidatorProvider( blockchain, new ValidatorContractController(transactionSimulator), qbftForksSchedule); diff --git a/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java b/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java index ff205e87519..bad87162fd2 100644 --- a/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java +++ b/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java @@ -28,6 +28,7 @@ import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.enclave.EnclaveFactory; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; @@ -162,6 +163,7 @@ BesuController provideBesuController( .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .besuComponent(context) + .apiConfiguration(ImmutableApiConfiguration.builder().build()) .build(); } } diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java index a79b6644587..beff4b8586b 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java @@ -41,6 +41,7 @@ import org.hyperledger.besu.enclave.types.ReceiveResponse; import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.ProtocolContext; +import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.chain.DefaultBlockchain; import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockDataGenerator; @@ -558,6 +559,7 @@ BesuController provideBesuController( .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .besuComponent(context) + .apiConfiguration(ImmutableApiConfiguration.builder().build()) .build(); return retval; } diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java index 305d786b8bd..3e905d94416 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java @@ -28,6 +28,7 @@ import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; @@ -137,6 +138,7 @@ BesuController provideBesuController( .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .besuComponent(context) + .apiConfiguration(ImmutableApiConfiguration.builder().build()) .build(); } } diff --git a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java index 4239cbdc344..cf995c25e07 100644 --- a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java +++ b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java @@ -510,6 +510,7 @@ private BesuController getController( .besuComponent(mock(BesuComponent.class)) .maxPeers(25) .maxRemotelyInitiatedPeers(15) + .apiConfiguration(ImmutableApiConfiguration.builder().build()) .build(); } } 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 e76c06fe2d4..a0e596a0005 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java @@ -25,6 +25,7 @@ import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockBody; @@ -105,6 +106,7 @@ private static BesuController createController(final @TempDir Path dataDir) thro .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .besuComponent(mock(BesuComponent.class)) + .apiConfiguration(ImmutableApiConfiguration.builder().build()) .build(); } 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 2b534660ed2..383ef1a3a1a 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java @@ -28,6 +28,7 @@ import org.hyperledger.besu.datatypes.Address; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockBody; @@ -475,6 +476,7 @@ protected BesuController createController(final GenesisConfigFile genesisConfigF .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .besuComponent(DaggerJsonBlockImporterTest_JsonBlockImportComponent.builder().build()) + .apiConfiguration(ImmutableApiConfiguration.builder().build()) .build(); } 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 9f405d4cb39..2f707edc6f4 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java @@ -25,6 +25,7 @@ import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; import org.hyperledger.besu.ethereum.core.MiningConfiguration; import org.hyperledger.besu.ethereum.core.PrivacyParameters; @@ -80,6 +81,7 @@ public void blockImport() throws IOException { .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .besuComponent(mock(BesuComponent.class)) + .apiConfiguration(ImmutableApiConfiguration.builder().build()) .build(); final RlpBlockImporter.ImportResult result = rlpBlockImporter.importBlockchain(source, targetController, false); @@ -114,6 +116,7 @@ public void blockImportRejectsBadPow() throws IOException { .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .besuComponent(mock(BesuComponent.class)) + .apiConfiguration(ImmutableApiConfiguration.builder().build()) .build(); assertThatThrownBy( @@ -145,6 +148,7 @@ public void blockImportCanSkipPow() throws IOException { .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .besuComponent(mock(BesuComponent.class)) + .apiConfiguration(ImmutableApiConfiguration.builder().build()) .build(); final RlpBlockImporter.ImportResult result = 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 72396593985..78f782d5e55 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/CommandTestAbstract.java @@ -296,6 +296,7 @@ public void initMocks() throws Exception { when(mockControllerBuilder.cacheLastBlocks(any())).thenReturn(mockControllerBuilder); when(mockControllerBuilder.genesisStateHashCacheEnabled(any())) .thenReturn(mockControllerBuilder); + when(mockControllerBuilder.apiConfiguration(any())).thenReturn(mockControllerBuilder); when(mockControllerBuilder.build()).thenReturn(mockController); lenient().when(mockController.getProtocolManager()).thenReturn(mockEthProtocolManager); diff --git a/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java index e17fb04acf0..26364087492 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java @@ -29,6 +29,7 @@ import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeader; @@ -158,7 +159,8 @@ public void setup() throws JsonProcessingException { .gasLimitCalculator(gasLimitCalculator) .evmConfiguration(EvmConfiguration.DEFAULT) .besuComponent(mock(BesuComponent.class)) - .networkConfiguration(NetworkingConfiguration.create()); + .networkConfiguration(NetworkingConfiguration.create()) + .apiConfiguration(ImmutableApiConfiguration.builder().build()); } protected abstract void setupBftGenesisConfigFile() throws JsonProcessingException; diff --git a/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java b/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java index 32924e29f92..f05ea666a0d 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java @@ -33,6 +33,7 @@ import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.core.Block; import org.hyperledger.besu.ethereum.core.BlockBody; import org.hyperledger.besu.ethereum.core.BlockHeader; @@ -191,7 +192,8 @@ public void setup() throws JsonProcessingException { .gasLimitCalculator(gasLimitCalculator) .evmConfiguration(EvmConfiguration.DEFAULT) .besuComponent(mock(BesuComponent.class)) - .networkConfiguration(NetworkingConfiguration.create()); + .networkConfiguration(NetworkingConfiguration.create()) + .apiConfiguration(ImmutableApiConfiguration.builder().build()); } @Test 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 47971b6442e..7c4a370beb0 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java @@ -33,6 +33,7 @@ import org.hyperledger.besu.datatypes.Hash; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.GasLimitCalculator; +import org.hyperledger.besu.ethereum.api.ImmutableApiConfiguration; import org.hyperledger.besu.ethereum.chain.Blockchain; import org.hyperledger.besu.ethereum.chain.GenesisState; import org.hyperledger.besu.ethereum.chain.MutableBlockchain; @@ -191,7 +192,8 @@ MergeBesuControllerBuilder visitWithMockConfigs(final MergeBesuControllerBuilder .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .besuComponent(mock(BesuComponent.class)) - .networkId(networkId); + .networkId(networkId) + .apiConfiguration(ImmutableApiConfiguration.builder().build()); } @Test 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 2a65b1e7cb0..f9918036ecb 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 @@ -45,6 +45,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.metrics.ObservableMetricsSystem; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; @@ -77,6 +78,7 @@ public class JsonRpcTestMethodsFactory { private final BlockchainQueries blockchainQueries; private final Synchronizer synchronizer; private final ProtocolSchedule protocolSchedule; + private final TransactionSimulator transactionSimulator; public JsonRpcTestMethodsFactory(final BlockchainImporter importer) { this.importer = importer; @@ -98,6 +100,9 @@ public JsonRpcTestMethodsFactory(final BlockchainImporter importer) { this.blockchainQueries = new BlockchainQueries( protocolSchedule, blockchain, stateArchive, MiningConfiguration.newDefault()); + + this.transactionSimulator = + new TransactionSimulator(blockchain, stateArchive, protocolSchedule, 0L); } public JsonRpcTestMethodsFactory( @@ -117,6 +122,8 @@ public JsonRpcTestMethodsFactory( stateArchive, MiningConfiguration.newDefault()); this.synchronizer = mock(Synchronizer.class); + this.transactionSimulator = + new TransactionSimulator(blockchain, stateArchive, protocolSchedule, 0L); } public JsonRpcTestMethodsFactory( @@ -137,6 +144,8 @@ public JsonRpcTestMethodsFactory( blockchain, stateArchive, MiningConfiguration.newDefault()); + this.transactionSimulator = + new TransactionSimulator(blockchain, stateArchive, protocolSchedule, 0L); } public BlockchainQueries getBlockchainQueries() { @@ -219,6 +228,7 @@ public Map methods() { ethPeers, Vertx.vertx(new VertxOptions().setWorkerPoolSize(1)), ImmutableApiConfiguration.builder().build(), - Optional.empty()); + Optional.empty(), + transactionSimulator); } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/GraphQLContextType.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/GraphQLContextType.java index c12f7578c6c..f689f191e6c 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/GraphQLContextType.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/GraphQLContextType.java @@ -41,6 +41,6 @@ public enum GraphQLContextType { /** Represents chain ID context. */ CHAIN_ID, - /** Represents gas cap context. */ - GAS_CAP + /** Represents the transaction simulator. */ + TRANSACTION_SIMULATOR } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/BlockAdapterBase.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/BlockAdapterBase.java index 6d5b696353a..945727fda24 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/BlockAdapterBase.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/BlockAdapterBase.java @@ -332,10 +332,8 @@ private Optional executeCall(final DataFetchingEnvironment environme final ProtocolSchedule protocolSchedule = environment.getGraphQlContext().get(GraphQLContextType.PROTOCOL_SCHEDULE); final long bn = header.getNumber(); - final long gasCap = environment.getGraphQlContext().get(GraphQLContextType.GAS_CAP); final TransactionSimulator transactionSimulator = - new TransactionSimulator( - query.getBlockchain(), query.getWorldStateArchive(), protocolSchedule, gasCap); + environment.getGraphQlContext().get(GraphQLContextType.TRANSACTION_SIMULATOR); long gasParam = -1; Wei gasPriceParam = null; diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/PendingStateAdapter.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/PendingStateAdapter.java index 49f6bc890f9..9ec80fbedd0 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/PendingStateAdapter.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/pojoadapter/PendingStateAdapter.java @@ -145,10 +145,8 @@ public Optional getCall(final DataFetchingEnvironment environment) { final BlockchainQueries query = getBlockchainQueries(environment); final ProtocolSchedule protocolSchedule = environment.getGraphQlContext().get(GraphQLContextType.PROTOCOL_SCHEDULE); - final long gasCap = environment.getGraphQlContext().get(GraphQLContextType.GAS_CAP); final TransactionSimulator transactionSimulator = - new TransactionSimulator( - query.getBlockchain(), query.getWorldStateArchive(), protocolSchedule, gasCap); + environment.getGraphQlContext().get(GraphQLContextType.TRANSACTION_SIMULATOR); long gasParam = -1; Wei gasPriceParam = null; diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/DebugJsonRpcMethods.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/DebugJsonRpcMethods.java index 90ae97c5c4f..9ca0bb6c1a4 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/DebugJsonRpcMethods.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/DebugJsonRpcMethods.java @@ -15,7 +15,6 @@ package org.hyperledger.besu.ethereum.api.jsonrpc.methods; import org.hyperledger.besu.ethereum.ProtocolContext; -import org.hyperledger.besu.ethereum.api.ApiConfiguration; import org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.DebugReplayBlock; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.DebugAccountAt; @@ -64,7 +63,7 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods { private final TransactionPool transactionPool; private final Synchronizer synchronizer; private final Path dataDir; - private final ApiConfiguration apiConfiguration; + private final TransactionSimulator transactionSimulator; DebugJsonRpcMethods( final BlockchainQueries blockchainQueries, @@ -74,7 +73,7 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods { final TransactionPool transactionPool, final Synchronizer synchronizer, final Path dataDir, - final ApiConfiguration apiConfiguration) { + final TransactionSimulator transactionSimulator) { this.blockchainQueries = blockchainQueries; this.protocolContext = protocolContext; this.protocolSchedule = protocolSchedule; @@ -82,7 +81,7 @@ public class DebugJsonRpcMethods extends ApiGroupJsonRpcMethods { this.transactionPool = transactionPool; this.synchronizer = synchronizer; this.dataDir = dataDir; - this.apiConfiguration = apiConfiguration; + this.transactionSimulator = transactionSimulator; } @Override @@ -120,13 +119,6 @@ protected Map create() { new DebugGetRawBlock(blockchainQueries), new DebugGetRawReceipts(blockchainQueries), new DebugGetRawTransaction(blockchainQueries), - new DebugTraceCall( - blockchainQueries, - protocolSchedule, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap()))); + new DebugTraceCall(blockchainQueries, protocolSchedule, transactionSimulator)); } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthJsonRpcMethods.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthJsonRpcMethods.java index de5662692ff..0ddcb564963 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthJsonRpcMethods.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/EthJsonRpcMethods.java @@ -89,6 +89,7 @@ public class EthJsonRpcMethods extends ApiGroupJsonRpcMethods { private final MiningCoordinator miningCoordinator; private final Set supportedCapabilities; private final ApiConfiguration apiConfiguration; + private final TransactionSimulator transactionSimulator; public EthJsonRpcMethods( final BlockchainQueries blockchainQueries, @@ -98,7 +99,8 @@ public EthJsonRpcMethods( final TransactionPool transactionPool, final MiningCoordinator miningCoordinator, final Set supportedCapabilities, - final ApiConfiguration apiConfiguration) { + final ApiConfiguration apiConfiguration, + final TransactionSimulator transactionSimulator) { this.blockchainQueries = blockchainQueries; this.synchronizer = synchronizer; this.protocolSchedule = protocolSchedule; @@ -107,6 +109,7 @@ public EthJsonRpcMethods( this.miningCoordinator = miningCoordinator; this.supportedCapabilities = supportedCapabilities; this.apiConfiguration = apiConfiguration; + this.transactionSimulator = transactionSimulator; } @Override @@ -125,13 +128,7 @@ protected Map create() { new EthGetBlockReceipts(blockchainQueries, protocolSchedule), new EthGetBlockTransactionCountByNumber(blockchainQueries), new EthGetBlockTransactionCountByHash(blockchainQueries), - new EthCall( - blockchainQueries, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), + new EthCall(blockchainQueries, transactionSimulator), new EthFeeHistory(protocolSchedule, blockchainQueries, miningCoordinator, apiConfiguration), new EthGetCode(blockchainQueries), new EthGetLogs(blockchainQueries, apiConfiguration.getMaxLogsRange()), @@ -155,20 +152,8 @@ protected Map create() { new EthGetStorageAt(blockchainQueries), new EthSendRawTransaction(transactionPool), new EthSendTransaction(), - new EthEstimateGas( - blockchainQueries, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), - new EthCreateAccessList( - blockchainQueries, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), + new EthEstimateGas(blockchainQueries, transactionSimulator), + new EthCreateAccessList(blockchainQueries, transactionSimulator), new EthMining(miningCoordinator), new EthCoinbase(miningCoordinator), new EthProtocolVersion(supportedCapabilities), 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 2e68576fca7..476da3ee304 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 @@ -36,6 +36,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.ObservableMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -85,7 +86,8 @@ public Map methods( final EthPeers ethPeers, final Vertx consensusEngineServer, final ApiConfiguration apiConfiguration, - final Optional enodeDnsConfiguration) { + final Optional enodeDnsConfiguration, + final TransactionSimulator transactionSimulator) { final Map enabled = new HashMap<>(); if (!rpcApis.isEmpty()) { final JsonRpcMethod modules = new RpcModules(rpcApis); @@ -111,7 +113,7 @@ public Map methods( transactionPool, synchronizer, dataDir, - apiConfiguration), + transactionSimulator), new EeaJsonRpcMethods( blockchainQueries, protocolSchedule, transactionPool, privacyParameters), new ExecutionEngineJsonRpcMethods( @@ -131,7 +133,8 @@ public Map methods( transactionPool, miningCoordinator, supportedCapabilities, - apiConfiguration), + apiConfiguration, + transactionSimulator), new NetJsonRpcMethods( p2pNetwork, networkId, @@ -155,6 +158,7 @@ public Map methods( protocolSchedule, protocolContext, apiConfiguration, + transactionSimulator, metricsSystem), new TxPoolJsonRpcMethods(transactionPool), new PluginsJsonRpcMethods(namedPlugins)); diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/TraceJsonRpcMethods.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/TraceJsonRpcMethods.java index 4638e90a625..0a2c090e5a5 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/TraceJsonRpcMethods.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/TraceJsonRpcMethods.java @@ -41,6 +41,7 @@ public class TraceJsonRpcMethods extends ApiGroupJsonRpcMethods { private final ProtocolSchedule protocolSchedule; private final ApiConfiguration apiConfiguration; private final ProtocolContext protocolContext; + private final TransactionSimulator transactionSimulator; private final MetricsSystem metricsSystem; TraceJsonRpcMethods( @@ -48,11 +49,13 @@ public class TraceJsonRpcMethods extends ApiGroupJsonRpcMethods { final ProtocolSchedule protocolSchedule, final ProtocolContext protocolContext, final ApiConfiguration apiConfiguration, + final TransactionSimulator transactionSimulator, final MetricsSystem metricsSystem) { this.blockchainQueries = blockchainQueries; this.protocolSchedule = protocolSchedule; this.protocolContext = protocolContext; this.apiConfiguration = apiConfiguration; + this.transactionSimulator = transactionSimulator; this.metricsSystem = metricsSystem; } @@ -76,29 +79,8 @@ protected Map create() { new TraceTransaction( () -> new BlockTracer(blockReplay), protocolSchedule, blockchainQueries), new TraceBlock(protocolSchedule, blockchainQueries, metricsSystem), - new TraceCall( - blockchainQueries, - protocolSchedule, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), - new TraceCallMany( - blockchainQueries, - protocolSchedule, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap())), - new TraceRawTransaction( - protocolSchedule, - blockchainQueries, - new TransactionSimulator( - blockchainQueries.getBlockchain(), - blockchainQueries.getWorldStateArchive(), - protocolSchedule, - apiConfiguration.getGasCap()))); + new TraceCall(blockchainQueries, protocolSchedule, transactionSimulator), + new TraceCallMany(blockchainQueries, protocolSchedule, transactionSimulator), + new TraceRawTransaction(protocolSchedule, blockchainQueries, transactionSimulator)); } } 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 08cfc3d7bd4..4aad65f43c8 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 @@ -38,6 +38,7 @@ import org.hyperledger.besu.ethereum.mainnet.ValidationResult; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.plugin.data.SyncStatus; import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; @@ -135,6 +136,13 @@ public void setupTest() throws Exception { final GraphQLDataFetchers dataFetchers = new GraphQLDataFetchers(supportedCapabilities); final GraphQL graphQL = GraphQLProvider.buildGraphQL(dataFetchers); + final var transactionSimulator = + new TransactionSimulator( + blockchain, + blockchainSetupUtil.getWorldArchive(), + blockchainSetupUtil.getProtocolSchedule(), + 0L); + service = new GraphQLHttpService( vertx, @@ -152,8 +160,8 @@ public void setupTest() throws Exception { miningCoordinatorMock, GraphQLContextType.SYNCHRONIZER, synchronizerMock, - GraphQLContextType.GAS_CAP, - 0L), + GraphQLContextType.TRANSACTION_SIMULATOR, + transactionSimulator), mock(EthScheduler.class)); service.start().join(); 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 db896a94856..75f84e1333f 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 @@ -46,6 +46,7 @@ import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.transaction.TransactionInvalidReason; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -169,6 +170,13 @@ protected Map getRpcMethods( final NatService natService = new NatService(Optional.empty()); + final var transactionSimulator = + new TransactionSimulator( + blockchainSetupUtil.getBlockchain(), + blockchainSetupUtil.getWorldArchive(), + blockchainSetupUtil.getProtocolSchedule(), + 0L); + return new JsonRpcMethodsFactory() .methods( CLIENT_NODE_NAME, @@ -201,7 +209,8 @@ protected Map getRpcMethods( mock(EthPeers.class), syncVertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + transactionSimulator); } protected void startService() throws Exception { 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 9113e15a12d..b3f650302a9 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 @@ -41,6 +41,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -138,7 +139,8 @@ public void initServerAndClient() throws Exception { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); service = createJsonRpcHttpService(); service.start().join(); 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 aacf1157965..72e947436dd 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 @@ -46,6 +46,7 @@ import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -169,7 +170,8 @@ public static void initServerAndClient() throws Exception { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); service = createJsonRpcHttpService(); jwtAuth = service.authenticationService.get().getJwtAuthProvider(); service.start().join(); 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 ae66f2ac760..4db5c019c3e 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 @@ -51,6 +51,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -235,7 +236,8 @@ private JsonRpcHttpService createJsonRpcHttpServiceWithRpcApis(final JsonRpcConf mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); final JsonRpcHttpService jsonRpcHttpService = new JsonRpcHttpService( vertx, @@ -346,7 +348,8 @@ private JsonRpcHttpService createJsonRpcHttpService( mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); final JsonRpcHttpService jsonRpcHttpService = new JsonRpcHttpService( vertx, 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 ec4f6c6e2b4..6f67cdeb3f9 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 @@ -41,6 +41,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.evm.internal.EvmConfiguration; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; @@ -147,7 +148,8 @@ public static void initServerAndClient() throws Exception { ethPeersMock, vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); disabledRpcMethods = new HashMap<>(); addedRpcMethods = new HashSet<>(); 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 fa336169b9a..d1348e5327e 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 @@ -48,6 +48,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -152,7 +153,8 @@ public void initServer() throws Exception { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); System.setProperty("javax.net.ssl.trustStore", CLIENT_AS_CA_CERT.getKeyStoreFile().toString()); System.setProperty( 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 b675430c49e..dfa519f7464 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 @@ -47,6 +47,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -140,7 +141,8 @@ public void beforeEach() { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); } @AfterEach 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 de5683ad5c0..705ccdd994c 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 @@ -47,6 +47,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; import org.hyperledger.besu.ethereum.permissioning.AccountLocalConfigPermissioningController; import org.hyperledger.besu.ethereum.permissioning.NodeLocalConfigPermissioningController; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -141,7 +142,8 @@ public void initServer() throws Exception { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty()); + Optional.empty(), + mock(TransactionSimulator.class)); service = createJsonRpcHttpService(createJsonRpcConfig()); service.start().join(); baseUrl = service.url(); 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 53785012d09..e1a5b1a75fd 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 @@ -54,6 +54,7 @@ import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule; import org.hyperledger.besu.ethereum.p2p.network.P2PNetwork; import org.hyperledger.besu.ethereum.p2p.rlpx.wire.Capability; +import org.hyperledger.besu.ethereum.transaction.TransactionSimulator; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.nat.NatService; @@ -205,7 +206,8 @@ public void before() throws URISyntaxException { mock(EthPeers.class), vertx, mock(ApiConfiguration.class), - Optional.empty())); + Optional.empty(), + mock(TransactionSimulator.class))); websocketMethods.putAll(rpcMethods); webSocketMessageHandlerSpy = From fad0f1b5acb88e0971425490a3d6bb291fc1b104 Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Wed, 27 Nov 2024 17:48:15 +0100 Subject: [PATCH 6/7] Keep `TransactionSimulationService` backward compatible Signed-off-by: Fabio Di Fabio --- .../TransactionSimulationServiceImpl.java | 10 --- plugin-api/build.gradle | 2 +- .../TransactionSimulationService.java | 73 +++++++++++++++++-- 3 files changed, 66 insertions(+), 19 deletions(-) diff --git a/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java index dd4a625d5f6..487ce031463 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java @@ -57,16 +57,6 @@ public void init(final Blockchain blockchain, final TransactionSimulator transac this.transactionSimulator = transactionSimulator; } - @Override - public Optional simulate( - final Transaction transaction, - final Optional maybeBlockHash, - final OperationTracer operationTracer, - final boolean isAllowExceedingBalance) { - return simulate( - transaction, Optional.empty(), maybeBlockHash, operationTracer, isAllowExceedingBalance); - } - @Override public Optional simulate( final Transaction transaction, diff --git a/plugin-api/build.gradle b/plugin-api/build.gradle index 07ff31d94ff..f0b0e168d0a 100644 --- a/plugin-api/build.gradle +++ b/plugin-api/build.gradle @@ -71,7 +71,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 = '39Mwb1gRxQsWdqUAkKIwEWuYfd6LtNN3ybwXx8HsKVk=' + knownHash = 'LXDYOiCFdCRrQ+9iaFtn421IzWI7hMNShp9n6eEui/k=' } check.dependsOn('checkAPIChanges') diff --git a/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/TransactionSimulationService.java b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/TransactionSimulationService.java index d7121642531..63f5df88260 100644 --- a/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/TransactionSimulationService.java +++ b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/TransactionSimulationService.java @@ -26,10 +26,13 @@ /** Transaction simulation service interface */ @Unstable public interface TransactionSimulationService extends BesuService { + /** - * Simulate transaction execution at the block identified by the hash + * Simulate transaction execution at the block identified by the hash if present, otherwise on the + * pending block, with optional state overrides that can be applied before the simulation. * * @param transaction tx + * @param accountOverrides state overrides to apply to this simulation * @param maybeBlockHash optional hash of the block, empty to simulate on pending block * @param operationTracer the tracer * @param isAllowExceedingBalance should ignore the sender balance during the simulation? @@ -37,24 +40,78 @@ public interface TransactionSimulationService extends BesuService { */ Optional simulate( Transaction transaction, + Optional accountOverrides, Optional maybeBlockHash, OperationTracer operationTracer, boolean isAllowExceedingBalance); + /** + * Simulate transaction execution at the block identified by the hash if present, otherwise on the + * pending block + * + * @param transaction tx + * @param maybeBlockHash optional hash of the block, empty to simulate on pending block + * @param operationTracer the tracer + * @param isAllowExceedingBalance should ignore the sender balance during the simulation? + * @return the result of the simulation + */ + default Optional simulate( + final Transaction transaction, + final Optional maybeBlockHash, + final OperationTracer operationTracer, + final boolean isAllowExceedingBalance) { + return simulate( + transaction, Optional.empty(), maybeBlockHash, operationTracer, isAllowExceedingBalance); + } + /** * Simulate transaction execution at the block identified by the hash * * @param transaction tx + * @param blockHash then hash of the block + * @param operationTracer the tracer + * @param isAllowExceedingBalance should ignore the sender balance during the simulation? + * @return the result of the simulation + * @deprecated use {@link #simulate(Transaction, Optional, OperationTracer, boolean)} + */ + @Deprecated(since = "24.11", forRemoval = true) + default Optional simulate( + final Transaction transaction, + final Hash blockHash, + final OperationTracer operationTracer, + final boolean isAllowExceedingBalance) { + return simulate( + transaction, + Optional.empty(), + Optional.of(blockHash), + operationTracer, + isAllowExceedingBalance); + } + + /** + * Simulate transaction execution at the block identified by the hash, with optional state + * overrides that can be applied before the simulation. + * + * @param transaction tx * @param accountOverrides state overrides to apply to this simulation - * @param maybeBlockHash optional hash of the block, empty to simulate on pending block + * @param blockHash then hash of the block * @param operationTracer the tracer * @param isAllowExceedingBalance should ignore the sender balance during the simulation? * @return the result of the simulation + * @deprecated use {@link #simulate(Transaction, Optional, Optional, OperationTracer, boolean)} */ - Optional simulate( - Transaction transaction, - Optional accountOverrides, - Optional maybeBlockHash, - OperationTracer operationTracer, - boolean isAllowExceedingBalance); + @Deprecated(since = "24.11", forRemoval = true) + default Optional simulate( + final Transaction transaction, + final Optional accountOverrides, + final Hash blockHash, + final OperationTracer operationTracer, + final boolean isAllowExceedingBalance) { + return simulate( + transaction, + accountOverrides, + Optional.of(blockHash), + operationTracer, + isAllowExceedingBalance); + } } From 2850b1529362eb2bb9185c58625043333269333b Mon Sep 17 00:00:00 2001 From: Fabio Di Fabio Date: Thu, 28 Nov 2024 12:41:51 +0100 Subject: [PATCH 7/7] Adjust overriding the state Signed-off-by: Fabio Di Fabio --- .../internal/methods/AbstractEstimateGas.java | 25 ++++++++++++++++--- .../internal/methods/EthCreateAccessList.java | 2 +- .../internal/methods/EthEstimateGas.java | 15 ----------- .../methods/EthCreateAccessListTest.java | 23 +++++++++++------ 4 files changed, 37 insertions(+), 28 deletions(-) diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractEstimateGas.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractEstimateGas.java index 9371abfb1f9..d72f5187b9e 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractEstimateGas.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractEstimateGas.java @@ -16,10 +16,12 @@ import static org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonCallParameterUtil.validateAndGetCallParams; +import org.hyperledger.besu.datatypes.AccountOverrideMap; import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcErrorConverter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcRequestException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonCallParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter; @@ -41,6 +43,8 @@ import java.util.Optional; +import com.google.common.annotations.VisibleForTesting; + public abstract class AbstractEstimateGas extends AbstractBlockParameterMethod { protected static final TransactionValidationParams ALLOW_EXCEEDING_BALANCE_VALIDATION_PARAMETERS = ImmutableTransactionValidationParams.builder() @@ -78,11 +82,12 @@ protected abstract Object simulate( protected Object pendingResult(final JsonRpcRequestContext requestContext) { final JsonCallParameter jsonCallParameter = validateAndGetCallParams(requestContext); final var validationParams = getTransactionValidationParams(jsonCallParameter); + final var maybeStateOverrides = getAddressAccountOverrideMap(requestContext); final var pendingBlockHeader = transactionSimulator.simulatePendingBlockHeader(); final TransactionSimulationFunction simulationFunction = (cp, op) -> transactionSimulator.processOnPending( - cp, Optional.empty(), validationParams, op, pendingBlockHeader); + cp, maybeStateOverrides, validationParams, op, pendingBlockHeader); return simulate( requestContext, jsonCallParameter, pendingBlockHeader.getGasLimit(), simulationFunction); } @@ -104,10 +109,11 @@ private Object resultByBlockHeader( final JsonCallParameter jsonCallParameter, final BlockHeader blockHeader) { final var validationParams = getTransactionValidationParams(jsonCallParameter); + final var maybeStateOverrides = getAddressAccountOverrideMap(requestContext); final TransactionSimulationFunction simulationFunction = (cp, op) -> - transactionSimulator.processOnPending( - cp, Optional.empty(), validationParams, op, blockHeader); + transactionSimulator.process( + cp, maybeStateOverrides, validationParams, op, blockHeader); return simulate( requestContext, jsonCallParameter, blockHeader.getGasLimit(), simulationFunction); } @@ -214,8 +220,19 @@ protected static TransactionValidationParams getTransactionValidationParams( return TransactionValidationParams.transactionSimulator(); } + @VisibleForTesting + protected Optional getAddressAccountOverrideMap( + final JsonRpcRequestContext request) { + try { + return request.getOptionalParameter(2, AccountOverrideMap.class); + } catch (JsonRpcParameter.JsonRpcParameterException e) { + throw new InvalidJsonRpcRequestException( + "Invalid account overrides parameter (index 2)", RpcErrorType.INVALID_CALL_PARAMS, e); + } + } + protected interface TransactionSimulationFunction { Optional simulate( - final CallParameter callParams, final OperationTracer operationTracer); + CallParameter callParams, OperationTracer operationTracer); } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessList.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessList.java index b4870b555ec..7d4ba313cf1 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessList.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessList.java @@ -52,7 +52,7 @@ protected Object simulate( final AccessListOperationTracer tracer = AccessListOperationTracer.create(); final Optional firstResult = - simulationFunction.simulate(callParams, tracer); + simulationFunction.simulate(overrideGasLimit(callParams, gasLimit), tracer); // if the call accessList is different from the simulation result, calculate gas and return if (shouldProcessWithAccessListOverride(callParams, tracer)) { diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthEstimateGas.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthEstimateGas.java index 23c7e12e838..05d5f78e0ff 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthEstimateGas.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthEstimateGas.java @@ -14,11 +14,8 @@ */ package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods; -import org.hyperledger.besu.datatypes.AccountOverrideMap; 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.exception.InvalidJsonRpcRequestException; -import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.Quantity; @@ -30,7 +27,6 @@ import java.util.Optional; -import com.google.common.annotations.VisibleForTesting; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -109,15 +105,4 @@ private Optional validateSimulationResult( } return Optional.empty(); } - - @VisibleForTesting - protected Optional getAddressAccountOverrideMap( - final JsonRpcRequestContext request) { - try { - return request.getOptionalParameter(2, AccountOverrideMap.class); - } catch (JsonRpcParameter.JsonRpcParameterException e) { - throw new InvalidJsonRpcRequestException( - "Invalid account overrides parameter (index 2)", RpcErrorType.INVALID_CALL_PARAMS, e); - } - } } diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessListTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessListTest.java index f7c0c31914f..93d45a959cf 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessListTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCreateAccessListTest.java @@ -186,7 +186,8 @@ public void shouldReturnEmptyAccessListIfNoParameterAndWithoutAccessedStorage() mockTransactionSimulatorResult(true, false, 1L, latestBlockHeader); assertThat(method.response(request)).usingRecursiveComparison().isEqualTo(expectedResponse); - verify(transactionSimulator, times(1)).process(any(), any(), any(), eq(latestBlockHeader)); + verify(transactionSimulator, times(1)) + .process(any(), eq(Optional.empty()), any(), any(), eq(latestBlockHeader)); } @Test @@ -207,7 +208,8 @@ public void shouldReturnAccessListIfNoParameterAndWithAccessedStorage() { assertThat(responseWithMockTracer(request, tracer)) .usingRecursiveComparison() .isEqualTo(expectedResponse); - verify(transactionSimulator, times(2)).process(any(), any(), any(), eq(latestBlockHeader)); + verify(transactionSimulator, times(2)) + .process(any(), eq(Optional.empty()), any(), any(), eq(latestBlockHeader)); } @Test @@ -224,7 +226,8 @@ public void shouldReturnEmptyAccessListIfNoAccessedStorage() { // Set TransactionSimulator.process response mockTransactionSimulatorResult(true, false, 1L, latestBlockHeader); assertThat(method.response(request)).usingRecursiveComparison().isEqualTo(expectedResponse); - verify(transactionSimulator, times(1)).process(any(), any(), any(), eq(latestBlockHeader)); + verify(transactionSimulator, times(1)) + .process(any(), eq(Optional.empty()), any(), any(), eq(latestBlockHeader)); } @Test @@ -245,7 +248,8 @@ public void shouldReturnAccessListIfParameterAndSameAccessedStorage() { assertThat(responseWithMockTracer(request, tracer)) .usingRecursiveComparison() .isEqualTo(expectedResponse); - verify(transactionSimulator, times(1)).process(any(), any(), any(), eq(latestBlockHeader)); + verify(transactionSimulator, times(1)) + .process(any(), eq(Optional.empty()), any(), any(), eq(latestBlockHeader)); } @Test @@ -269,7 +273,8 @@ public void shouldReturnAccessListIfWithParameterAndDifferentAccessedStorage() { assertThat(responseWithMockTracer(request, tracer)) .usingRecursiveComparison() .isEqualTo(expectedResponse); - verify(transactionSimulator, times(2)).process(any(), any(), any(), eq(latestBlockHeader)); + verify(transactionSimulator, times(2)) + .process(any(), eq(Optional.empty()), any(), any(), eq(latestBlockHeader)); } @Test @@ -289,7 +294,8 @@ public void shouldReturnAccessListWhenBlockTagParamIsPresent() { assertThat(responseWithMockTracer(request, tracer)) .usingRecursiveComparison() .isEqualTo(expectedResponse); - verify(transactionSimulator, times(2)).process(any(), any(), any(), eq(finalizedBlockHeader)); + verify(transactionSimulator, times(2)) + .process(any(), eq(Optional.empty()), any(), any(), eq(finalizedBlockHeader)); } @Test @@ -309,7 +315,8 @@ public void shouldReturnAccessListWhenBlockNumberParamIsPresent() { assertThat(responseWithMockTracer(request, tracer)) .usingRecursiveComparison() .isEqualTo(expectedResponse); - verify(transactionSimulator, times(2)).process(any(), any(), any(), eq(genesisBlockHeader)); + verify(transactionSimulator, times(2)) + .process(any(), eq(Optional.empty()), any(), any(), eq(genesisBlockHeader)); } private JsonRpcResponse responseWithMockTracer( @@ -334,7 +341,7 @@ private void mockTransactionSimulatorResult( final long estimateGas, final BlockHeader blockHeader) { final TransactionSimulatorResult mockTxSimResult = mock(TransactionSimulatorResult.class); - when(transactionSimulator.process(any(), any(), any(), eq(blockHeader))) + when(transactionSimulator.process(any(), eq(Optional.empty()), any(), any(), eq(blockHeader))) .thenReturn(Optional.of(mockTxSimResult)); final TransactionProcessingResult mockResult = mock(TransactionProcessingResult.class); when(mockResult.getEstimateGasUsedByTransaction()).thenReturn(estimateGas);