diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 2aff0bb48e59..c74366535784 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -19,6 +19,17 @@ jobs: steps: - name: checkout uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 + - name: Pre-process Release Name + id: pre_process_release_name + run: | + RELEASE_NAME="${{ github.event.release.name }}" + # strip all whitespace + RELEASE_NAME="${RELEASE_NAME//[[:space:]]/}" + if [[ ! "$RELEASE_NAME" =~ ^[0-9]+\.[0-9]+(\.[0-9]+)?(-.*)?$ ]]; then + echo "Release name does not conform to a valid besu release format YY.M.v[-suffix], e.g. 24.8.0-RC1." + exit 1 + fi + echo "RELEASE_NAME=$RELEASE_NAME" >> $GITHUB_ENV # Store in environment variable - name: Set up Java uses: actions/setup-java@387ac29b308b003ca37ba93a6cab5eb57c8f5f93 with: @@ -30,7 +41,7 @@ jobs: cache-disabled: true - name: assemble release run: - ./gradlew -Prelease.releaseVersion=${{github.event.release.name}} -Pversion=${{github.event.release.name}} assemble + ./gradlew -Prelease.releaseVersion=${{env.RELEASE_NAME}} -Pversion=${{env.RELEASE_NAME}} assemble - name: hashes id: hashes run: | @@ -43,13 +54,13 @@ jobs: uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 with: path: 'build/distributions/besu*.tar.gz' - name: besu-${{ github.event.release.name }}.tar.gz + name: besu-${{ env.RELEASE_NAME }}.tar.gz compression-level: 0 - name: upload zipfile uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 with: path: 'build/distributions/besu*.zip' - name: besu-${{ github.event.release.name }}.zip + name: besu-${{ env.RELEASE_NAME }}.zip compression-level: 0 testWindows: @@ -121,7 +132,7 @@ jobs: env: ARTIFACTORY_USER: ${{ secrets.BESU_ARTIFACTORY_USER }} ARTIFACTORY_KEY: ${{ secrets.BESU_ARTIFACTORY_TOKEN }} - run: ./gradlew -Prelease.releaseVersion=${{ github.event.release.name }} -Pversion=${{github.event.release.name}} artifactoryPublish + run: ./gradlew -Prelease.releaseVersion=${{ env.RELEASE_NAME }} -Pversion=${{env.RELEASE_NAME}} artifactoryPublish hadolint: runs-on: ubuntu-22.04 @@ -195,11 +206,11 @@ jobs: architecture: ${{ steps.prep.outputs.ARCH }} with: cache-disabled: true - arguments: testDocker -PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }} -Pversion=${{github.event.release.name}} -Prelease.releaseVersion=${{ github.event.release.name }} + arguments: testDocker -PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }} -Pversion=${{env.RELEASE_NAME}} -Prelease.releaseVersion=${{ env.RELEASE_NAME }} - name: publish env: architecture: ${{ steps.prep.outputs.ARCH }} - run: ./gradlew --no-daemon dockerUpload -PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }} -Pversion=${{github.event.release.name}} -Prelease.releaseVersion=${{ github.event.release.name }} + run: ./gradlew --no-daemon dockerUpload -PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }} -Pversion=${{env.RELEASE_NAME}} -Prelease.releaseVersion=${{ env.RELEASE_NAME }} multiArch: needs: buildDocker @@ -226,7 +237,7 @@ jobs: username: ${{ secrets.DOCKER_USER_RW }} password: ${{ secrets.DOCKER_PASSWORD_RW }} - name: multi-arch docker - run: ./gradlew manifestDocker -PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }} -Pversion=${{github.event.release.name}} -Prelease.releaseVersion=${{ github.event.release.name }} + run: ./gradlew manifestDocker -PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }} -Pversion=${{env.RELEASE_NAME}} -Prelease.releaseVersion=${{ env.RELEASE_NAME }} amendNotes: needs: multiArch @@ -239,7 +250,7 @@ jobs: with: append_body: true body: | - `docker pull ${{env.registry}}/${{secrets.DOCKER_ORG}}/besu:${{github.event.release.name}}` + `docker pull ${{env.registry}}/${{secrets.DOCKER_ORG}}/besu:${{env.RELEASE_NAME}}` dockerPromoteX64: needs: multiArch @@ -262,9 +273,9 @@ jobs: with: cache-disabled: true - name: Docker upload - run: ./gradlew "-Prelease.releaseVersion=${{ github.event.release.name }}" "-PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }}" dockerUploadRelease + run: ./gradlew "-Prelease.releaseVersion=${{ env.RELEASE_NAME }}" "-PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }}" dockerUploadRelease - name: Docker manifest - run: ./gradlew "-Prelease.releaseVersion=${{ github.event.release.name }}" "-PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }}" manifestDockerRelease + run: ./gradlew "-Prelease.releaseVersion=${{ env.RELEASE_NAME }}" "-PdockerOrgName=${{ env.registry }}/${{ secrets.DOCKER_ORG }}" manifestDockerRelease verifyContainer: needs: dockerPromoteX64 @@ -276,6 +287,6 @@ jobs: - name: Checkout uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 - name: Trigger container verify - run: echo '{"version":"${{ github.event.release.name }}","verify-latest-version":"true"}' | gh workflow run container-verify.yml --json + run: echo '{"version":"${{ env.RELEASE_NAME }}","verify-latest-version":"true"}' | gh workflow run container-verify.yml --json env: GH_TOKEN: ${{ github.token }} diff --git a/CHANGELOG.md b/CHANGELOG.md index 9173e46fd5e8..b9fccf29c48c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,17 +1,30 @@ # Changelog +## [Unreleased] + +### Fixed +- **DebugMetrics**: Fixed a `ClassCastException` occurring in `DebugMetrics` when handling nested metric structures. Previously, `Double` values within these structures were incorrectly cast to `Map` objects, leading to errors. This update allows for proper handling of both direct values and nested structures at the same level. Issue# [#7383] + +### Tests +- Added a comprehensive test case to reproduce the bug and verify the fix for the `ClassCastException` in `DebugMetrics`. This ensures that complex, dynamically nested metric structures can be handled without errors. + ## Next release ### Upcoming Breaking Changes ### Breaking Changes +- Receipt compaction is enabled by default. It will no longer be possible to downgrade Besu to versions prior to 24.5.1. ### Additions and Improvements - Add 'inbound' field to admin_peers JSON-RPC Call [#7461](https://github.com/hyperledger/besu/pull/7461) +- Add pending block header to `TransactionEvaluationContext` plugin API [#7483](https://github.com/hyperledger/besu/pull/7483) +- Add bootnode to holesky config [#7500](https://github.com/hyperledger/besu/pull/7500) ### Bug fixes - Fix tracing in precompiled contracts when halting for out of gas [#7318](https://github.com/hyperledger/besu/issues/7318) - Correctly release txpool save and restore lock in case of exceptions [#7473](https://github.com/hyperledger/besu/pull/7473) +- Fix for `eth_gasPrice` could not retrieve block error [#7482](https://github.com/hyperledger/besu/pull/7482) + ## 24.8.0 @@ -37,6 +50,7 @@ - Correct entrypoint in Docker evmtool [#7430](https://github.com/hyperledger/besu/pull/7430) - Fix protocol schedule check for devnets [#7429](https://github.com/hyperledger/besu/pull/7429) - Fix behaviour when starting in a pre-merge network [#7431](https://github.com/hyperledger/besu/pull/7431) +- Fix Null pointer from DNS daemon [#7505](https://github.com/hyperledger/besu/issues/7505) ## 24.7.1 diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index eb4a656b0e48..c2d6c57d25a1 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,7 +28,7 @@ Having the following accounts is necessary for contributing code/issues to Besu. ### Other important information -* [Roadmap](https://wiki.hyperledger.org/display/BESU/Roadmap) +* [Roadmap](https://wiki.hyperledger.org/pages/viewpage.action?pageId=24781786) * [Code of Conduct](https://wiki.hyperledger.org/display/BESU/Code+of+Conduct) * [Governance](https://wiki.hyperledger.org/display/BESU/Governance) diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/AcceptanceTestBase.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/AcceptanceTestBase.java index cac4deb9d9ba..4072c6f1bc1c 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/AcceptanceTestBase.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/AcceptanceTestBase.java @@ -57,6 +57,7 @@ import java.util.concurrent.Executors; import org.junit.After; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -183,4 +184,11 @@ protected void waitForBlockHeight(final Node node, final long blockchainHeight) assertThat(node.execute(ethTransactions.blockNumber())) .isGreaterThanOrEqualTo(BigInteger.valueOf(blockchainHeight))); } + + @Test + public void dryRunDetector() { + assertThat(true) + .withFailMessage("This test is here so gradle --dry-run executes this class") + .isTrue(); + } } diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/AcceptanceTestBaseJunit5.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/AcceptanceTestBaseJunit5.java index 92d9273e8f87..0cf24b57364f 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/AcceptanceTestBaseJunit5.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/AcceptanceTestBaseJunit5.java @@ -58,6 +58,7 @@ import org.apache.logging.log4j.ThreadContext; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInfo; import org.junit.jupiter.api.extension.ExtendWith; import org.slf4j.Logger; @@ -196,4 +197,11 @@ protected void waitForBlockHeight(final Node node, final long blockchainHeight) assertThat(node.execute(ethTransactions.blockNumber())) .isGreaterThanOrEqualTo(BigInteger.valueOf(blockchainHeight))); } + + @Test + void dryRunDetector() { + assertThat(true) + .withFailMessage("This test is here so gradle --dry-run executes this class") + .isTrue(); + } } diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/perm/AllowListContainsKeyAndValue.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/perm/AllowListContainsKeyAndValue.java index 0913fd227f3b..a2ffc9b36da2 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/perm/AllowListContainsKeyAndValue.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/condition/perm/AllowListContainsKeyAndValue.java @@ -24,16 +24,11 @@ import java.nio.file.Path; import java.util.Collection; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - public class AllowListContainsKeyAndValue implements Condition { private final ALLOWLIST_TYPE allowlistType; private final Collection allowlistValues; private final Path configFilePath; - private static final Logger LOG = LoggerFactory.getLogger(AllowListContainsKeyAndValue.class); - public AllowListContainsKeyAndValue( final ALLOWLIST_TYPE allowlistType, final Collection allowlistValues, @@ -52,7 +47,6 @@ public void verify(final Node node) { allowlistType, allowlistValues, configFilePath); } catch (final Exception e) { result = false; - LOG.error("Error verifying allowlist contains key and value", e); } assertThat(result).isTrue(); } diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java index 37906761d1a1..c6696b15a229 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/ProcessBesuNodeRunner.java @@ -24,8 +24,6 @@ import org.hyperledger.besu.ethereum.eth.transactions.ImmutableTransactionPoolConfiguration; import org.hyperledger.besu.ethereum.p2p.rlpx.connections.netty.TLSConfiguration; import org.hyperledger.besu.ethereum.permissioning.PermissioningConfiguration; -import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; -import org.hyperledger.besu.ethereum.worldstate.ImmutableDataStorageConfiguration; import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.plugin.services.metrics.MetricCategory; import org.hyperledger.besu.tests.acceptance.dsl.StaticNodesUtils; @@ -113,11 +111,7 @@ public void startNode(final BesuNode node) { .getCLIOptions()); params.addAll( - DataStorageOptions.fromConfig( - ImmutableDataStorageConfiguration.builder() - .from(DataStorageConfiguration.DEFAULT_FOREST_CONFIG) - .build()) - .getCLIOptions()); + DataStorageOptions.fromConfig(node.getDataStorageConfiguration()).getCLIOptions()); if (node.getMiningParameters().isMiningEnabled()) { params.add("--miner-enabled"); 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 001406cb7814..f28a1d8876ee 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 @@ -18,13 +18,8 @@ import org.hyperledger.besu.Runner; import org.hyperledger.besu.RunnerBuilder; -import org.hyperledger.besu.chainexport.RlpBlockExporter; -import org.hyperledger.besu.chainimport.JsonBlockImporter; -import org.hyperledger.besu.chainimport.RlpBlockImporter; -import org.hyperledger.besu.cli.BesuCommand; import org.hyperledger.besu.cli.config.EthNetworkConfig; import org.hyperledger.besu.cli.config.NetworkName; -import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.controller.BesuControllerBuilder; @@ -36,28 +31,22 @@ import org.hyperledger.besu.ethereum.api.graphql.GraphQLConfiguration; import org.hyperledger.besu.ethereum.api.jsonrpc.InProcessRpcConfiguration; import org.hyperledger.besu.ethereum.core.ImmutableMiningParameters; -import org.hyperledger.besu.ethereum.core.MiningParameters; import org.hyperledger.besu.ethereum.core.plugins.PluginConfiguration; import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration; -import org.hyperledger.besu.ethereum.eth.transactions.BlobCacheModule; import org.hyperledger.besu.ethereum.eth.transactions.ImmutableTransactionPoolConfiguration; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPoolConfiguration; import org.hyperledger.besu.ethereum.p2p.peers.EnodeURLImpl; 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.trie.diffbased.bonsai.cache.BonsaiCachedMerkleTrieLoaderModule; -import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; import org.hyperledger.besu.evm.internal.EvmConfiguration; -import org.hyperledger.besu.metrics.MetricsSystemModule; +import org.hyperledger.besu.metrics.MetricsSystemFactory; import org.hyperledger.besu.metrics.ObservableMetricsSystem; -import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; import org.hyperledger.besu.plugin.data.EnodeURL; import org.hyperledger.besu.plugin.services.BesuConfiguration; import org.hyperledger.besu.plugin.services.BesuEvents; import org.hyperledger.besu.plugin.services.BlockchainService; -import org.hyperledger.besu.plugin.services.MetricsSystem; import org.hyperledger.besu.plugin.services.PermissioningService; import org.hyperledger.besu.plugin.services.PicoCLIOptions; import org.hyperledger.besu.plugin.services.PrivacyPluginService; @@ -81,27 +70,17 @@ import org.hyperledger.besu.services.TransactionPoolValidatorServiceImpl; import org.hyperledger.besu.services.TransactionSelectionServiceImpl; import org.hyperledger.besu.services.TransactionSimulationServiceImpl; -import org.hyperledger.besu.services.kvstore.InMemoryStoragePlugin; import java.io.File; -import java.io.IOException; -import java.nio.file.Files; import java.nio.file.Path; import java.time.Clock; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; -import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.stream.Collectors; -import javax.inject.Inject; -import javax.inject.Named; -import javax.inject.Singleton; -import dagger.Component; -import dagger.Module; -import dagger.Provides; import io.opentelemetry.api.GlobalOpenTelemetry; import io.vertx.core.Vertx; import org.slf4j.Logger; @@ -117,6 +96,60 @@ public class ThreadBesuNodeRunner implements BesuNodeRunner { private final Map besuPluginContextMap = new ConcurrentHashMap<>(); + private BesuPluginContextImpl buildPluginContext( + final BesuNode node, + final StorageServiceImpl storageService, + final SecurityModuleServiceImpl securityModuleService, + final TransactionSimulationServiceImpl transactionSimulationServiceImpl, + final TransactionSelectionServiceImpl transactionSelectionServiceImpl, + final TransactionPoolValidatorServiceImpl transactionPoolValidatorServiceImpl, + final BlockchainServiceImpl blockchainServiceImpl, + final RpcEndpointServiceImpl rpcEndpointServiceImpl, + final BesuConfiguration commonPluginConfiguration, + final PermissioningServiceImpl permissioningService) { + final CommandLine commandLine = new CommandLine(CommandSpec.create()); + final BesuPluginContextImpl besuPluginContext = new BesuPluginContextImpl(); + besuPluginContext.addService(StorageService.class, storageService); + besuPluginContext.addService(SecurityModuleService.class, securityModuleService); + besuPluginContext.addService(PicoCLIOptions.class, new PicoCLIOptionsImpl(commandLine)); + besuPluginContext.addService(RpcEndpointService.class, rpcEndpointServiceImpl); + besuPluginContext.addService( + TransactionSelectionService.class, transactionSelectionServiceImpl); + besuPluginContext.addService( + TransactionPoolValidatorService.class, transactionPoolValidatorServiceImpl); + besuPluginContext.addService( + TransactionSimulationService.class, transactionSimulationServiceImpl); + besuPluginContext.addService(BlockchainService.class, blockchainServiceImpl); + besuPluginContext.addService(BesuConfiguration.class, commonPluginConfiguration); + + final Path pluginsPath; + final String pluginDir = System.getProperty("besu.plugins.dir"); + if (pluginDir == null || pluginDir.isEmpty()) { + pluginsPath = node.homeDirectory().resolve("plugins"); + final File pluginsDirFile = pluginsPath.toFile(); + if (!pluginsDirFile.isDirectory()) { + pluginsDirFile.mkdirs(); + pluginsDirFile.deleteOnExit(); + } + System.setProperty("besu.plugins.dir", pluginsPath.toString()); + } else { + pluginsPath = Path.of(pluginDir); + } + + besuPluginContext.addService(BesuConfiguration.class, commonPluginConfiguration); + besuPluginContext.addService(PermissioningService.class, permissioningService); + besuPluginContext.addService(PrivacyPluginService.class, new PrivacyPluginServiceImpl()); + + besuPluginContext.registerPlugins( + new PluginConfiguration.Builder().pluginsDir(pluginsPath).build()); + + commandLine.parseArgs(node.getConfiguration().getExtraCLIOptions().toArray(new String[0])); + + // register built-in plugins + new RocksDBPlugin().register(besuPluginContext); + return besuPluginContext; + } + @Override public void startNode(final BesuNode node) { @@ -129,9 +162,8 @@ public void startNode(final BesuNode node) { throw new UnsupportedOperationException("commands are not supported with thread runner"); } - AcceptanceTestBesuComponent component = - DaggerThreadBesuNodeRunner_AcceptanceTestBesuComponent.create(); - + final StorageServiceImpl storageService = new StorageServiceImpl(); + final SecurityModuleServiceImpl securityModuleService = new SecurityModuleServiceImpl(); final TransactionSimulationServiceImpl transactionSimulationServiceImpl = new TransactionSimulationServiceImpl(); final TransactionSelectionServiceImpl transactionSelectionServiceImpl = @@ -154,22 +186,49 @@ public void startNode(final BesuNode node) { .withMiningParameters(miningParameters); final BesuPluginContextImpl besuPluginContext = - besuPluginContextMap.computeIfAbsent(node, n -> component.getBesuPluginContext()); + besuPluginContextMap.computeIfAbsent( + node, + n -> + buildPluginContext( + node, + storageService, + securityModuleService, + transactionSimulationServiceImpl, + transactionSelectionServiceImpl, + transactionPoolValidatorServiceImpl, + blockchainServiceImpl, + rpcEndpointServiceImpl, + commonPluginConfiguration, + permissioningService)); GlobalOpenTelemetry.resetForTest(); - final ObservableMetricsSystem metricsSystem = component.getObservableMetricsSystem(); + final ObservableMetricsSystem metricsSystem = + MetricsSystemFactory.create(node.getMetricsConfiguration()); final List bootnodes = node.getConfiguration().getBootnodes().stream() .map(EnodeURLImpl::fromURI) .collect(Collectors.toList()); - - final EthNetworkConfig.Builder networkConfigBuilder = component.ethNetworkConfigBuilder(); - networkConfigBuilder.setBootNodes(bootnodes); + final NetworkName network = node.getNetwork() == null ? NetworkName.DEV : node.getNetwork(); + final EthNetworkConfig.Builder networkConfigBuilder = + new EthNetworkConfig.Builder(EthNetworkConfig.getNetworkConfig(network)) + .setBootNodes(bootnodes); node.getConfiguration() .getGenesisConfig() .map(GenesisConfigFile::fromConfig) .ifPresent(networkConfigBuilder::setGenesisConfigFile); final EthNetworkConfig ethNetworkConfig = networkConfigBuilder.build(); + final SynchronizerConfiguration synchronizerConfiguration = + new SynchronizerConfiguration.Builder().build(); + final BesuControllerBuilder builder = + new BesuController.Builder() + .fromEthNetworkConfig(ethNetworkConfig, synchronizerConfiguration.getSyncMode()); + + final KeyValueStorageProvider storageProvider = + new KeyValueStorageProviderBuilder() + .withStorageFactory(storageService.getByName("rocksdb").get()) + .withCommonConfiguration(commonPluginConfiguration) + .withMetricsSystem(metricsSystem) + .build(); final TransactionPoolConfiguration txPoolConfig = ImmutableTransactionPoolConfiguration.builder() @@ -178,20 +237,35 @@ public void startNode(final BesuNode node) { .transactionPoolValidatorService(transactionPoolValidatorServiceImpl) .build(); - final BesuControllerBuilder builder = component.besuControllerBuilder(); - builder.isRevertReasonEnabled(node.isRevertReasonEnabled()); - builder.networkConfiguration(node.getNetworkingConfiguration()); - builder.transactionPoolConfiguration(txPoolConfig); - builder.dataDirectory(dataDir); - builder.nodeKey(new NodeKey(new KeyPairSecurityModule(KeyPairUtil.loadKeyPair(dataDir)))); - builder.privacyParameters(node.getPrivacyParameters()); final InProcessRpcConfiguration inProcessRpcConfiguration = node.inProcessRpcConfiguration(); + final int maxPeers = 25; + + builder + .synchronizerConfiguration(new SynchronizerConfiguration.Builder().build()) + .dataDirectory(node.homeDirectory()) + .miningParameters(miningParameters) + .privacyParameters(node.getPrivacyParameters()) + .nodeKey(new NodeKey(new KeyPairSecurityModule(KeyPairUtil.loadKeyPair(dataDir)))) + .metricsSystem(metricsSystem) + .transactionPoolConfiguration(txPoolConfig) + .dataStorageConfiguration(node.getDataStorageConfiguration()) + .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) + .clock(Clock.systemUTC()) + .isRevertReasonEnabled(node.isRevertReasonEnabled()) + .storageProvider(storageProvider) + .gasLimitCalculator(GasLimitCalculator.constant()) + .evmConfiguration(EvmConfiguration.DEFAULT) + .maxPeers(maxPeers) + .maxRemotelyInitiatedPeers(15) + .networkConfiguration(node.getNetworkingConfiguration()) + .randomPeerPriority(false); + node.getGenesisConfig() .map(GenesisConfigFile::fromConfig) .ifPresent(builder::genesisConfigFile); - final BesuController besuController = component.besuController(); + final BesuController besuController = builder.build(); initTransactionSimulationService( transactionSimulationServiceImpl, besuController, node.getApiConfiguration()); @@ -225,10 +299,11 @@ public void startNode(final BesuNode node) { .collect(Collectors.toList())) .besuPluginContext(besuPluginContext) .autoLogBloomCaching(false) - .storageProvider(besuController.getStorageProvider()) + .storageProvider(storageProvider) .rpcEndpointService(rpcEndpointServiceImpl) .inProcessRpcConfiguration(inProcessRpcConfiguration); node.engineRpcConfiguration().ifPresent(runnerBuilder::engineJsonRpcConfiguration); + besuPluginContext.beforeExternalServices(); final Runner runner = runnerBuilder.build(); @@ -321,230 +396,4 @@ public void startConsoleCapture() { public String getConsoleContents() { throw new RuntimeException("Console contents can only be captured in process execution"); } - - @Module - @SuppressWarnings("CloseableProvides") - static class BesuControllerModule { - @Provides - @Singleton - public SynchronizerConfiguration provideSynchronizationConfiguration() { - final SynchronizerConfiguration synchronizerConfiguration = - SynchronizerConfiguration.builder().build(); - return synchronizerConfiguration; - } - - @Singleton - @Provides - public BesuControllerBuilder provideBesuControllerBuilder( - final EthNetworkConfig ethNetworkConfig, - final SynchronizerConfiguration synchronizerConfiguration) { - - final BesuControllerBuilder builder = - new BesuController.Builder() - .fromEthNetworkConfig(ethNetworkConfig, synchronizerConfiguration.getSyncMode()); - return builder; - } - - @Provides - public BesuController provideBesuController( - final SynchronizerConfiguration synchronizerConfiguration, - final BesuControllerBuilder builder, - final ObservableMetricsSystem metricsSystem, - final KeyValueStorageProvider storageProvider, - final MiningParameters miningParameters) { - - builder - .synchronizerConfiguration(synchronizerConfiguration) - .metricsSystem(metricsSystem) - .dataStorageConfiguration(DataStorageConfiguration.DEFAULT_FOREST_CONFIG) - .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) - .clock(Clock.systemUTC()) - .storageProvider(storageProvider) - .gasLimitCalculator(GasLimitCalculator.constant()) - .evmConfiguration(EvmConfiguration.DEFAULT) - .maxPeers(25) - .maxRemotelyInitiatedPeers(15) - .miningParameters(miningParameters) - .randomPeerPriority(false) - .besuComponent(null); - return builder.build(); - } - - @Provides - @Singleton - public EthNetworkConfig.Builder provideEthNetworkConfigBuilder() { - final EthNetworkConfig.Builder networkConfigBuilder = - new EthNetworkConfig.Builder(EthNetworkConfig.getNetworkConfig(NetworkName.DEV)); - return networkConfigBuilder; - } - - @Provides - public EthNetworkConfig provideEthNetworkConfig( - final EthNetworkConfig.Builder networkConfigBuilder) { - - final EthNetworkConfig ethNetworkConfig = networkConfigBuilder.build(); - return ethNetworkConfig; - } - - @Provides - @Named("besuPluginContext") - public BesuPluginContextImpl providePluginContext( - final StorageServiceImpl storageService, - final SecurityModuleServiceImpl securityModuleService, - final TransactionSimulationServiceImpl transactionSimulationServiceImpl, - final TransactionSelectionServiceImpl transactionSelectionServiceImpl, - final TransactionPoolValidatorServiceImpl transactionPoolValidatorServiceImpl, - final BlockchainServiceImpl blockchainServiceImpl, - final RpcEndpointServiceImpl rpcEndpointServiceImpl, - final BesuConfiguration commonPluginConfiguration, - final PermissioningServiceImpl permissioningService) { - final CommandLine commandLine = new CommandLine(CommandSpec.create()); - final BesuPluginContextImpl besuPluginContext = new BesuPluginContextImpl(); - besuPluginContext.addService(StorageService.class, storageService); - besuPluginContext.addService(SecurityModuleService.class, securityModuleService); - besuPluginContext.addService(PicoCLIOptions.class, new PicoCLIOptionsImpl(commandLine)); - besuPluginContext.addService(RpcEndpointService.class, rpcEndpointServiceImpl); - besuPluginContext.addService( - TransactionSelectionService.class, transactionSelectionServiceImpl); - besuPluginContext.addService( - TransactionPoolValidatorService.class, transactionPoolValidatorServiceImpl); - besuPluginContext.addService( - TransactionSimulationService.class, transactionSimulationServiceImpl); - besuPluginContext.addService(BlockchainService.class, blockchainServiceImpl); - besuPluginContext.addService(BesuConfiguration.class, commonPluginConfiguration); - - final Path pluginsPath; - final String pluginDir = System.getProperty("besu.plugins.dir"); - if (pluginDir == null || pluginDir.isEmpty()) { - // pluginsPath = node.homeDirectory().resolve("plugins"); - pluginsPath = commonPluginConfiguration.getDataPath().resolve("plugins"); - final File pluginsDirFile = pluginsPath.toFile(); - if (!pluginsDirFile.isDirectory()) { - pluginsDirFile.mkdirs(); - pluginsDirFile.deleteOnExit(); - } - System.setProperty("besu.plugins.dir", pluginsPath.toString()); - } else { - pluginsPath = Path.of(pluginDir); - } - - besuPluginContext.addService(BesuConfiguration.class, commonPluginConfiguration); - besuPluginContext.addService(PermissioningService.class, permissioningService); - besuPluginContext.addService(PrivacyPluginService.class, new PrivacyPluginServiceImpl()); - - besuPluginContext.registerPlugins( - new PluginConfiguration.Builder().pluginsDir(pluginsPath).build()); - - // register built-in plugins - new RocksDBPlugin().register(besuPluginContext); - return besuPluginContext; - } - - @Provides - public KeyValueStorageProvider provideKeyValueStorageProvider( - final BesuConfiguration commonPluginConfiguration, final MetricsSystem metricsSystem) { - - final StorageServiceImpl storageService = new StorageServiceImpl(); - storageService.registerKeyValueStorage( - new InMemoryStoragePlugin.InMemoryKeyValueStorageFactory("memory")); - final KeyValueStorageProvider storageProvider = - new KeyValueStorageProviderBuilder() - .withStorageFactory(storageService.getByName("memory").get()) - .withCommonConfiguration(commonPluginConfiguration) - .withMetricsSystem(metricsSystem) - .build(); - - return storageProvider; - } - - @Provides - public MiningParameters provideMiningParameters( - final TransactionSelectionServiceImpl transactionSelectionServiceImpl) { - final var miningParameters = - ImmutableMiningParameters.builder() - .transactionSelectionService(transactionSelectionServiceImpl) - .build(); - - return miningParameters; - } - - @Provides - Path provideDataDir() { - try { - return Files.createTempDirectory("acctest"); - } catch (final IOException e) { - throw new RuntimeException("Unable to create temporary data directory", e); - } - } - - @Provides - @Inject - BesuConfiguration provideBesuConfiguration(final Path dataDir) { - final BesuConfigurationImpl commonPluginConfiguration = new BesuConfigurationImpl(); - commonPluginConfiguration.init( - dataDir, dataDir.resolve(DATABASE_PATH), DataStorageConfiguration.DEFAULT_FOREST_CONFIG); - return commonPluginConfiguration; - } - - @Provides - TransactionPoolConfiguration provideTransactionPoolConfiguration( - final BesuNode node, - final TransactionPoolValidatorServiceImpl transactionPoolValidatorServiceImpl) { - return ImmutableTransactionPoolConfiguration.builder() - .from(node.getTransactionPoolConfiguration()) - .strictTransactionReplayProtectionEnabled(node.isStrictTxReplayProtectionEnabled()) - .transactionPoolValidatorService(transactionPoolValidatorServiceImpl) - .build(); - } - } - - @Module - static class MockBesuCommandModule { - - @Provides - BesuCommand provideBesuCommand(final AcceptanceTestBesuComponent component) { - final BesuCommand besuCommand = - new BesuCommand( - component, - RlpBlockImporter::new, - JsonBlockImporter::new, - RlpBlockExporter::new, - new RunnerBuilder(), - new BesuController.Builder(), - Optional.ofNullable(component.getBesuPluginContext()).orElse(null), - System.getenv()); - besuCommand.toCommandLine(); - return besuCommand; - } - - @Provides - @Singleton - MetricsConfiguration provideMetricsConfiguration() { - return MetricsConfiguration.builder().build(); - } - - @Provides - @Named("besuCommandLogger") - @Singleton - Logger provideBesuCommandLogger() { - return LoggerFactory.getLogger(MockBesuCommandModule.class); - } - } - - @Singleton - @Component( - modules = { - ThreadBesuNodeRunner.BesuControllerModule.class, - ThreadBesuNodeRunner.MockBesuCommandModule.class, - BonsaiCachedMerkleTrieLoaderModule.class, - MetricsSystemModule.class, - BlobCacheModule.class - }) - public interface AcceptanceTestBesuComponent extends BesuComponent { - BesuController besuController(); - - BesuControllerBuilder besuControllerBuilder(); // TODO: needing this sucks - - EthNetworkConfig.Builder ethNetworkConfigBuilder(); - } } diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java index ed4a28422dd6..efbf91246b5e 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/configuration/BesuNodeFactory.java @@ -32,7 +32,9 @@ import org.hyperledger.besu.ethereum.core.PrivacyParameters; import org.hyperledger.besu.ethereum.permissioning.LocalPermissioningConfiguration; import org.hyperledger.besu.ethereum.permissioning.PermissioningConfiguration; +import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; import org.hyperledger.besu.pki.keystore.KeyStoreWrapper; +import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; import org.hyperledger.besu.tests.acceptance.dsl.node.BesuNode; import org.hyperledger.besu.tests.acceptance.dsl.node.Node; import org.hyperledger.besu.tests.acceptance.dsl.node.RunnableNode; @@ -476,7 +478,9 @@ public BesuNode createIbft2Node(final String name, final String genesisFile) thr .build()); } - public BesuNode createIbft2Node(final String name, final boolean fixedPort) throws IOException { + public BesuNode createIbft2Node( + final String name, final boolean fixedPort, final DataStorageFormat storageFormat) + throws IOException { JsonRpcConfiguration rpcConfig = node.createJsonRpcWithIbft2EnabledConfig(false); rpcConfig.addRpcApi("ADMIN,TXPOOL"); if (fixedPort) { @@ -484,6 +488,7 @@ public BesuNode createIbft2Node(final String name, final boolean fixedPort) thro Math.abs(name.hashCode() % 60000) + 1024); // Generate a consistent port for p2p based on node name } + BesuNodeConfigurationBuilder builder = new BesuNodeConfigurationBuilder() .name(name) @@ -491,6 +496,10 @@ public BesuNode createIbft2Node(final String name, final boolean fixedPort) thro .jsonRpcConfiguration(rpcConfig) .webSocketConfiguration(node.createWebSocketEnabledConfig()) .devMode(false) + .dataStorageConfiguration( + storageFormat == DataStorageFormat.FOREST + ? DataStorageConfiguration.DEFAULT_FOREST_CONFIG + : DataStorageConfiguration.DEFAULT_BONSAI_CONFIG) .genesisConfigProvider(GenesisConfigurationFactory::createIbft2GenesisConfig); if (fixedPort) { builder.p2pPort( @@ -527,7 +536,9 @@ public BesuNode createQbftNodeWithTLSPKCS11(final String name) throws IOExceptio return createQbftNodeWithTLS(name, KeyStoreWrapper.KEYSTORE_TYPE_PKCS11); } - public BesuNode createQbftNode(final String name, final boolean fixedPort) throws IOException { + public BesuNode createQbftNode( + final String name, final boolean fixedPort, final DataStorageFormat storageFormat) + throws IOException { JsonRpcConfiguration rpcConfig = node.createJsonRpcWithQbftEnabledConfig(false); rpcConfig.addRpcApi("ADMIN,TXPOOL"); if (fixedPort) { @@ -543,6 +554,10 @@ public BesuNode createQbftNode(final String name, final boolean fixedPort) throw .jsonRpcConfiguration(rpcConfig) .webSocketConfiguration(node.createWebSocketEnabledConfig()) .devMode(false) + .dataStorageConfiguration( + storageFormat == DataStorageFormat.FOREST + ? DataStorageConfiguration.DEFAULT_FOREST_CONFIG + : DataStorageConfiguration.DEFAULT_BONSAI_CONFIG) .genesisConfigProvider(GenesisConfigurationFactory::createQbftGenesisConfig); if (fixedPort) { builder.p2pPort( diff --git a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/privacy/PrivacyNode.java b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/privacy/PrivacyNode.java index d54bf9087267..520cd7d57415 100644 --- a/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/privacy/PrivacyNode.java +++ b/acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/privacy/PrivacyNode.java @@ -276,7 +276,7 @@ private PrivacyStorageProvider createKeyValueStorageProvider( final Path dataLocation, final Path dbLocation) { final var besuConfiguration = new BesuConfigurationImpl(); besuConfiguration - .init(dataLocation, dbLocation, besuConfig.getDataStorageConfiguration()) + .init(dataLocation, dbLocation, null) .withMiningParameters(besuConfig.getMiningParameters()); return new PrivacyKeyValueStorageProviderBuilder() .withStorageFactory( diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftAcceptanceTestParameterization.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftAcceptanceTestParameterization.java index 15872070d006..2351f740bfb3 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftAcceptanceTestParameterization.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bft/BftAcceptanceTestParameterization.java @@ -14,6 +14,7 @@ */ package org.hyperledger.besu.tests.acceptance.bft; +import org.hyperledger.besu.plugin.services.storage.DataStorageFormat; import org.hyperledger.besu.tests.acceptance.dsl.node.BesuNode; import org.hyperledger.besu.tests.acceptance.dsl.node.configuration.BesuNodeFactory; @@ -38,7 +39,9 @@ public static Stream getFactories() { @FunctionalInterface public interface NodeCreator { - BesuNode create(BesuNodeFactory factory, String name, boolean fixedPort) throws Exception; + BesuNode create( + BesuNodeFactory factory, String name, boolean fixedPort, DataStorageFormat storageFormat) + throws Exception; } @FunctionalInterface @@ -64,11 +67,15 @@ public BftAcceptanceTestParameterization( } public BesuNode createNode(BesuNodeFactory factory, String name) throws Exception { - return creatorFn.create(factory, name, false); + return creatorFn.create(factory, name, false, DataStorageFormat.FOREST); + } + + public BesuNode createBonsaiNodeFixedPort(BesuNodeFactory factory, String name) throws Exception { + return creatorFn.create(factory, name, true, DataStorageFormat.BONSAI); } - public BesuNode createNodeFixedPort(BesuNodeFactory factory, String name) throws Exception { - return creatorFn.create(factory, name, true); + public BesuNode createForestNodeFixedPort(BesuNodeFactory factory, String name) throws Exception { + return creatorFn.create(factory, name, true, DataStorageFormat.FOREST); } public BesuNode createNodeWithValidators( diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bftsoak/BftMiningSoakTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bftsoak/BftMiningSoakTest.java index 9861a7dab65b..878e503ba395 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bftsoak/BftMiningSoakTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bftsoak/BftMiningSoakTest.java @@ -60,10 +60,11 @@ public void shouldBeStableDuringLongTest( // in between certain steps. There should be no upper-limit to how long the test is run for assertThat(getTestDurationMins()).isGreaterThanOrEqualTo(MIN_TEST_TIME_MINS); - final BesuNode minerNode1 = nodeFactory.createNodeFixedPort(besu, "miner1"); - final BesuNode minerNode2 = nodeFactory.createNodeFixedPort(besu, "miner2"); - final BesuNode minerNode3 = nodeFactory.createNodeFixedPort(besu, "miner3"); - final BesuNode minerNode4 = nodeFactory.createNodeFixedPort(besu, "miner4"); + // Create a mix of Bonsai and Forest DB nodes + final BesuNode minerNode1 = nodeFactory.createBonsaiNodeFixedPort(besu, "miner1"); + final BesuNode minerNode2 = nodeFactory.createForestNodeFixedPort(besu, "miner2"); + final BesuNode minerNode3 = nodeFactory.createBonsaiNodeFixedPort(besu, "miner3"); + final BesuNode minerNode4 = nodeFactory.createForestNodeFixedPort(besu, "miner4"); // Each step should be given a minimum of 3 minutes to complete successfully. If the time // give to run the soak test results in a time-per-step lower than this then the time diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bootstrap/ClusterThreadNodeRunnerAcceptanceTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bootstrap/ClusterThreadNodeRunnerAcceptanceTest.java index 39cc5ad26fc7..8fbd0d3d6255 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bootstrap/ClusterThreadNodeRunnerAcceptanceTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/bootstrap/ClusterThreadNodeRunnerAcceptanceTest.java @@ -38,7 +38,7 @@ public void setUp() throws Exception { final BesuNodeRunner besuNodeRunner = new ThreadBesuNodeRunner(); noDiscoveryCluster = new Cluster(clusterConfiguration, net, besuNodeRunner); final BesuNode noDiscoveryNode = besu.createNodeWithNoDiscovery("noDiscovery"); - fullNode = besu.createArchiveNode("archive"); + fullNode = besu.createArchiveNode("node2"); noDiscoveryCluster.start(noDiscoveryNode, fullNode); } diff --git a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/jsonrpc/AbstractJsonRpcTest.java b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/jsonrpc/AbstractJsonRpcTest.java index d88b1ed8b559..129074917633 100644 --- a/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/jsonrpc/AbstractJsonRpcTest.java +++ b/acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/jsonrpc/AbstractJsonRpcTest.java @@ -40,6 +40,7 @@ import okhttp3.Request; import okhttp3.RequestBody; import okhttp3.Response; +import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; @@ -147,4 +148,11 @@ public static Stream testCasesFromPath(final String testCasesPath) return Arrays.stream(testCasesList).sorted().map(File::toURI).map(Arguments::of); } + + @Test + void dryRunDetector() { + assertThat(true) + .withFailMessage("This test is here so gradle --dry-run executes this class") + .isTrue(); + } } diff --git a/acceptance-tests/tests/src/test/resources/jsonrpc/engine/shanghai/test-cases/05_shanghai_prepare_payload_invalid_null_withdrawals.json b/acceptance-tests/tests/src/test/resources/jsonrpc/engine/shanghai/test-cases/05_shanghai_prepare_payload_invalid_null_withdrawals.json index ac5947c79be4..ec5e2251791d 100644 --- a/acceptance-tests/tests/src/test/resources/jsonrpc/engine/shanghai/test-cases/05_shanghai_prepare_payload_invalid_null_withdrawals.json +++ b/acceptance-tests/tests/src/test/resources/jsonrpc/engine/shanghai/test-cases/05_shanghai_prepare_payload_invalid_null_withdrawals.json @@ -21,7 +21,7 @@ "id" : 67, "error" : { "code" : -32602, - "message" : "Invalid params" + "message" : "Invalid withdrawals" } }, "statusCode" : 200 diff --git a/acceptance-tests/tests/src/test/resources/jsonrpc/engine/shanghai/test-cases/09_shanghai_newPayloadV2_invalid_null_withdrawals.json b/acceptance-tests/tests/src/test/resources/jsonrpc/engine/shanghai/test-cases/09_shanghai_newPayloadV2_invalid_null_withdrawals.json index 41718648049f..0fe0a15dfc81 100644 --- a/acceptance-tests/tests/src/test/resources/jsonrpc/engine/shanghai/test-cases/09_shanghai_newPayloadV2_invalid_null_withdrawals.json +++ b/acceptance-tests/tests/src/test/resources/jsonrpc/engine/shanghai/test-cases/09_shanghai_newPayloadV2_invalid_null_withdrawals.json @@ -28,8 +28,7 @@ "id": 67, "error": { "code": -32602, - "message": "Invalid params", - "data": "Invalid withdrawals" + "message": "Invalid withdrawals" } }, "statusCode": 200 diff --git a/besu/build.gradle b/besu/build.gradle index 7eef4a216c2f..286ca7a30fcd 100644 --- a/besu/build.gradle +++ b/besu/build.gradle @@ -104,8 +104,6 @@ dependencies { testImplementation 'org.mockito:mockito-core' testImplementation 'org.testcontainers:testcontainers' testImplementation 'tech.pegasys.discovery:discovery' - testImplementation 'com.google.dagger:dagger' annotationProcessor 'com.google.dagger:dagger-compiler' - testAnnotationProcessor 'com.google.dagger:dagger-compiler' } 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 ba61a869ff6f..00ea6e1efdba 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java @@ -1651,15 +1651,17 @@ private void validateChainDataPruningParams() { } private GenesisConfigFile readGenesisConfigFile() { - return genesisFile != null - ? GenesisConfigFile.fromSource(genesisConfigSource(genesisFile)) - : GenesisConfigFile.fromResource( - Optional.ofNullable(network).orElse(MAINNET).getGenesisFile()); + final GenesisConfigFile effectiveGenesisFile = + genesisFile != null + ? GenesisConfigFile.fromSource(genesisConfigSource(genesisFile)) + : GenesisConfigFile.fromResource( + Optional.ofNullable(network).orElse(MAINNET).getGenesisFile()); + return effectiveGenesisFile.withOverrides(genesisConfigOverrides); } private GenesisConfigOptions readGenesisConfigOptions() { try { - return genesisConfigFileSupplier.get().getConfigOptions(genesisConfigOverrides); + return genesisConfigFileSupplier.get().getConfigOptions(); } catch (final Exception e) { throw new ParameterException( this.commandLine, "Unable to load genesis file. " + e.getCause()); diff --git a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/DataStorageOptions.java b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/DataStorageOptions.java index 6f5c037c0d33..3d53a595ec86 100644 --- a/besu/src/main/java/org/hyperledger/besu/cli/options/stable/DataStorageOptions.java +++ b/besu/src/main/java/org/hyperledger/besu/cli/options/stable/DataStorageOptions.java @@ -95,8 +95,8 @@ public class DataStorageOptions implements CLIOptions @Option( names = "--receipt-compaction-enabled", - description = "Enables compact storing of receipts (default: ${DEFAULT-VALUE}).", - arity = "1") + description = "Enables compact storing of receipts (default: ${DEFAULT-VALUE})", + fallbackValue = "true") private Boolean receiptCompactionEnabled = DEFAULT_RECEIPT_COMPACTION_ENABLED; @CommandLine.ArgGroup(validate = false) 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 6bb3fb117c11..ddb75fcdedcb 100644 --- a/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java +++ b/besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java @@ -552,7 +552,6 @@ public BesuController build() { checkNotNull(evmConfiguration, "Missing evm config"); checkNotNull(networkingConfiguration, "Missing network configuration"); checkNotNull(dataStorageConfiguration, "Missing data storage configuration"); - prepForBuild(); final ProtocolSchedule protocolSchedule = createProtocolSchedule(); diff --git a/besu/src/main/java/org/hyperledger/besu/services/BlockchainServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/BlockchainServiceImpl.java index f10ebcce474a..1f014ee06104 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/BlockchainServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/BlockchainServiceImpl.java @@ -34,7 +34,6 @@ import java.util.Optional; import java.util.function.Supplier; import java.util.stream.Collectors; -import javax.inject.Inject; /** The Blockchain service implementation. */ @Unstable @@ -45,7 +44,6 @@ public class BlockchainServiceImpl implements BlockchainService { private MutableBlockchain blockchain; /** Instantiates a new Blockchain service implementation. */ - @Inject public BlockchainServiceImpl() {} /** diff --git a/besu/src/main/java/org/hyperledger/besu/services/PermissioningServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/PermissioningServiceImpl.java index e43bf1c054ef..eda202f6d4d1 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/PermissioningServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/PermissioningServiceImpl.java @@ -19,7 +19,6 @@ import org.hyperledger.besu.plugin.services.permissioning.NodeMessagePermissioningProvider; import java.util.List; -import javax.inject.Inject; import com.google.common.collect.Lists; @@ -30,7 +29,6 @@ public class PermissioningServiceImpl implements PermissioningService { Lists.newArrayList(); /** Default Constructor. */ - @Inject public PermissioningServiceImpl() {} @Override diff --git a/besu/src/main/java/org/hyperledger/besu/services/RpcEndpointServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/RpcEndpointServiceImpl.java index 5d7df73b2ef2..dcfe29146e71 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/RpcEndpointServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/RpcEndpointServiceImpl.java @@ -36,7 +36,6 @@ import java.util.NoSuchElementException; import java.util.function.Function; import java.util.stream.Collectors; -import javax.inject.Inject; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,7 +48,6 @@ public class RpcEndpointServiceImpl implements RpcEndpointService { private Map inProcessRpcMethods; /** Default Constructor. */ - @Inject public RpcEndpointServiceImpl() {} /** diff --git a/besu/src/main/java/org/hyperledger/besu/services/SecurityModuleServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/SecurityModuleServiceImpl.java index 5605fe49b5f7..c3905c304bc9 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/SecurityModuleServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/SecurityModuleServiceImpl.java @@ -21,18 +21,15 @@ import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Supplier; -import javax.inject.Inject; /** The Security module service implementation. */ public class SecurityModuleServiceImpl implements SecurityModuleService { + private final Map> securityModuleSuppliers = + new ConcurrentHashMap<>(); /** Default Constructor. */ - @Inject public SecurityModuleServiceImpl() {} - private final Map> securityModuleSuppliers = - new ConcurrentHashMap<>(); - @Override public void register(final String name, final Supplier securityModuleSupplier) { securityModuleSuppliers.put(name, securityModuleSupplier); diff --git a/besu/src/main/java/org/hyperledger/besu/services/StorageServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/StorageServiceImpl.java index dd5d822ccc38..6629da690e8c 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/StorageServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/StorageServiceImpl.java @@ -23,7 +23,6 @@ import java.util.Map; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; -import javax.inject.Inject; /** The Storage service implementation. */ public class StorageServiceImpl implements StorageService { @@ -32,7 +31,6 @@ public class StorageServiceImpl implements StorageService { private final Map factories; /** Instantiates a new Storage service. */ - @Inject public StorageServiceImpl() { this.segments = List.of(KeyValueSegmentIdentifier.values()); this.factories = new ConcurrentHashMap<>(); diff --git a/besu/src/main/java/org/hyperledger/besu/services/SynchronizationServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/SynchronizationServiceImpl.java index 898ede5d0d4b..2e15e2ab82f6 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/SynchronizationServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/SynchronizationServiceImpl.java @@ -74,17 +74,11 @@ public SynchronizationServiceImpl( @Override public void fireNewUnverifiedForkchoiceEvent( final Hash head, final Hash safeBlock, final Hash finalizedBlock) { - final MergeContext mergeContext = protocolContext.getConsensusContext(MergeContext.class); - if (mergeContext != null) { - mergeContext.fireNewUnverifiedForkchoiceEvent(head, safeBlock, finalizedBlock); - protocolContext.getBlockchain().setFinalized(finalizedBlock); - protocolContext.getBlockchain().setSafeBlock(safeBlock); - } else { - LOG.atWarn() - .setMessage( - "The merge context is unavailable, hence the fork choice event cannot be triggered") - .log(); - } + protocolContext + .safeConsensusContext(MergeContext.class) + .ifPresent(mc -> mc.fireNewUnverifiedForkchoiceEvent(head, safeBlock, finalizedBlock)); + protocolContext.getBlockchain().setFinalized(finalizedBlock); + protocolContext.getBlockchain().setSafeBlock(safeBlock); } @Override diff --git a/besu/src/main/java/org/hyperledger/besu/services/TransactionPoolValidatorServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/TransactionPoolValidatorServiceImpl.java index 46af0a6ea541..1e1f94fb3249 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/TransactionPoolValidatorServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/TransactionPoolValidatorServiceImpl.java @@ -19,17 +19,15 @@ import org.hyperledger.besu.plugin.services.txvalidator.PluginTransactionPoolValidatorFactory; import java.util.Optional; -import javax.inject.Inject; /** The Transaction pool validator service implementation. */ public class TransactionPoolValidatorServiceImpl implements TransactionPoolValidatorService { + private Optional factory = Optional.empty(); + /** Default Constructor. */ - @Inject public TransactionPoolValidatorServiceImpl() {} - private Optional factory = Optional.empty(); - @Override public PluginTransactionPoolValidator createTransactionValidator() { return factory diff --git a/besu/src/main/java/org/hyperledger/besu/services/TransactionSelectionServiceImpl.java b/besu/src/main/java/org/hyperledger/besu/services/TransactionSelectionServiceImpl.java index c7049c9aa0a3..8595a3c030b3 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/TransactionSelectionServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/TransactionSelectionServiceImpl.java @@ -19,17 +19,15 @@ import org.hyperledger.besu.plugin.services.txselection.PluginTransactionSelectorFactory; import java.util.Optional; -import javax.inject.Inject; /** The Transaction Selection service implementation. */ public class TransactionSelectionServiceImpl implements TransactionSelectionService { + private Optional factory = Optional.empty(); + /** Default Constructor. */ - @Inject public TransactionSelectionServiceImpl() {} - private Optional factory = Optional.empty(); - @Override public PluginTransactionSelector createPluginTransactionSelector() { return factory 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 8ec00e817031..54cce205a363 100644 --- a/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java +++ b/besu/src/main/java/org/hyperledger/besu/services/TransactionSimulationServiceImpl.java @@ -30,7 +30,6 @@ import org.hyperledger.besu.plugin.services.TransactionSimulationService; import java.util.Optional; -import javax.inject.Inject; /** TransactionSimulationServiceImpl */ @Unstable @@ -44,7 +43,6 @@ public class TransactionSimulationServiceImpl implements TransactionSimulationSe private TransactionSimulator transactionSimulator; /** Create an instance to be configured */ - @Inject public TransactionSimulationServiceImpl() {} /** diff --git a/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java b/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java deleted file mode 100644 index a246d18d2ffe..000000000000 --- a/besu/src/test/java/org/hyperledger/besu/FlexGroupPrivacyTest.java +++ /dev/null @@ -1,168 +0,0 @@ -/* - * Copyright contributors to Hyperledger 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; - -import static org.assertj.core.api.Assertions.assertThat; -import static org.hyperledger.besu.ethereum.core.PrivacyParameters.FLEXIBLE_PRIVACY; - -import org.hyperledger.besu.components.BesuComponent; -import org.hyperledger.besu.components.BesuPluginContextModule; -import org.hyperledger.besu.components.MockBesuCommandModule; -import org.hyperledger.besu.components.NoOpMetricsSystemModule; -import org.hyperledger.besu.components.PrivacyTestModule; -import org.hyperledger.besu.config.GenesisConfigFile; -import org.hyperledger.besu.controller.BesuController; -import org.hyperledger.besu.cryptoservices.NodeKeyUtils; -import org.hyperledger.besu.datatypes.Address; -import org.hyperledger.besu.enclave.EnclaveFactory; -import org.hyperledger.besu.ethereum.GasLimitCalculator; -import org.hyperledger.besu.ethereum.core.BlockHeader; -import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; -import org.hyperledger.besu.ethereum.core.InMemoryKeyValueStorageProvider; -import org.hyperledger.besu.ethereum.core.MiningParameters; -import org.hyperledger.besu.ethereum.core.PrivacyParameters; -import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; -import org.hyperledger.besu.ethereum.eth.sync.SyncMode; -import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration; -import org.hyperledger.besu.ethereum.eth.transactions.BlobCacheModule; -import org.hyperledger.besu.ethereum.eth.transactions.TransactionPoolConfiguration; -import org.hyperledger.besu.ethereum.p2p.config.NetworkingConfiguration; -import org.hyperledger.besu.ethereum.privacy.storage.PrivacyStorageProvider; -import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.cache.BonsaiCachedMerkleTrieLoaderModule; -import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; -import org.hyperledger.besu.evm.internal.EvmConfiguration; -import org.hyperledger.besu.evm.precompile.PrecompiledContract; -import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; -import org.hyperledger.besu.testutil.TestClock; - -import java.math.BigInteger; -import java.net.URI; -import java.net.URISyntaxException; -import java.nio.file.Path; -import javax.inject.Named; -import javax.inject.Singleton; - -import dagger.Component; -import dagger.Module; -import dagger.Provides; -import io.vertx.core.Vertx; -import org.junit.jupiter.api.AfterEach; -import org.junit.jupiter.api.Test; - -class FlexGroupPrivacyTest { - - private final Vertx vertx = Vertx.vertx(); - - @AfterEach - public void cleanUp() { - vertx.close(); - } - - @Test - void flexibleEnabledPrivacy() { - final BesuController besuController = - DaggerFlexGroupPrivacyTest_FlexGroupPrivacyTestComponent.builder() - .build() - .getBesuController(); - - final PrecompiledContract flexiblePrecompiledContract = - getPrecompile(besuController, FLEXIBLE_PRIVACY); - - assertThat(flexiblePrecompiledContract.getName()).isEqualTo("FlexiblePrivacy"); - } - - private PrecompiledContract getPrecompile( - final BesuController besuController, final Address defaultPrivacy) { - return besuController - .getProtocolSchedule() - .getByBlockHeader(blockHeader(0)) - .getPrecompileContractRegistry() - .get(defaultPrivacy); - } - - private BlockHeader blockHeader(final long number) { - return new BlockHeaderTestFixture().number(number).buildHeader(); - } - - @Singleton - @Component( - modules = { - FlexGroupPrivacyParametersModule.class, - FlexGroupPrivacyTest.PrivacyTestBesuControllerModule.class, - PrivacyTestModule.class, - MockBesuCommandModule.class, - BonsaiCachedMerkleTrieLoaderModule.class, - NoOpMetricsSystemModule.class, - BesuPluginContextModule.class, - BlobCacheModule.class - }) - interface FlexGroupPrivacyTestComponent extends BesuComponent { - BesuController getBesuController(); - } - - @Module - static class FlexGroupPrivacyParametersModule { - - @Provides - PrivacyParameters providePrivacyParameters( - final PrivacyStorageProvider storageProvider, final Vertx vertx) { - try { - return new PrivacyParameters.Builder() - .setEnabled(true) - .setEnclaveUrl(new URI("http://127.0.0.1:8000")) - .setStorageProvider(storageProvider) - .setEnclaveFactory(new EnclaveFactory(vertx)) - .setFlexiblePrivacyGroupsEnabled(true) - .build(); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } - } - - @Module - static class PrivacyTestBesuControllerModule { - - @Provides - @Singleton - @SuppressWarnings("CloseableProvides") - BesuController provideBesuController( - final PrivacyParameters privacyParameters, - final DataStorageConfiguration dataStorageConfiguration, - final FlexGroupPrivacyTestComponent context, - @Named("dataDir") final Path dataDir) { - - return new BesuController.Builder() - .fromGenesisFile(GenesisConfigFile.mainnet(), SyncMode.FULL) - .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) - .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) - .storageProvider(new InMemoryKeyValueStorageProvider()) - .networkId(BigInteger.ONE) - .miningParameters(MiningParameters.newDefault()) - .dataStorageConfiguration(dataStorageConfiguration) - .nodeKey(NodeKeyUtils.generate()) - .metricsSystem(new NoOpMetricsSystem()) - .dataDirectory(dataDir) - .clock(TestClock.fixed()) - .privacyParameters(privacyParameters) - .transactionPoolConfiguration(TransactionPoolConfiguration.DEFAULT) - .gasLimitCalculator(GasLimitCalculator.constant()) - .evmConfiguration(EvmConfiguration.DEFAULT) - .networkConfiguration(NetworkingConfiguration.create()) - .besuComponent(context) - .build(); - } - } -} diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java index 6298b70a9532..ceb0be40fe6b 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyReorgTest.java @@ -21,12 +21,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.hyperledger.besu.components.BesuComponent; -import org.hyperledger.besu.components.BesuPluginContextModule; -import org.hyperledger.besu.components.EnclaveModule; -import org.hyperledger.besu.components.MockBesuCommandModule; -import org.hyperledger.besu.components.NoOpMetricsSystemModule; -import org.hyperledger.besu.components.PrivacyTestModule; import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.crypto.KeyPair; @@ -53,9 +47,7 @@ import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration; -import org.hyperledger.besu.ethereum.eth.transactions.BlobCacheModule; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPoolConfiguration; -import org.hyperledger.besu.ethereum.mainnet.BlockImportResult; import org.hyperledger.besu.ethereum.mainnet.HeaderValidationMode; import org.hyperledger.besu.ethereum.p2p.config.NetworkingConfiguration; import org.hyperledger.besu.ethereum.privacy.PrivateStateRootResolver; @@ -64,7 +56,6 @@ import org.hyperledger.besu.ethereum.privacy.storage.PrivacyStorageProvider; import org.hyperledger.besu.ethereum.privacy.storage.PrivateStateStorage; import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput; -import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.cache.BonsaiCachedMerkleTrieLoaderModule; import org.hyperledger.besu.evm.internal.EvmConfiguration; import org.hyperledger.besu.evm.log.LogsBloomFilter; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; @@ -79,21 +70,19 @@ import java.util.Collections; import java.util.Optional; import java.util.function.Supplier; -import javax.inject.Named; -import javax.inject.Singleton; import com.google.common.base.Suppliers; -import dagger.Component; -import dagger.Module; -import dagger.Provides; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes32; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; @SuppressWarnings("rawtypes") public class PrivacyReorgTest { + @TempDir private Path folder; + private static final Supplier SIGNATURE_ALGORITHM = Suppliers.memoize(SignatureAlgorithmFactory::getInstance); @@ -141,15 +130,11 @@ public class PrivacyReorgTest { .signAndBuild(KEY_PAIR); private final BlockDataGenerator gen = new BlockDataGenerator(); + private BesuController besuController; + private PrivateStateRootResolver privateStateRootResolver; private PrivacyParameters privacyParameters; private Enclave mockEnclave; private Transaction privacyMarkerTransaction; - private final PrivacyReorgTestComponent component = - DaggerPrivacyReorgTest_PrivacyReorgTestComponent.create(); - - private final BesuController besuController = component.getBesuController(); - private final PrivateStateRootResolver privateStateRootResolver = - component.getPrivacyParameters().getPrivateStateRootResolver(); @BeforeEach public void setUp() throws IOException { @@ -189,6 +174,29 @@ public void setUp() throws IOException { .build(); privacyParameters.setPrivacyUserId(ENCLAVE_PUBLIC_KEY.toBase64String()); + + privateStateRootResolver = + new PrivateStateRootResolver(privacyParameters.getPrivateStateStorage()); + + besuController = + new BesuController.Builder() + .fromGenesisFile( + GenesisConfigFile.fromResource("/privacy_reorg_genesis.json"), SyncMode.FULL) + .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) + .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) + .storageProvider(new InMemoryKeyValueStorageProvider()) + .networkId(BigInteger.ONE) + .miningParameters(MiningParameters.newDefault()) + .nodeKey(NodeKeyUtils.generate()) + .metricsSystem(new NoOpMetricsSystem()) + .dataDirectory(folder) + .clock(TestClock.fixed()) + .privacyParameters(privacyParameters) + .transactionPoolConfiguration(TransactionPoolConfiguration.DEFAULT) + .gasLimitCalculator(GasLimitCalculator.constant()) + .evmConfiguration(EvmConfiguration.DEFAULT) + .networkConfiguration(NetworkingConfiguration.create()) + .build(); } @Test @@ -196,8 +204,7 @@ public void privacyGroupHeadIsTracked() { // Setup an initial blockchain with one private transaction final ProtocolContext protocolContext = besuController.getProtocolContext(); final DefaultBlockchain blockchain = (DefaultBlockchain) protocolContext.getBlockchain(); - final PrivateStateStorage privateStateStorage = - component.getPrivacyParameters().getPrivateStateStorage(); + final PrivateStateStorage privateStateStorage = privacyParameters.getPrivateStateStorage(); final Block firstBlock = gen.block( @@ -237,7 +244,7 @@ public void reorgToChainAtEqualHeight() { // Setup an initial blockchain with one private transaction final ProtocolContext protocolContext = besuController.getProtocolContext(); final DefaultBlockchain blockchain = (DefaultBlockchain) protocolContext.getBlockchain(); - assertThat(blockchain.getChainHeadBlockNumber()).isEqualTo(0); + final Block firstBlock = gen.block( getBlockOptionsWithTransaction( @@ -245,9 +252,8 @@ public void reorgToChainAtEqualHeight() { privacyMarkerTransaction, FIRST_BLOCK_WITH_SINGLE_TRANSACTION_STATE_ROOT)); - var importResult = appendBlock(besuController, blockchain, protocolContext, firstBlock); - assertThat(importResult.isImported()).isTrue(); - assertThat(blockchain.getChainHeadBlockNumber()).isEqualTo(1); + appendBlock(besuController, blockchain, protocolContext, firstBlock); + // Check that the private state root is not the empty state assertPrivateStateRoot( privateStateRootResolver, blockchain, STATE_ROOT_AFTER_TRANSACTION_APPENDED_TO_EMPTY_STATE); @@ -388,12 +394,12 @@ public void reorgToLongerChain() { } @SuppressWarnings("unchecked") - private BlockImportResult appendBlock( + private void appendBlock( final BesuController besuController, final DefaultBlockchain blockchain, final ProtocolContext protocolContext, final Block block) { - return besuController + besuController .getProtocolSchedule() .getByBlockHeader(blockchain.getChainHeadHeader()) .getBlockImporter() @@ -481,93 +487,4 @@ private BlockDataGenerator.BlockOptions getBlockOptions( .hasOmmers(false) .setLogsBloom(LogsBloomFilter.empty()); } - - @Singleton - @Component( - modules = { - PrivacyReorgTest.PrivacyReorgParametersModule.class, - PrivacyReorgTest.PrivacyReorgTestBesuControllerModule.class, - PrivacyReorgTest.PrivacyReorgTestGenesisConfigModule.class, - EnclaveModule.class, - PrivacyTestModule.class, - MockBesuCommandModule.class, - NoOpMetricsSystemModule.class, - BonsaiCachedMerkleTrieLoaderModule.class, - BlobCacheModule.class, - BesuPluginContextModule.class - }) - interface PrivacyReorgTestComponent extends BesuComponent { - - BesuController getBesuController(); - - PrivacyParameters getPrivacyParameters(); - } - - @Module - static class PrivacyReorgParametersModule { - - // TODO: copypasta, get this from the enclave factory - private static final Bytes ENCLAVE_PUBLIC_KEY = - Bytes.fromBase64String("A1aVtMxLCUHmBVHXoZzzBgPbW/wj5axDpW9X8l91SGo="); - - @Provides - PrivacyParameters providePrivacyReorgParameters( - final PrivacyStorageProvider storageProvider, final EnclaveFactory enclaveFactory) { - - PrivacyParameters retval = - new PrivacyParameters.Builder() - .setEnabled(true) - .setStorageProvider(storageProvider) - .setEnclaveUrl(URI.create("http//1.1.1.1:1234")) - .setEnclaveFactory(enclaveFactory) - .build(); - retval.setPrivacyUserId(ENCLAVE_PUBLIC_KEY.toBase64String()); - return retval; - } - } - - @Module - static class PrivacyReorgTestBesuControllerModule { - - @Provides - @Singleton - @SuppressWarnings("CloseableProvides") - BesuController provideBesuController( - final PrivacyParameters privacyParameters, - final GenesisConfigFile genesisConfigFile, - final PrivacyReorgTestComponent context, - final @Named("dataDir") Path dataDir) { - - // dataStorageConfiguration default - // named privacyReorgParams - BesuController retval = - new BesuController.Builder() - .fromGenesisFile(genesisConfigFile, SyncMode.FULL) - .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) - .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) - .storageProvider(new InMemoryKeyValueStorageProvider()) - .networkId(BigInteger.ONE) - .miningParameters(MiningParameters.newDefault()) - .nodeKey(NodeKeyUtils.generate()) - .metricsSystem(new NoOpMetricsSystem()) - .dataDirectory(dataDir) - .clock(TestClock.fixed()) - .privacyParameters(privacyParameters) - .transactionPoolConfiguration(TransactionPoolConfiguration.DEFAULT) - .gasLimitCalculator(GasLimitCalculator.constant()) - .evmConfiguration(EvmConfiguration.DEFAULT) - .networkConfiguration(NetworkingConfiguration.create()) - .besuComponent(context) - .build(); - return retval; - } - } - - @Module - static class PrivacyReorgTestGenesisConfigModule { - @Provides - GenesisConfigFile providePrivacyReorgGenesisConfigFile() { - return GenesisConfigFile.fromResource("/privacy_reorg_genesis.json"); - } - } } diff --git a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java index 4d488ced3bc2..dc5b7003c84d 100644 --- a/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java +++ b/besu/src/test/java/org/hyperledger/besu/PrivacyTest.java @@ -1,5 +1,5 @@ /* - * Copyright contributors to Hyperledger Besu. + * Copyright ConsenSys AG. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at @@ -16,17 +16,18 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.hyperledger.besu.ethereum.core.PrivacyParameters.DEFAULT_PRIVACY; - -import org.hyperledger.besu.components.BesuComponent; -import org.hyperledger.besu.components.BesuPluginContextModule; -import org.hyperledger.besu.components.MockBesuCommandModule; -import org.hyperledger.besu.components.NoOpMetricsSystemModule; -import org.hyperledger.besu.components.PrivacyParametersModule; -import org.hyperledger.besu.components.PrivacyTestModule; -import org.hyperledger.besu.config.GenesisConfigFile; +import static org.hyperledger.besu.ethereum.core.PrivacyParameters.FLEXIBLE_PRIVACY; +import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_BACKGROUND_THREAD_COUNT; +import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_CACHE_CAPACITY; +import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_IS_HIGH_SPEC; +import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_MAX_OPEN_FILES; + +import org.hyperledger.besu.cli.config.EthNetworkConfig; +import org.hyperledger.besu.cli.config.NetworkName; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.datatypes.Address; +import org.hyperledger.besu.enclave.EnclaveFactory; import org.hyperledger.besu.ethereum.GasLimitCalculator; import org.hyperledger.besu.ethereum.core.BlockHeader; import org.hyperledger.besu.ethereum.core.BlockHeaderTestFixture; @@ -36,47 +37,126 @@ import org.hyperledger.besu.ethereum.eth.EthProtocolConfiguration; import org.hyperledger.besu.ethereum.eth.sync.SyncMode; import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration; -import org.hyperledger.besu.ethereum.eth.transactions.BlobCacheModule; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPoolConfiguration; import org.hyperledger.besu.ethereum.p2p.config.NetworkingConfiguration; -import org.hyperledger.besu.ethereum.trie.diffbased.bonsai.cache.BonsaiCachedMerkleTrieLoaderModule; +import org.hyperledger.besu.ethereum.privacy.storage.PrivacyStorageProvider; +import org.hyperledger.besu.ethereum.privacy.storage.keyvalue.PrivacyKeyValueStorageProviderBuilder; +import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueSegmentIdentifier; import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; import org.hyperledger.besu.evm.internal.EvmConfiguration; import org.hyperledger.besu.evm.precompile.PrecompiledContract; import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; +import org.hyperledger.besu.plugin.services.storage.rocksdb.RocksDBKeyValuePrivacyStorageFactory; +import org.hyperledger.besu.plugin.services.storage.rocksdb.RocksDBKeyValueStorageFactory; +import org.hyperledger.besu.plugin.services.storage.rocksdb.RocksDBMetricsFactory; +import org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBFactoryConfiguration; +import org.hyperledger.besu.services.BesuConfigurationImpl; import org.hyperledger.besu.testutil.TestClock; +import java.io.IOException; import java.math.BigInteger; +import java.net.URI; +import java.net.URISyntaxException; +import java.nio.file.Files; import java.nio.file.Path; -import javax.inject.Named; -import javax.inject.Singleton; +import java.util.Arrays; -import dagger.Component; -import dagger.Module; -import dagger.Provides; import io.vertx.core.Vertx; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; -class PrivacyTest { +public class PrivacyTest { private final Vertx vertx = Vertx.vertx(); + @TempDir private Path dataDir; + @AfterEach public void cleanUp() { vertx.close(); } @Test - void defaultPrivacy() { - final BesuController besuController = - DaggerPrivacyTest_PrivacyTestComponent.builder().build().getBesuController(); + public void defaultPrivacy() throws IOException, URISyntaxException { + final BesuController besuController = setUpControllerWithPrivacyEnabled(false); final PrecompiledContract precompiledContract = getPrecompile(besuController, DEFAULT_PRIVACY); assertThat(precompiledContract.getName()).isEqualTo("Privacy"); } + @Test + public void flexibleEnabledPrivacy() throws IOException, URISyntaxException { + final BesuController besuController = setUpControllerWithPrivacyEnabled(true); + + final PrecompiledContract flexiblePrecompiledContract = + getPrecompile(besuController, FLEXIBLE_PRIVACY); + + assertThat(flexiblePrecompiledContract.getName()).isEqualTo("FlexiblePrivacy"); + } + + private BesuController setUpControllerWithPrivacyEnabled(final boolean flexibleEnabled) + throws IOException, URISyntaxException { + final Path dbDir = Files.createTempDirectory(dataDir, "database"); + final var miningParameters = MiningParameters.newDefault(); + final var dataStorageConfiguration = DataStorageConfiguration.DEFAULT_FOREST_CONFIG; + final PrivacyParameters privacyParameters = + new PrivacyParameters.Builder() + .setEnabled(true) + .setEnclaveUrl(new URI("http://127.0.0.1:8000")) + .setStorageProvider( + createKeyValueStorageProvider( + dataDir, dbDir, dataStorageConfiguration, miningParameters)) + .setEnclaveFactory(new EnclaveFactory(vertx)) + .setFlexiblePrivacyGroupsEnabled(flexibleEnabled) + .build(); + return new BesuController.Builder() + .fromEthNetworkConfig(EthNetworkConfig.getNetworkConfig(NetworkName.MAINNET), SyncMode.FULL) + .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) + .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) + .storageProvider(new InMemoryKeyValueStorageProvider()) + .networkId(BigInteger.ONE) + .miningParameters(miningParameters) + .dataStorageConfiguration(dataStorageConfiguration) + .nodeKey(NodeKeyUtils.generate()) + .metricsSystem(new NoOpMetricsSystem()) + .dataDirectory(dataDir) + .clock(TestClock.fixed()) + .privacyParameters(privacyParameters) + .transactionPoolConfiguration(TransactionPoolConfiguration.DEFAULT) + .gasLimitCalculator(GasLimitCalculator.constant()) + .evmConfiguration(EvmConfiguration.DEFAULT) + .networkConfiguration(NetworkingConfiguration.create()) + .build(); + } + + private PrivacyStorageProvider createKeyValueStorageProvider( + final Path dataDir, + final Path dbDir, + final DataStorageConfiguration dataStorageConfiguration, + final MiningParameters miningParameters) { + final var besuConfiguration = new BesuConfigurationImpl(); + besuConfiguration + .init(dataDir, dbDir, dataStorageConfiguration) + .withMiningParameters(miningParameters); + return new PrivacyKeyValueStorageProviderBuilder() + .withStorageFactory( + new RocksDBKeyValuePrivacyStorageFactory( + new RocksDBKeyValueStorageFactory( + () -> + new RocksDBFactoryConfiguration( + DEFAULT_MAX_OPEN_FILES, + DEFAULT_BACKGROUND_THREAD_COUNT, + DEFAULT_CACHE_CAPACITY, + DEFAULT_IS_HIGH_SPEC), + Arrays.asList(KeyValueSegmentIdentifier.values()), + RocksDBMetricsFactory.PRIVATE_ROCKS_DB_METRICS))) + .withCommonConfiguration(besuConfiguration) + .withMetricsSystem(new NoOpMetricsSystem()) + .build(); + } + private PrecompiledContract getPrecompile( final BesuController besuController, final Address defaultPrivacy) { return besuController @@ -89,55 +169,4 @@ private PrecompiledContract getPrecompile( private BlockHeader blockHeader(final long number) { return new BlockHeaderTestFixture().number(number).buildHeader(); } - - @Singleton - @Component( - modules = { - PrivacyParametersModule.class, - PrivacyTest.PrivacyTestBesuControllerModule.class, - PrivacyTestModule.class, - MockBesuCommandModule.class, - BonsaiCachedMerkleTrieLoaderModule.class, - NoOpMetricsSystemModule.class, - BesuPluginContextModule.class, - BlobCacheModule.class - }) - interface PrivacyTestComponent extends BesuComponent { - - BesuController getBesuController(); - } - - @Module - static class PrivacyTestBesuControllerModule { - - @Provides - @Singleton - @SuppressWarnings("CloseableProvides") - BesuController provideBesuController( - final PrivacyParameters privacyParameters, - final DataStorageConfiguration dataStorageConfiguration, - final PrivacyTestComponent context, - @Named("dataDir") final Path dataDir) { - - return new BesuController.Builder() - .fromGenesisFile(GenesisConfigFile.mainnet(), SyncMode.FULL) - .synchronizerConfiguration(SynchronizerConfiguration.builder().build()) - .ethProtocolConfiguration(EthProtocolConfiguration.defaultConfig()) - .storageProvider(new InMemoryKeyValueStorageProvider()) - .networkId(BigInteger.ONE) - .miningParameters(MiningParameters.newDefault()) - .dataStorageConfiguration(dataStorageConfiguration) - .nodeKey(NodeKeyUtils.generate()) - .metricsSystem(new NoOpMetricsSystem()) - .dataDirectory(dataDir) - .clock(TestClock.fixed()) - .privacyParameters(privacyParameters) - .transactionPoolConfiguration(TransactionPoolConfiguration.DEFAULT) - .gasLimitCalculator(GasLimitCalculator.constant()) - .evmConfiguration(EvmConfiguration.DEFAULT) - .networkConfiguration(NetworkingConfiguration.create()) - .besuComponent(context) - .build(); - } - } } diff --git a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java index 5fefc7ef2245..5b2a56078f52 100644 --- a/besu/src/test/java/org/hyperledger/besu/RunnerTest.java +++ b/besu/src/test/java/org/hyperledger/besu/RunnerTest.java @@ -22,10 +22,8 @@ import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_CACHE_CAPACITY; import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_IS_HIGH_SPEC; import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_MAX_OPEN_FILES; -import static org.mockito.Mockito.mock; import org.hyperledger.besu.cli.config.EthNetworkConfig; -import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.config.MergeConfigOptions; @@ -485,7 +483,6 @@ private BesuController getController( .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) .randomPeerPriority(Boolean.FALSE) - .besuComponent(mock(BesuComponent.class)) .maxPeers(25) .maxRemotelyInitiatedPeers(15) .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 bbc7dea1abb7..05057f15c83d 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainexport/RlpBlockExporterTest.java @@ -16,12 +16,10 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; import org.hyperledger.besu.chainimport.RlpBlockImporter; import org.hyperledger.besu.cli.config.EthNetworkConfig; import org.hyperledger.besu.cli.config.NetworkName; -import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; import org.hyperledger.besu.ethereum.GasLimitCalculator; @@ -104,7 +102,6 @@ private static BesuController createController(final @TempDir Path dataDir) thro .gasLimitCalculator(GasLimitCalculator.constant()) .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) - .besuComponent(mock(BesuComponent.class)) .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 7b1a4bc7d2cb..73015afd005c 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/JsonBlockImporterTest.java @@ -17,9 +17,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; -import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.config.JsonUtil; import org.hyperledger.besu.controller.BesuController; @@ -465,7 +463,6 @@ protected BesuController createController(final GenesisConfigFile genesisConfigF .gasLimitCalculator(GasLimitCalculator.constant()) .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) - .besuComponent(mock(BesuComponent.class)) .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 7d4fabb2225d..e37b8a5fd08d 100644 --- a/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java +++ b/besu/src/test/java/org/hyperledger/besu/chainimport/RlpBlockImporterTest.java @@ -16,11 +16,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; -import static org.mockito.Mockito.mock; import org.hyperledger.besu.cli.config.EthNetworkConfig; import org.hyperledger.besu.cli.config.NetworkName; -import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.MergeConfigOptions; import org.hyperledger.besu.controller.BesuController; import org.hyperledger.besu.cryptoservices.NodeKeyUtils; @@ -79,7 +77,6 @@ public void blockImport() throws IOException { .gasLimitCalculator(GasLimitCalculator.constant()) .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) - .besuComponent(mock(BesuComponent.class)) .build(); final RlpBlockImporter.ImportResult result = rlpBlockImporter.importBlockchain(source, targetController, false); @@ -113,7 +110,6 @@ public void blockImportRejectsBadPow() throws IOException { .gasLimitCalculator(GasLimitCalculator.constant()) .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) - .besuComponent(mock(BesuComponent.class)) .build(); assertThatThrownBy( @@ -144,7 +140,6 @@ public void blockImportCanSkipPow() throws IOException { .gasLimitCalculator(GasLimitCalculator.constant()) .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) - .besuComponent(mock(BesuComponent.class)) .build(); final RlpBlockImporter.ImportResult result = diff --git a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java index 23ba593a3849..e6e0e8595172 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java @@ -171,6 +171,60 @@ public void tearDown() { MergeConfigOptions.setMergeEnabled(false); } + @Test + public void testGenesisOverrideOptions() throws Exception { + parseCommand("--override-genesis-config", "shanghaiTime=123"); + + final ArgumentCaptor networkArg = + ArgumentCaptor.forClass(EthNetworkConfig.class); + + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); + verify(mockControllerBuilder).build(); + + final EthNetworkConfig config = networkArg.getValue(); + // mainnet defaults + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(1)); + + // assert that shanghaiTime override is applied + final GenesisConfigFile actualGenesisConfigFile = (config.genesisConfigFile()); + assertThat(actualGenesisConfigFile).isNotNull(); + assertThat(actualGenesisConfigFile.getConfigOptions().getShanghaiTime()).isNotEmpty(); + assertThat(actualGenesisConfigFile.getConfigOptions().getShanghaiTime().getAsLong()) + .isEqualTo(123); + + assertThat(commandOutput.toString(UTF_8)).isEmpty(); + assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + } + + @Test + public void testGenesisOverrideOptionsWithCustomGenesis() throws Exception { + final Path genesisFile = createFakeGenesisFile(GENESIS_VALID_JSON); + + parseCommand( + "--genesis-file", genesisFile.toString(), "--override-genesis-config", "shanghaiTime=123"); + + final ArgumentCaptor networkArg = + ArgumentCaptor.forClass(EthNetworkConfig.class); + + verify(mockControllerBuilderFactory).fromEthNetworkConfig(networkArg.capture(), any()); + verify(mockControllerBuilder).build(); + + final EthNetworkConfig config = networkArg.getValue(); + assertThat(config.bootNodes()).isEmpty(); + assertThat(config.dnsDiscoveryUrl()).isNull(); + assertThat(config.networkId()).isEqualTo(BigInteger.valueOf(3141592)); + + // then assert that the shanghaiTime is applied + final GenesisConfigFile actualGenesisConfigFile = (config.genesisConfigFile()); + assertThat(actualGenesisConfigFile).isNotNull(); + assertThat(actualGenesisConfigFile.getConfigOptions().getShanghaiTime()).isNotEmpty(); + assertThat(actualGenesisConfigFile.getConfigOptions().getShanghaiTime().getAsLong()) + .isEqualTo(123); + + assertThat(commandOutput.toString(UTF_8)).isEmpty(); + assertThat(commandErrorOutput.toString(UTF_8)).isEmpty(); + } + @Test public void callingHelpSubCommandMustDisplayUsage() { parseCommand("--help"); diff --git a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/DataStorageOptionsTest.java b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/DataStorageOptionsTest.java index 2086381825f0..29fa3d660715 100644 --- a/besu/src/test/java/org/hyperledger/besu/cli/options/stable/DataStorageOptionsTest.java +++ b/besu/src/test/java/org/hyperledger/besu/cli/options/stable/DataStorageOptionsTest.java @@ -126,13 +126,20 @@ public void bonsaiCodeUsingCodeHashEnabledCanBeDisabled() { "false"); } + @Test + public void receiptCompactionCanBeEnabledWithImplicitTrueValue() { + internalTestSuccess( + dataStorageConfiguration -> + assertThat(dataStorageConfiguration.getReceiptCompactionEnabled()).isEqualTo(true), + "--receipt-compaction-enabled"); + } + @Test public void receiptCompactionCanBeEnabled() { internalTestSuccess( dataStorageConfiguration -> assertThat(dataStorageConfiguration.getReceiptCompactionEnabled()).isEqualTo(true), - "--receipt-compaction-enabled", - "true"); + "--receipt-compaction-enabled=true"); } @Test @@ -140,8 +147,7 @@ public void receiptCompactionCanBeDisabled() { internalTestSuccess( dataStorageConfiguration -> assertThat(dataStorageConfiguration.getReceiptCompactionEnabled()).isEqualTo(false), - "--receipt-compaction-enabled", - "false"); + "--receipt-compaction-enabled=false"); } @Override diff --git a/besu/src/test/java/org/hyperledger/besu/components/EnclaveModule.java b/besu/src/test/java/org/hyperledger/besu/components/EnclaveModule.java deleted file mode 100644 index 20f9c1bf4974..000000000000 --- a/besu/src/test/java/org/hyperledger/besu/components/EnclaveModule.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright contributors to Hyperledger 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.components; - -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -import org.hyperledger.besu.crypto.KeyPair; -import org.hyperledger.besu.crypto.SignatureAlgorithm; -import org.hyperledger.besu.crypto.SignatureAlgorithmFactory; -import org.hyperledger.besu.datatypes.Wei; -import org.hyperledger.besu.enclave.Enclave; -import org.hyperledger.besu.enclave.EnclaveFactory; -import org.hyperledger.besu.enclave.types.ReceiveResponse; -import org.hyperledger.besu.ethereum.privacy.PrivateTransaction; -import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput; -import org.hyperledger.besu.plugin.data.Restriction; - -import java.math.BigInteger; -import java.nio.charset.StandardCharsets; -import java.util.Collections; -import java.util.function.Supplier; - -import com.google.common.base.Suppliers; -import dagger.Module; -import dagger.Provides; -import org.apache.tuweni.bytes.Bytes; -import org.apache.tuweni.bytes.Bytes32; - -@Module -public class EnclaveModule { - - private static final Supplier SIGNATURE_ALGORITHM = - Suppliers.memoize(SignatureAlgorithmFactory::getInstance); - - private static final Bytes ENCLAVE_PUBLIC_KEY = - Bytes.fromBase64String("A1aVtMxLCUHmBVHXoZzzBgPbW/wj5axDpW9X8l91SGo="); - - private static final Bytes32 PRIVACY_GROUP_BYTES32 = - Bytes32.fromHexString("0xf250d523ae9164722b06ca25cfa2a7f3c45df96b09e215236f886c876f715bfa"); - - private static final Bytes MOCK_PAYLOAD = - Bytes.fromHexString( - "0x608060405234801561001057600080fd5b5060008054600160a060020a03191633179055610199806100326000396000f3fe6080604052600436106100565763ffffffff7c01000000000000000000000000000000000000000000000000000000006000350416633fa4f245811461005b5780636057361d1461008257806367e404ce146100ae575b600080fd5b34801561006757600080fd5b506100706100ec565b60408051918252519081900360200190f35b34801561008e57600080fd5b506100ac600480360360208110156100a557600080fd5b50356100f2565b005b3480156100ba57600080fd5b506100c3610151565b6040805173ffffffffffffffffffffffffffffffffffffffff9092168252519081900360200190f35b60025490565b604080513381526020810183905281517fc9db20adedc6cf2b5d25252b101ab03e124902a73fcb12b753f3d1aaa2d8f9f5929181900390910190a16002556001805473ffffffffffffffffffffffffffffffffffffffff191633179055565b60015473ffffffffffffffffffffffffffffffffffffffff169056fea165627a7a72305820c7f729cb24e05c221f5aa913700793994656f233fe2ce3b9fd9a505ea17e8d8a0029"); - - private static final KeyPair KEY_PAIR = - SIGNATURE_ALGORITHM - .get() - .createKeyPair( - SIGNATURE_ALGORITHM - .get() - .createPrivateKey( - new BigInteger( - "8f2a55949038a9610f50fb23b5883af3b4ecb3c3bb792cbcefbd1542c692be63", 16))); - - private static final PrivateTransaction PRIVATE_TRANSACTION = - PrivateTransaction.builder() - .chainId(BigInteger.valueOf(1337)) - .gasLimit(1000) - .gasPrice(Wei.ZERO) - .nonce(0) - .payload(MOCK_PAYLOAD) - .to(null) - .privateFrom(ENCLAVE_PUBLIC_KEY) - .privateFor(Collections.singletonList(ENCLAVE_PUBLIC_KEY)) - .restriction(Restriction.RESTRICTED) - .value(Wei.ZERO) - .signAndBuild(KEY_PAIR); - - @Provides - EnclaveFactory provideMockableEnclaveFactory() { - Enclave mockEnclave = mock(Enclave.class); - final BytesValueRLPOutput rlpOutput = new BytesValueRLPOutput(); - PRIVATE_TRANSACTION.writeTo(rlpOutput); - when(mockEnclave.receive(any())) - .thenReturn( - new ReceiveResponse( - rlpOutput.encoded().toBase64String().getBytes(StandardCharsets.UTF_8), - PRIVACY_GROUP_BYTES32.toBase64String(), - ENCLAVE_PUBLIC_KEY.toBase64String())); - EnclaveFactory enclaveFactory = mock(EnclaveFactory.class); - when(enclaveFactory.createVertxEnclave(any())).thenReturn(mockEnclave); - return enclaveFactory; - } -} diff --git a/besu/src/test/java/org/hyperledger/besu/components/MockBesuCommandModule.java b/besu/src/test/java/org/hyperledger/besu/components/MockBesuCommandModule.java deleted file mode 100644 index 743b4ee8de91..000000000000 --- a/besu/src/test/java/org/hyperledger/besu/components/MockBesuCommandModule.java +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright contributors to Hyperledger 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.components; - -import static org.mockito.Mockito.mock; - -import org.hyperledger.besu.cli.BesuCommand; -import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration; - -import javax.inject.Named; -import javax.inject.Singleton; - -import dagger.Module; -import dagger.Provides; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -@Module -public class MockBesuCommandModule { - - @Provides - BesuCommand provideBesuCommand() { - return mock(BesuCommand.class); - } - - @Provides - @Singleton - MetricsConfiguration provideMetricsConfiguration() { - return MetricsConfiguration.builder().build(); - } - - @Provides - @Named("besuCommandLogger") - @Singleton - Logger provideBesuCommandLogger() { - return LoggerFactory.getLogger(MockBesuCommandModule.class); - } -} diff --git a/besu/src/test/java/org/hyperledger/besu/components/PrivacyParametersModule.java b/besu/src/test/java/org/hyperledger/besu/components/PrivacyParametersModule.java deleted file mode 100644 index 0b8fcf744ff4..000000000000 --- a/besu/src/test/java/org/hyperledger/besu/components/PrivacyParametersModule.java +++ /dev/null @@ -1,47 +0,0 @@ -/* - * Copyright contributors to Hyperledger 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.components; - -import org.hyperledger.besu.enclave.EnclaveFactory; -import org.hyperledger.besu.ethereum.core.PrivacyParameters; -import org.hyperledger.besu.ethereum.privacy.storage.PrivacyStorageProvider; - -import java.net.URI; -import java.net.URISyntaxException; - -import dagger.Module; -import dagger.Provides; -import io.vertx.core.Vertx; - -/** Provides a general use PrivacyParameters instance for testing. */ -@Module -public class PrivacyParametersModule { - - @Provides - PrivacyParameters providePrivacyParameters( - final PrivacyStorageProvider storageProvider, final Vertx vertx) { - try { - return new PrivacyParameters.Builder() - .setEnabled(true) - .setEnclaveUrl(new URI("http://127.0.0.1:8000")) - .setStorageProvider(storageProvider) - .setEnclaveFactory(new EnclaveFactory(vertx)) - .setFlexiblePrivacyGroupsEnabled(false) - .build(); - } catch (URISyntaxException e) { - throw new RuntimeException(e); - } - } -} diff --git a/besu/src/test/java/org/hyperledger/besu/components/PrivacyTestModule.java b/besu/src/test/java/org/hyperledger/besu/components/PrivacyTestModule.java deleted file mode 100644 index 13cafe1ab455..000000000000 --- a/besu/src/test/java/org/hyperledger/besu/components/PrivacyTestModule.java +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright contributors to Hyperledger 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.components; - -import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_BACKGROUND_THREAD_COUNT; -import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_CACHE_CAPACITY; -import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_IS_HIGH_SPEC; -import static org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBCLIOptions.DEFAULT_MAX_OPEN_FILES; - -import org.hyperledger.besu.ethereum.privacy.storage.PrivacyStorageProvider; -import org.hyperledger.besu.ethereum.privacy.storage.keyvalue.PrivacyKeyValueStorageProviderBuilder; -import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueSegmentIdentifier; -import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration; -import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; -import org.hyperledger.besu.plugin.services.storage.rocksdb.RocksDBKeyValuePrivacyStorageFactory; -import org.hyperledger.besu.plugin.services.storage.rocksdb.RocksDBKeyValueStorageFactory; -import org.hyperledger.besu.plugin.services.storage.rocksdb.RocksDBMetricsFactory; -import org.hyperledger.besu.plugin.services.storage.rocksdb.configuration.RocksDBFactoryConfiguration; -import org.hyperledger.besu.services.BesuConfigurationImpl; - -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.Arrays; -import javax.inject.Named; -import javax.inject.Singleton; - -import dagger.Module; -import dagger.Provides; -import io.vertx.core.Vertx; - -@Module -public class PrivacyTestModule { - - @Provides - @Named("dataDir") - Path provideDataDir() { - try { - return Files.createTempDirectory("PrivacyTestDatadir"); - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Provides - Vertx provideVertx() { - return Vertx.vertx(); - } - - @Provides - DataStorageConfiguration provideDataStorageConfiguration() { - return DataStorageConfiguration.DEFAULT_FOREST_CONFIG; - } - - @Provides - @Singleton - @Named("dbDir") - Path provideDbDir(@Named("dataDir") final Path dataDir) { - try { - final Path dbDir = Files.createTempDirectory(dataDir, "database"); - return dbDir; - } catch (IOException e) { - throw new RuntimeException(e); - } - } - - @Provides - @Singleton - @Named("flexibleEnabled") - Boolean provideFlexibleEnabled() { - return true; - } - - @Provides - @Singleton - @SuppressWarnings("CloseableProvides") - PrivacyStorageProvider provideKeyValueStorageProvider( - @Named("dbDir") final Path dbDir, - final DataStorageConfiguration dataStorageConfiguration, - @Named("dataDir") final Path dataDir) { - final var besuConfiguration = new BesuConfigurationImpl(); - besuConfiguration.init(dataDir, dbDir, dataStorageConfiguration); - return new PrivacyKeyValueStorageProviderBuilder() - .withStorageFactory( - new RocksDBKeyValuePrivacyStorageFactory( - new RocksDBKeyValueStorageFactory( - () -> - new RocksDBFactoryConfiguration( - DEFAULT_MAX_OPEN_FILES, - DEFAULT_BACKGROUND_THREAD_COUNT, - DEFAULT_CACHE_CAPACITY, - DEFAULT_IS_HIGH_SPEC), - Arrays.asList(KeyValueSegmentIdentifier.values()), - RocksDBMetricsFactory.PRIVATE_ROCKS_DB_METRICS))) - .withCommonConfiguration(besuConfiguration) - .withMetricsSystem(new NoOpMetricsSystem()) - .build(); - } -} 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 c7caf62ec2a7..f9e671f522d7 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/AbstractBftBesuControllerBuilderTest.java @@ -19,7 +19,6 @@ import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; -import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.CheckpointConfigOptions; import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.config.GenesisConfigOptions; @@ -105,7 +104,6 @@ public void setup() throws JsonProcessingException { lenient().when(genesisConfigFile.getDifficulty()).thenReturn(Bytes.of(0).toHexString()); lenient().when(genesisConfigFile.getMixHash()).thenReturn(Hash.ZERO.toHexString()); lenient().when(genesisConfigFile.getNonce()).thenReturn(Long.toHexString(1)); - lenient().when(genesisConfigFile.getConfigOptions(any())).thenReturn(genesisConfigOptions); lenient().when(genesisConfigFile.getConfigOptions()).thenReturn(genesisConfigOptions); lenient().when(genesisConfigOptions.getCheckpointOptions()).thenReturn(checkpointConfigOptions); lenient() @@ -158,7 +156,6 @@ public void setup() throws JsonProcessingException { .storageProvider(storageProvider) .gasLimitCalculator(gasLimitCalculator) .evmConfiguration(EvmConfiguration.DEFAULT) - .besuComponent(mock(BesuComponent.class)) .networkConfiguration(NetworkingConfiguration.create()); } 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 aa79b944a111..39904df798db 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilderTest.java @@ -20,7 +20,6 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.CheckpointConfigOptions; import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.config.GenesisConfigOptions; @@ -114,7 +113,6 @@ public void setup() throws JsonProcessingException { "0x0000000000000000000000000000000000000000000000000000000000000000b9b81ee349c3807e46bc71aa2632203c5b4620340000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"); lenient().when(genesisConfigFile.getMixHash()).thenReturn(Hash.ZERO.toHexString()); lenient().when(genesisConfigFile.getNonce()).thenReturn(Long.toHexString(1)); - lenient().when(genesisConfigFile.getConfigOptions(any())).thenReturn(genesisConfigOptions); lenient().when(genesisConfigFile.getConfigOptions()).thenReturn(genesisConfigOptions); lenient().when(genesisConfigOptions.getCheckpointOptions()).thenReturn(checkpointConfigOptions); lenient() @@ -191,7 +189,6 @@ public void setup() throws JsonProcessingException { .storageProvider(storageProvider) .gasLimitCalculator(gasLimitCalculator) .evmConfiguration(EvmConfiguration.DEFAULT) - .besuComponent(mock(BesuComponent.class)) .networkConfiguration(NetworkingConfiguration.create()); } 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 c788f417103a..544b63301529 100644 --- a/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java +++ b/besu/src/test/java/org/hyperledger/besu/controller/MergeBesuControllerBuilderTest.java @@ -23,7 +23,6 @@ import static org.mockito.Mockito.spy; import static org.mockito.Mockito.when; -import org.hyperledger.besu.components.BesuComponent; import org.hyperledger.besu.config.CheckpointConfigOptions; import org.hyperledger.besu.config.GenesisConfigFile; import org.hyperledger.besu.config.GenesisConfigOptions; @@ -125,7 +124,6 @@ public void setup() { lenient().when(genesisConfigFile.getExtraData()).thenReturn(Bytes.EMPTY.toHexString()); lenient().when(genesisConfigFile.getMixHash()).thenReturn(Hash.ZERO.toHexString()); lenient().when(genesisConfigFile.getNonce()).thenReturn(Long.toHexString(1)); - lenient().when(genesisConfigFile.getConfigOptions(any())).thenReturn(genesisConfigOptions); lenient().when(genesisConfigFile.getConfigOptions()).thenReturn(genesisConfigOptions); lenient().when(genesisConfigOptions.getCheckpointOptions()).thenReturn(checkpointConfigOptions); when(genesisConfigOptions.getTerminalTotalDifficulty()) @@ -191,7 +189,6 @@ MergeBesuControllerBuilder visitWithMockConfigs(final MergeBesuControllerBuilder .storageProvider(storageProvider) .evmConfiguration(EvmConfiguration.DEFAULT) .networkConfiguration(NetworkingConfiguration.create()) - .besuComponent(mock(BesuComponent.class)) .networkId(networkId); } diff --git a/build.gradle b/build.gradle index 7d2293b61e3c..6a4f279666aa 100644 --- a/build.gradle +++ b/build.gradle @@ -160,6 +160,10 @@ allprojects { url 'https://splunk.jfrog.io/splunk/ext-releases-local' content { includeGroupByRegex('com\\.splunk\\..*') } } + maven { + url 'https://gitlab.com/api/v4/projects/19871573/packages/maven' + content { includeGroupByRegex('com\\.gitlab\\.javafuzz(\\..*)?') } + } mavenCentral() diff --git a/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java b/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java index bd1e117773bf..453c38dac202 100644 --- a/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java +++ b/config/src/main/java/org/hyperledger/besu/config/GenesisConfigFile.java @@ -18,7 +18,6 @@ import java.net.URL; import java.util.Arrays; -import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -41,6 +40,7 @@ public class GenesisConfigFile { private final GenesisReader loader; private final ObjectNode genesisRoot; + private Map overrides; private GenesisConfigFile(final GenesisReader loader) { this.loader = loader; @@ -107,36 +107,42 @@ public static GenesisConfigFile fromConfig(final ObjectNode config) { } /** - * Gets config options. + * Gets config options, including any overrides. * * @return the config options */ public GenesisConfigOptions getConfigOptions() { - return getConfigOptions(Collections.emptyMap()); - } - - /** - * Gets config options. - * - * @param overrides the overrides - * @return the config options - */ - public GenesisConfigOptions getConfigOptions(final Map overrides) { final ObjectNode config = loader.getConfig(); - - Map overridesRef = overrides; + // are there any overrides to apply? + if (this.overrides == null) { + return JsonGenesisConfigOptions.fromJsonObject(config); + } + // otherwise apply overrides + Map overridesRef = this.overrides; // if baseFeePerGas has been explicitly configured, pass it as an override: final var optBaseFee = getBaseFeePerGas(); if (optBaseFee.isPresent()) { // streams and maps cannot handle null values. - overridesRef = new HashMap<>(overrides); + overridesRef = new HashMap<>(this.overrides); overridesRef.put("baseFeePerGas", optBaseFee.get().toShortHexString()); } return JsonGenesisConfigOptions.fromJsonObjectWithOverrides(config, overridesRef); } + /** + * Sets overrides for genesis options. + * + * @param overrides the overrides + * @return the config options + */ + public GenesisConfigFile withOverrides(final Map overrides) { + + this.overrides = overrides; + return this; + } + /** * Stream allocations stream. * diff --git a/config/src/main/resources/holesky.json b/config/src/main/resources/holesky.json index 6ae6942a8cf5..d91971b35156 100644 --- a/config/src/main/resources/holesky.json +++ b/config/src/main/resources/holesky.json @@ -20,7 +20,8 @@ "dns": "enrtree://AKA3AM6LPBYEUDMVNU3BSVQJ5AD45Y7YPOHJLEF6W26QOE4VTUDPE@all.holesky.ethdisco.net", "bootnodes": [ "enode://ac906289e4b7f12df423d654c5a962b6ebe5b3a74cc9e06292a85221f9a64a6f1cfdd6b714ed6dacef51578f92b34c60ee91e9ede9c7f8fadc4d347326d95e2b@146.190.13.128:30303", - "enode://a3435a0155a3e837c02f5e7f5662a2f1fbc25b48e4dc232016e1c51b544cb5b4510ef633ea3278c0e970fa8ad8141e2d4d0f9f95456c537ff05fdf9b31c15072@178.128.136.233:30303" + "enode://a3435a0155a3e837c02f5e7f5662a2f1fbc25b48e4dc232016e1c51b544cb5b4510ef633ea3278c0e970fa8ad8141e2d4d0f9f95456c537ff05fdf9b31c15072@178.128.136.233:30303", + "enode://7fa09f1e8bb179ab5e73f45d3a7169a946e7b3de5ef5cea3a0d4546677e4435ee38baea4dd10b3ddfdc1f1c5e869052932af8b8aeb6f9738598ec4590d0b11a6@65.109.94.124:30303" ] } }, diff --git a/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java b/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java index 9f014b7d4d25..3e6b488b9bd8 100644 --- a/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java +++ b/config/src/test/java/org/hyperledger/besu/config/GenesisConfigFileTest.java @@ -187,7 +187,9 @@ void shouldGetBaseFeeExplicitlyAtGenesis() { @Test void shouldOverrideConfigOptionsBaseFeeWhenSpecified() { GenesisConfigOptions withOverrides = - EMPTY_CONFIG.getConfigOptions(Map.of("baseFeePerGas", Wei.of(8).toString())); + EMPTY_CONFIG + .withOverrides(Map.of("baseFeePerGas", Wei.of(8).toString())) + .getConfigOptions(); assertThat(withOverrides.getBaseFeePerGas()).contains(Wei.of(8L)); } @@ -229,7 +231,8 @@ void assertMainnetTerminalTotalDifficulty() { void assertTerminalTotalDifficultyOverride() { GenesisConfigOptions sepoliaOverrideOptions = GenesisConfigFile.fromResource("/sepolia.json") - .getConfigOptions(Map.of("terminalTotalDifficulty", String.valueOf(Long.MAX_VALUE))); + .withOverrides(Map.of("terminalTotalDifficulty", String.valueOf(Long.MAX_VALUE))) + .getConfigOptions(); assertThat(sepoliaOverrideOptions.getTerminalTotalDifficulty()).isPresent(); assertThat(sepoliaOverrideOptions.getTerminalTotalDifficulty()) @@ -355,10 +358,12 @@ void testOverridePresent() { override.put("contractSizeLimit", bigBlockString); assertThat(config.getForkBlockNumbers()).isNotEmpty(); - assertThat(config.getConfigOptions(override).getIstanbulBlockNumber()).hasValue(bigBlock); - assertThat(config.getConfigOptions(override).getChainId()) + assertThat(config.withOverrides(override).getConfigOptions().getIstanbulBlockNumber()) + .hasValue(bigBlock); + assertThat(config.withOverrides(override).getConfigOptions().getChainId()) .hasValue(BigInteger.valueOf(bigBlock)); - assertThat(config.getConfigOptions(override).getContractSizeLimit()).hasValue(bigBlock); + assertThat(config.withOverrides(override).getConfigOptions().getContractSizeLimit()) + .hasValue(bigBlock); } @Test @@ -370,9 +375,11 @@ void testOverrideNull() { override.put("contractSizeLimit", null); assertThat(config.getForkBlockNumbers()).isNotEmpty(); - assertThat(config.getConfigOptions(override).getIstanbulBlockNumber()).isNotPresent(); - assertThat(config.getConfigOptions(override).getChainId()).isNotPresent(); - assertThat(config.getConfigOptions(override).getContractSizeLimit()).isNotPresent(); + assertThat(config.withOverrides(override).getConfigOptions().getIstanbulBlockNumber()) + .isNotPresent(); + assertThat(config.withOverrides(override).getConfigOptions().getChainId()).isNotPresent(); + assertThat(config.withOverrides(override).getConfigOptions().getContractSizeLimit()) + .isNotPresent(); } @Test @@ -388,10 +395,12 @@ void testOverrideCaseInsensitivity() { // all lower case override.put("contractsizelimit", bigBlockString); - assertThat(config.getConfigOptions(override).getIstanbulBlockNumber()).hasValue(bigBlock); - assertThat(config.getConfigOptions(override).getChainId()) + assertThat(config.withOverrides(override).getConfigOptions().getIstanbulBlockNumber()) + .hasValue(bigBlock); + assertThat(config.withOverrides(override).getConfigOptions().getChainId()) .hasValue(BigInteger.valueOf(bigBlock)); - assertThat(config.getConfigOptions(override).getContractSizeLimit()).hasValue(bigBlock); + assertThat(config.withOverrides(override).getConfigOptions().getContractSizeLimit()) + .hasValue(bigBlock); } @Test @@ -402,9 +411,11 @@ void testOverrideEmptyString() { override.put("chainId", ""); override.put("contractSizeLimit", ""); - assertThat(config.getConfigOptions(override).getIstanbulBlockNumber()).isNotPresent(); - assertThat(config.getConfigOptions(override).getChainId()).isNotPresent(); - assertThat(config.getConfigOptions(override).getContractSizeLimit()).isNotPresent(); + assertThat(config.withOverrides(override).getConfigOptions().getIstanbulBlockNumber()) + .isNotPresent(); + assertThat(config.withOverrides(override).getConfigOptions().getChainId()).isNotPresent(); + assertThat(config.withOverrides(override).getConfigOptions().getContractSizeLimit()) + .isNotPresent(); } @Test @@ -431,7 +442,8 @@ void testConstantinopleFixShouldNotBeSupportedAlongPetersburg() { override.put("constantinopleFixBlock", "1000"); assertThatExceptionOfType(RuntimeException.class) - .isThrownBy(() -> config.getConfigOptions(override).getPetersburgBlockNumber()) + .isThrownBy( + () -> config.withOverrides(override).getConfigOptions().getPetersburgBlockNumber()) .withMessage( "Genesis files cannot specify both petersburgBlock and constantinopleFixBlock."); } diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/CliqueGetSigners.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/CliqueGetSigners.java index 813c296098c8..057fb30ee5e6 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/CliqueGetSigners.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/CliqueGetSigners.java @@ -20,6 +20,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -71,7 +72,7 @@ private Optional determineBlockHeader(final JsonRpcRequestContext r final Optional blockParameter; try { blockParameter = request.getOptionalParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/CliqueGetSignersAtHash.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/CliqueGetSignersAtHash.java index c683b9d48556..908ff9f4123e 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/CliqueGetSignersAtHash.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/CliqueGetSignersAtHash.java @@ -20,6 +20,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -71,7 +72,7 @@ private Optional determineBlockHeader(final JsonRpcRequestContext r final Hash hash; try { hash = request.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/Discard.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/Discard.java index 467164e8c021..da3214b1ef06 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/Discard.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/Discard.java @@ -22,6 +22,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -51,7 +52,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Address address; try { address = requestContext.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/Propose.java b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/Propose.java index 6e198a84fe28..26ab19c9882a 100644 --- a/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/Propose.java +++ b/consensus/clique/src/main/java/org/hyperledger/besu/consensus/clique/jsonrpc/methods/Propose.java @@ -23,6 +23,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -53,14 +54,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Address address; try { address = requestContext.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } final Boolean auth; try { auth = requestContext.getRequiredParameter(1, Boolean.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid auth parameter (index 1)", RpcErrorType.INVALID_PROPOSAL_PARAMS, e); } diff --git a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/jsonrpc/AbstractGetSignerMetricsMethod.java b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/jsonrpc/AbstractGetSignerMetricsMethod.java index 7ef368fb762e..e3785976af93 100644 --- a/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/jsonrpc/AbstractGetSignerMetricsMethod.java +++ b/consensus/common/src/main/java/org/hyperledger/besu/consensus/common/jsonrpc/AbstractGetSignerMetricsMethod.java @@ -20,6 +20,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -70,14 +71,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Optional startBlockParameter; try { startBlockParameter = requestContext.getOptionalParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid start block parameter (index 0)", RpcErrorType.INVALID_BLOCK_NUMBER_PARAMS, e); } final Optional endBlockParameter; try { endBlockParameter = requestContext.getOptionalParameter(1, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid end block parameter (index 1)", RpcErrorType.INVALID_BLOCK_NUMBER_PARAMS, e); } diff --git a/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftDiscardValidatorVote.java b/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftDiscardValidatorVote.java index 7e6c00108885..89534689379c 100644 --- a/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftDiscardValidatorVote.java +++ b/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftDiscardValidatorVote.java @@ -22,6 +22,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -55,7 +56,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Address validatorAddress; try { validatorAddress = requestContext.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid validator address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftGetValidatorsByBlockHash.java b/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftGetValidatorsByBlockHash.java index 3c3346cd4362..dfefe22c53f9 100644 --- a/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftGetValidatorsByBlockHash.java +++ b/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftGetValidatorsByBlockHash.java @@ -20,6 +20,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -66,7 +67,7 @@ private Object blockResult(final JsonRpcRequestContext request) { final Hash hash; try { hash = request.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } diff --git a/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftGetValidatorsByBlockNumber.java b/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftGetValidatorsByBlockNumber.java index 7992f0918c46..a878ebc66e78 100644 --- a/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftGetValidatorsByBlockNumber.java +++ b/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftGetValidatorsByBlockNumber.java @@ -21,6 +21,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.AbstractBlockParameterMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; 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; @@ -54,7 +55,7 @@ public IbftGetValidatorsByBlockNumber( protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVote.java b/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVote.java index 9364422c5783..f010633e63f4 100644 --- a/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVote.java +++ b/consensus/ibft/src/main/java/org/hyperledger/besu/consensus/ibft/jsonrpc/methods/IbftProposeValidatorVote.java @@ -23,6 +23,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -56,14 +57,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Address validatorAddress; try { validatorAddress = requestContext.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } final Boolean add; try { add = requestContext.getRequiredParameter(1, Boolean.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid vote type parameter (index 1)", RpcErrorType.INVALID_VOTE_TYPE_PARAMS, e); } diff --git a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftDiscardValidatorVote.java b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftDiscardValidatorVote.java index 98856caaa61c..66e9cf60143e 100644 --- a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftDiscardValidatorVote.java +++ b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftDiscardValidatorVote.java @@ -20,6 +20,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -53,7 +54,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Address validatorAddress; try { validatorAddress = requestContext.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid validator address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, diff --git a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftGetValidatorsByBlockHash.java b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftGetValidatorsByBlockHash.java index e991f7f355df..75000bde5d36 100644 --- a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftGetValidatorsByBlockHash.java +++ b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftGetValidatorsByBlockHash.java @@ -21,6 +21,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -67,7 +68,7 @@ private Object blockResult(final JsonRpcRequestContext request) { final Hash hash; try { hash = request.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } diff --git a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftGetValidatorsByBlockNumber.java b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftGetValidatorsByBlockNumber.java index 7a64a7ab22a6..b33490f0c22a 100644 --- a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftGetValidatorsByBlockNumber.java +++ b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftGetValidatorsByBlockNumber.java @@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.AbstractBlockParameterMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; 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; @@ -54,7 +55,7 @@ public QbftGetValidatorsByBlockNumber( protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftProposeValidatorVote.java b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftProposeValidatorVote.java index aa3a8b267e5b..e6ad3ff6a890 100644 --- a/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftProposeValidatorVote.java +++ b/consensus/qbft/src/main/java/org/hyperledger/besu/consensus/qbft/jsonrpc/methods/QbftProposeValidatorVote.java @@ -21,6 +21,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -54,7 +55,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Address validatorAddress; try { validatorAddress = requestContext.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid validator address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, @@ -63,7 +64,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Boolean add; try { add = requestContext.getRequiredParameter(1, Boolean.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid vote type parameter (index 1)", RpcErrorType.INVALID_VOTE_TYPE_PARAMS, e); } diff --git a/docs/tracing/README.md b/docs/tracing/README.md index 0acac729d4f3..77deadd16aa4 100644 --- a/docs/tracing/README.md +++ b/docs/tracing/README.md @@ -21,4 +21,4 @@ Open the Zipkin UI by browsing to http://localhost:9411/ You will be able to see the detail of your traces. References: -* [OpenTelemetry Environment Variable Specification](https://github.com/open-telemetry/opentelemetry-specification/blob/master/specification/sdk-environment-variables.md) +* [OpenTelemetry Environment Variable Specification](https://github.com/open-telemetry/opentelemetry-specification/blob/main/specification/configuration/sdk-environment-variables.md) diff --git a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetBlockByNumberIntegrationTest.java b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetBlockByNumberIntegrationTest.java index 966cda12008c..3798cbe507c4 100644 --- a/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetBlockByNumberIntegrationTest.java +++ b/ethereum/api/src/integration-test/java/org/hyperledger/besu/ethereum/api/jsonrpc/methods/fork/frontier/EthGetBlockByNumberIntegrationTest.java @@ -437,7 +437,7 @@ public void missingHashesOrTransactionParameter() { assertThat(thrown) .isInstanceOf(InvalidJsonRpcParameters.class) - .hasMessage("Invalid is transaction complete parameter (index 1)"); + .hasMessage("Invalid return complete transaction parameter (index 1)"); } /** diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/execution/TracedJsonRpcProcessor.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/execution/TracedJsonRpcProcessor.java index f1a799cf6386..ec0e6aef64af 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/execution/TracedJsonRpcProcessor.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/execution/TracedJsonRpcProcessor.java @@ -84,7 +84,7 @@ public JsonRpcResponse process( case INVALID_GAS_PRICE_PARAMS: case INVALID_HASH_RATE_PARAMS: case INVALID_ID_PARAMS: - case INVALID_IS_TRANSACTION_COMPLETE_PARAMS: + case INVALID_RETURN_COMPLETE_TRANSACTION_PARAMS: case INVALID_LOG_FILTER_PARAMS: case INVALID_LOG_LEVEL_PARAMS: case INVALID_MAX_RESULTS_PARAMS: diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/DebugReplayBlock.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/DebugReplayBlock.java index 6dbf9f586fe1..ab53e415dd54 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/DebugReplayBlock.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/DebugReplayBlock.java @@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.AbstractBlockParameterMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -60,7 +61,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/JsonRpcRequest.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/JsonRpcRequest.java index 06b495624eff..a7c1e15e01da 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/JsonRpcRequest.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/JsonRpcRequest.java @@ -16,6 +16,7 @@ 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.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import java.util.Arrays; @@ -132,15 +133,18 @@ public int hashCode() { return Objects.hash(id, method, Arrays.hashCode(params), version, isNotification); } - public T getRequiredParameter(final int index, final Class paramClass) { + public T getRequiredParameter(final int index, final Class paramClass) + throws JsonRpcParameterException { return parameterAccessor.required(params, index, paramClass); } - public Optional getOptionalParameter(final int index, final Class paramClass) { + public Optional getOptionalParameter(final int index, final Class paramClass) + throws JsonRpcParameterException { return parameterAccessor.optional(params, index, paramClass); } - public Optional> getOptionalList(final int index, final Class paramClass) { + public Optional> getOptionalList(final int index, final Class paramClass) + throws JsonRpcParameterException { return parameterAccessor.optionalList(params, index, paramClass); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/JsonRpcRequestContext.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/JsonRpcRequestContext.java index b489259eb827..cc96384005b1 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/JsonRpcRequestContext.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/JsonRpcRequestContext.java @@ -14,6 +14,8 @@ */ package org.hyperledger.besu.ethereum.api.jsonrpc.internal; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; + import java.util.List; import java.util.Objects; import java.util.Optional; @@ -61,15 +63,18 @@ public Optional getUser() { return user; } - public T getRequiredParameter(final int index, final Class paramClass) { + public T getRequiredParameter(final int index, final Class paramClass) + throws JsonRpcParameterException { return jsonRpcRequest.getRequiredParameter(index, paramClass); } - public Optional getOptionalParameter(final int index, final Class paramClass) { + public Optional getOptionalParameter(final int index, final Class paramClass) + throws JsonRpcParameterException { return jsonRpcRequest.getOptionalParameter(index, paramClass); } - public Optional> getOptionalList(final int index, final Class listOf) { + public Optional> getOptionalList(final int index, final Class listOf) + throws JsonRpcParameterException { return jsonRpcRequest.getOptionalList(index, listOf); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractTraceByBlock.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractTraceByBlock.java index a5965211757d..36991796b51e 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractTraceByBlock.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AbstractTraceByBlock.java @@ -19,6 +19,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TraceTypeParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -67,7 +68,7 @@ protected BlockParameter blockParameter(final JsonRpcRequestContext request) { final Optional maybeBlockParameter; try { maybeBlockParameter = request.getOptionalParameter(2, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 2)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminChangeLogLevel.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminChangeLogLevel.java index 3cfd524c1487..6081f8f3404d 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminChangeLogLevel.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminChangeLogLevel.java @@ -17,6 +17,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -47,7 +48,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String logLevel; try { logLevel = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid log level parameter (index 0)", RpcErrorType.INVALID_LOG_LEVEL_PARAMS, e); } @@ -58,7 +59,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Optional optionalLogFilters; try { optionalLogFilters = requestContext.getOptionalParameter(1, String[].class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid log filter parameters (index 1)", RpcErrorType.INVALID_LOG_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminGenerateLogBloomCache.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminGenerateLogBloomCache.java index 437f7f5821ac..cad60660c33e 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminGenerateLogBloomCache.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminGenerateLogBloomCache.java @@ -18,6 +18,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -43,7 +44,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Optional startBlockParam; try { startBlockParam = requestContext.getOptionalParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid start block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -60,7 +61,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Optional stopBlockParam; try { stopBlockParam = requestContext.getOptionalParameter(1, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid stop block parameter (index 1)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRemoveCache.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRemoveCache.java index 94430c526f83..c7b67b282704 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRemoveCache.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRemoveCache.java @@ -18,6 +18,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -46,14 +47,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Optional startBlockParameter; try { startBlockParameter = requestContext.getOptionalParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid start block parameter (index 0)", RpcErrorType.INVALID_BLOCK_NUMBER_PARAMS, e); } final Optional stopBlockParameter; try { stopBlockParameter = requestContext.getOptionalParameter(1, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid stop block parameter (index 1)", RpcErrorType.INVALID_BLOCK_NUMBER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRepairCache.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRepairCache.java index 7336faff0e68..650a9f74eb43 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRepairCache.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminLogsRepairCache.java @@ -17,6 +17,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -43,7 +44,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Optional blockNumber; try { blockNumber = requestContext.getOptionalParameter(0, Long.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block number parameter (index 0)", RpcErrorType.INVALID_BLOCK_NUMBER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminModifyPeer.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminModifyPeer.java index f1c134ed915a..5b70668c3223 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminModifyPeer.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminModifyPeer.java @@ -15,6 +15,7 @@ package org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -65,7 +66,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { } catch (final P2PDisabledException e) { return new JsonRpcErrorResponse( requestContext.getRequest().getId(), RpcErrorType.P2P_DISABLED); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { return new JsonRpcErrorResponse( requestContext.getRequest().getId(), RpcErrorType.INVALID_ENODE_PARAMS); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugAccountAt.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugAccountAt.java index 602f3de3e0ca..318d8a0b8de5 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugAccountAt.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugAccountAt.java @@ -20,6 +20,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTrace; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer; @@ -69,7 +70,7 @@ protected BlockParameterOrBlockHash blockParameterOrBlockHash( final JsonRpcRequestContext requestContext) { try { return requestContext.getRequiredParameter(0, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -81,7 +82,7 @@ protected Object resultByBlockHash( final Integer txIndex; try { txIndex = requestContext.getRequiredParameter(1, Integer.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction index parameter (index 1)", RpcErrorType.INVALID_TRANSACTION_INDEX_PARAMS, @@ -90,7 +91,7 @@ protected Object resultByBlockHash( final Address address; try { address = requestContext.getRequiredParameter(2, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 2)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugAccountRange.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugAccountRange.java index fc787031dacd..852972f4d829 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugAccountRange.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugAccountRange.java @@ -19,6 +19,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -62,7 +63,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { try { blockParameterOrBlockHash = requestContext.getRequiredParameter(0, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter or block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, @@ -71,14 +72,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String addressHash; try { addressHash = requestContext.getRequiredParameter(2, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address hash parameter (index 2)", RpcErrorType.INVALID_ADDRESS_HASH_PARAMS, e); } final int maxResults; try { maxResults = requestContext.getRequiredParameter(3, Integer.TYPE); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid max results parameter (index 3)", RpcErrorType.INVALID_MAX_RESULTS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugBatchSendRawTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugBatchSendRawTransaction.java index 83553dc8745f..d78f9fb6be9e 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugBatchSendRawTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugBatchSendRawTransaction.java @@ -16,8 +16,11 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.util.DomainObjectDecodeUtils; import org.hyperledger.besu.ethereum.eth.transactions.TransactionPool; import org.hyperledger.besu.ethereum.mainnet.ValidationResult; @@ -56,9 +59,15 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final List executionStatuses = new ArrayList<>(); IntStream.range(0, requestContext.getRequest().getParamLength()) .forEach( - i -> + i -> { + try { executionStatuses.add( - process(i, requestContext.getRequiredParameter(i, String.class)))); + process(i, requestContext.getRequiredParameter(i, String.class))); + } catch (JsonRpcParameterException e) { + throw new InvalidJsonRpcParameters( + "Invalid parameter (index " + i + ")", RpcErrorType.INVALID_PARAMS, e); + } + }); return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), executionStatuses); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawBlock.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawBlock.java index 28d886bd81e5..c9097583e368 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawBlock.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawBlock.java @@ -18,6 +18,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; 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.query.BlockchainQueries; @@ -40,7 +41,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawHeader.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawHeader.java index e2f2c89e1aac..8e4f9ce6ead8 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawHeader.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawHeader.java @@ -18,6 +18,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; 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.query.BlockchainQueries; @@ -40,7 +41,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawReceipts.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawReceipts.java index cddba5086e8b..1c634c3c7309 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawReceipts.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawReceipts.java @@ -19,6 +19,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; import org.hyperledger.besu.ethereum.core.TransactionReceipt; @@ -44,7 +45,7 @@ protected BlockParameterOrBlockHash blockParameterOrBlockHash( final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawTransaction.java index d6ede25b27ef..2b1e756d22a4 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugGetRawTransaction.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -43,7 +44,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash txHash; try { txHash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugMetrics.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugMetrics.java index 89e6e4a2ae7c..b5c74245ce44 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugMetrics.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugMetrics.java @@ -71,7 +71,26 @@ private void addLabelledObservation( @SuppressWarnings("unchecked") private Map getNextMapLevel( final Map current, final String name) { + // Use compute to either return the existing map or create a new one return (Map) - current.computeIfAbsent(name, key -> new HashMap()); + current.compute( + name, + (k, v) -> { + if (v instanceof Map) { + // If the value is already a Map, return it as is + return v; + } else { + // If the value is not a Map, create a new Map + Map newMap = new HashMap<>(); + if (v != null) { + // If v is not null and not a Map, we store it as a leaf value + // If the original value was not null, store it under the "value" key + // This handles cases where a metric value (e.g., Double) was previously stored + // directly + newMap.put("value", v); + } + return newMap; + } + }); } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugSetHead.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugSetHead.java index a3b423675fdb..7958f8e7595f 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugSetHead.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugSetHead.java @@ -22,6 +22,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -47,7 +48,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStandardTraceBadBlockToFile.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStandardTraceBadBlockToFile.java index 2d0c4cac4e29..b49c94fd6a05 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStandardTraceBadBlockToFile.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStandardTraceBadBlockToFile.java @@ -19,6 +19,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TransactionTraceParams; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; @@ -56,14 +57,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash blockHash; try { blockHash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } final Optional transactionTraceParams; try { transactionTraceParams = requestContext.getOptionalParameter(1, TransactionTraceParams.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction trace parameters (index 1)", RpcErrorType.INVALID_TRANSACTION_TRACE_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStandardTraceBlockToFile.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStandardTraceBlockToFile.java index 5fba2911bdde..b3bb32370ee4 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStandardTraceBlockToFile.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStandardTraceBlockToFile.java @@ -20,6 +20,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TransactionTraceParams; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTracer; @@ -63,14 +64,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash blockHash; try { blockHash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } final Optional transactionTraceParams; try { transactionTraceParams = requestContext.getOptionalParameter(1, TransactionTraceParams.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction trace parameters (index 1)", RpcErrorType.INVALID_TRANSACTION_TRACE_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStorageRangeAt.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStorageRangeAt.java index 5aabff4b574c..1fde6610ef80 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStorageRangeAt.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugStorageRangeAt.java @@ -20,6 +20,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockReplay; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer.TraceableState; @@ -73,14 +74,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { try { blockParameterOrBlockHash = requestContext.getRequiredParameter(0, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } final int transactionIndex; try { transactionIndex = requestContext.getRequiredParameter(1, Integer.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction index parameter (index 1)", RpcErrorType.INVALID_TRANSACTION_INDEX_PARAMS, @@ -89,21 +90,21 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Address accountAddress; try { accountAddress = requestContext.getRequiredParameter(2, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid account address parameter (index 2)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } final Hash startKey; try { startKey = Hash.fromHexStringLenient(requestContext.getRequiredParameter(3, String.class)); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid data start hash parameter (index 3)", RpcErrorType.INVALID_DATA_HASH_PARAMS, e); } final int limit; try { limit = requestContext.getRequiredParameter(4, Integer.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid limit parameter (index 4)", RpcErrorType.INVALID_TRANSACTION_LIMIT_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlock.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlock.java index 2d668c7f2290..edfb816bb9d7 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlock.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlock.java @@ -17,6 +17,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TransactionTraceParams; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTrace; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTracer; @@ -65,15 +66,15 @@ public String getName() { @Override public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { - final String input = requestContext.getRequiredParameter(0, String.class); final Block block; try { + final String input = requestContext.getRequiredParameter(0, String.class); block = Block.readFrom(RLP.input(Bytes.fromHexString(input)), this.blockHeaderFunctions); } catch (final RLPException e) { LOG.debug("Failed to parse block RLP (index 0)", e); return new JsonRpcErrorResponse( requestContext.getRequest().getId(), RpcErrorType.INVALID_BLOCK_PARAMS); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block params (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -84,7 +85,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { .getOptionalParameter(1, TransactionTraceParams.class) .map(TransactionTraceParams::traceOptions) .orElse(TraceOptions.DEFAULT); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction trace parameter (index 1)", RpcErrorType.INVALID_TRANSACTION_TRACE_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockByHash.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockByHash.java index da795439cf37..d98e8abd8dfb 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockByHash.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockByHash.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TransactionTraceParams; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTrace; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTracer; @@ -55,7 +56,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash blockHash; try { blockHash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } @@ -66,9 +67,9 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { .getOptionalParameter(1, TransactionTraceParams.class) .map(TransactionTraceParams::traceOptions) .orElse(TraceOptions.DEFAULT); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( - "Invalid transaction trace parameters (index 1)", + "Invalid transaction trace parameter (index 1)", RpcErrorType.INVALID_TRANSACTION_TRACE_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockByNumber.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockByNumber.java index eb90edabb956..99c96c99be91 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockByNumber.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceBlockByNumber.java @@ -19,6 +19,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TransactionTraceParams; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTrace; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTracer; @@ -51,7 +52,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -68,7 +69,7 @@ protected Object resultByBlockNumber( .getOptionalParameter(1, TransactionTraceParams.class) .map(TransactionTraceParams::traceOptions) .orElse(TraceOptions.DEFAULT); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction trace parameter (index 1)", RpcErrorType.INVALID_TRANSACTION_TRACE_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceCall.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceCall.java index ad46d981ac83..e808e79ddc30 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceCall.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceCall.java @@ -20,6 +20,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TransactionTraceParams; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError; @@ -60,9 +61,9 @@ protected TraceOptions getTraceOptions(final JsonRpcRequestContext requestContex .getOptionalParameter(2, TransactionTraceParams.class) .map(TransactionTraceParams::traceOptions) .orElse(TraceOptions.DEFAULT); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( - "Invalid transaction trace parameters (index 2)", + "Invalid transaction trace parameter (index 2)", RpcErrorType.INVALID_TRANSACTION_TRACE_PARAMS, e); } @@ -73,7 +74,7 @@ protected BlockParameter blockParameter(final JsonRpcRequestContext request) { final Optional maybeBlockParameter; try { maybeBlockParameter = request.getOptionalParameter(1, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 1)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceTransaction.java index 8ec14dc4ad5c..1e85e6530a4a 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugTraceTransaction.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TransactionTraceParams; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTracer; @@ -53,7 +54,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash hash; try { hash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, @@ -69,7 +70,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { .getOptionalParameter(1, TransactionTraceParams.class) .map(TransactionTraceParams::traceOptions) .orElse(TraceOptions.DEFAULT); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction trace parameter (index 1)", RpcErrorType.INVALID_TRANSACTION_TRACE_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCall.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCall.java index a08b17dfc638..0e0318f9c2bf 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCall.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthCall.java @@ -25,6 +25,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameterOrBlockHash; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonCallParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -60,7 +61,7 @@ protected BlockParameterOrBlockHash blockParameterOrBlockHash( final JsonRpcRequestContext request) { try { return request.getRequiredParameter(1, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameters (index 1)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthFeeHistory.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthFeeHistory.java index 01a080227902..b95746dad981 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthFeeHistory.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthFeeHistory.java @@ -24,6 +24,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UnsignedIntParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -91,7 +92,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext request) { final int blockCount; try { blockCount = request.getRequiredParameter(0, UnsignedIntParameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block count parameter (index 0)", RpcErrorType.INVALID_BLOCK_COUNT_PARAMS, e); } @@ -101,7 +102,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext request) { final BlockParameter highestBlock; try { highestBlock = request.getRequiredParameter(1, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid highest block parameter (index 1)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -109,7 +110,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext request) { final Optional> maybeRewardPercentiles; try { maybeRewardPercentiles = request.getOptionalParameter(2, Double[].class).map(Arrays::asList); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid reward percentiles parameter (index 2)", RpcErrorType.INVALID_REWARD_PERCENTILES_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBalance.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBalance.java index e863626c967d..cb1d879a05f5 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBalance.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBalance.java @@ -20,6 +20,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; 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; @@ -45,7 +46,7 @@ protected BlockParameterOrBlockHash blockParameterOrBlockHash( final JsonRpcRequestContext request) { try { return request.getRequiredParameter(1, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameter (index 1)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -56,7 +57,7 @@ protected String resultByBlockHash(final JsonRpcRequestContext request, final Ha final Address address; try { address = request.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByHash.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByHash.java index 09b1c2f9523e..f5b633253adc 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByHash.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByHash.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -64,7 +65,7 @@ private BlockResult blockResult(final JsonRpcRequestContext request) { final Hash hash; try { hash = request.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } @@ -95,10 +96,10 @@ private BlockResult transactionHash(final Hash hash) { private boolean isCompleteTransactions(final JsonRpcRequestContext requestContext) { try { return requestContext.getRequiredParameter(1, Boolean.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( - "Invalid is complete transaction parameter (index 1)", - RpcErrorType.INVALID_IS_TRANSACTION_COMPLETE_PARAMS, + "Invalid return complete transaction parameter (index 1)", + RpcErrorType.INVALID_RETURN_COMPLETE_TRANSACTION_PARAMS, e); } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByNumber.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByNumber.java index 5e0bc9c7ab4d..0a26a24ee386 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByNumber.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByNumber.java @@ -19,6 +19,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.BlockResult; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.BlockResultFactory; @@ -66,7 +67,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -126,10 +127,10 @@ private BlockResult transactionHash(final long blockNumber) { private boolean isCompleteTransactions(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(1, Boolean.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( - "Invalid is transaction complete parameter (index 1)", - RpcErrorType.INVALID_IS_TRANSACTION_COMPLETE_PARAMS, + "Invalid return complete transaction parameter (index 1)", + RpcErrorType.INVALID_RETURN_COMPLETE_TRANSACTION_PARAMS, e); } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockReceipts.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockReceipts.java index d9592db8c115..a113e4ee8e80 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockReceipts.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockReceipts.java @@ -19,6 +19,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.BlockReceiptsResult; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.TransactionReceiptResult; @@ -57,7 +58,7 @@ protected BlockParameterOrBlockHash blockParameterOrBlockHash( final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameters (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockTransactionCountByHash.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockTransactionCountByHash.java index e1fbd790868e..fc7c3cc70c2d 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockTransactionCountByHash.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockTransactionCountByHash.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -42,7 +43,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash hash; try { hash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block header hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockTransactionCountByNumber.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockTransactionCountByNumber.java index 2a068a617406..95bd7cc5070d 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockTransactionCountByNumber.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockTransactionCountByNumber.java @@ -18,6 +18,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; 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; @@ -37,7 +38,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameters (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetCode.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetCode.java index 8a9881a0125e..0c9194b0b34b 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetCode.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetCode.java @@ -20,6 +20,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; @@ -47,7 +48,7 @@ protected BlockParameterOrBlockHash blockParameterOrBlockHash( final JsonRpcRequestContext request) { try { return request.getRequiredParameter(1, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameter (index 1)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -58,7 +59,7 @@ protected String resultByBlockHash(final JsonRpcRequestContext request, final Ha final Address address; try { address = request.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetFilterChanges.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetFilterChanges.java index 0773651b6151..b3fa7565d63e 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetFilterChanges.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetFilterChanges.java @@ -19,6 +19,7 @@ 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.filter.FilterManager; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -47,7 +48,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String filterId; try { filterId = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter ID parameter (index 0)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetFilterLogs.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetFilterLogs.java index b66b7963e1cd..0fd32455b249 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetFilterLogs.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetFilterLogs.java @@ -18,6 +18,7 @@ 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.filter.FilterManager; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -45,7 +46,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String filterId; try { filterId = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter ID parameter (index 0)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetLogs.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetLogs.java index c9645d53e0a7..225870ba3a48 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetLogs.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetLogs.java @@ -18,6 +18,7 @@ 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.parameters.FilterParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -55,7 +56,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final FilterParameter filter; try { filter = requestContext.getRequiredParameter(0, FilterParameter.class); - } catch (Exception e) { + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter parameter (index 0)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetMinerDataByBlockHash.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetMinerDataByBlockHash.java index 8e3d55f1eab2..8b54364a9994 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetMinerDataByBlockHash.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetMinerDataByBlockHash.java @@ -19,6 +19,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -65,7 +66,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash hash; try { hash = requestContext.getRequest().getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetMinerDataByBlockNumber.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetMinerDataByBlockNumber.java index c2df71268648..e0fe24606264 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetMinerDataByBlockNumber.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetMinerDataByBlockNumber.java @@ -19,6 +19,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.MinerDataResult; import org.hyperledger.besu.ethereum.api.query.BlockWithMetadata; @@ -44,7 +45,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetProof.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetProof.java index 7c2f67b724f7..d1920b5c1a2e 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetProof.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetProof.java @@ -20,6 +20,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -51,7 +52,7 @@ protected BlockParameterOrBlockHash blockParameterOrBlockHash( final JsonRpcRequestContext request) { try { return request.getRequiredParameter(2, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameter (index 2)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -64,7 +65,7 @@ protected Object resultByBlockHash( final Address address; try { address = requestContext.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } @@ -110,7 +111,7 @@ private List getStorageKeys(final JsonRpcRequestContext request) { return Arrays.stream(request.getRequiredParameter(1, String[].class)) .map(UInt256::fromHexString) .collect(Collectors.toList()); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid storage keys parameters (index 1)", RpcErrorType.INVALID_STORAGE_KEYS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetStorageAt.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetStorageAt.java index 34ed62b63294..a171fc16d1d7 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetStorageAt.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetStorageAt.java @@ -20,6 +20,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UInt256Parameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; @@ -41,7 +42,7 @@ protected BlockParameterOrBlockHash blockParameterOrBlockHash( final JsonRpcRequestContext request) { try { return request.getRequiredParameter(2, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameter (index 2)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -52,14 +53,14 @@ protected String resultByBlockHash(final JsonRpcRequestContext request, final Ha final Address address; try { address = request.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } final UInt256 position; try { position = request.getRequiredParameter(1, UInt256Parameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid position parameter (index 1)", RpcErrorType.INVALID_POSITION_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByBlockHashAndIndex.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByBlockHashAndIndex.java index 9c7cf5e7a85e..917c09a32650 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByBlockHashAndIndex.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByBlockHashAndIndex.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UnsignedIntParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -47,7 +48,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash hash; try { hash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, @@ -56,7 +57,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final int index; try { index = requestContext.getRequiredParameter(1, UnsignedIntParameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction id parameter (index 1)", RpcErrorType.INVALID_TRANSACTION_ID_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByBlockNumberAndIndex.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByBlockNumberAndIndex.java index a5383f6680d1..338a8783688a 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByBlockNumberAndIndex.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByBlockNumberAndIndex.java @@ -18,6 +18,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UnsignedIntParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.TransactionCompleteResult; @@ -41,7 +42,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -53,7 +54,7 @@ protected Object resultByBlockNumber( final int index; try { index = request.getRequiredParameter(1, UnsignedIntParameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction index parameter (index 1)", RpcErrorType.INVALID_TRANSACTION_INDEX_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByHash.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByHash.java index 90e7a6a1edc8..5d8b0085226d 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByHash.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionByHash.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -54,7 +55,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash hash; try { hash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionCount.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionCount.java index a9916099eac2..4e26f8ee9890 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionCount.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionCount.java @@ -20,6 +20,7 @@ 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.parameters.BlockParameterOrBlockHash; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; 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; @@ -54,7 +55,7 @@ protected BlockParameterOrBlockHash blockParameterOrBlockHash( final JsonRpcRequestContext request) { try { return request.getRequiredParameter(1, BlockParameterOrBlockHash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block or block hash parameter (index 1)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -65,7 +66,7 @@ protected Object pendingResult(final JsonRpcRequestContext request) { final Address address; try { address = request.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } @@ -88,7 +89,7 @@ protected String resultByBlockHash(final JsonRpcRequestContext request, final Ha final Address address; try { address = request.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionReceipt.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionReceipt.java index a437cd86dc2b..44e4cfe0d6c5 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionReceipt.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetTransactionReceipt.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -51,7 +52,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash hash; try { hash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockHashAndIndex.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockHashAndIndex.java index 9269bf965c01..f76b461ceffc 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockHashAndIndex.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockHashAndIndex.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UnsignedIntParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -49,14 +50,14 @@ private BlockResult blockResult(final JsonRpcRequestContext requestContext) { final Hash hash; try { hash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } final int index; try { index = requestContext.getRequiredParameter(1, UnsignedIntParameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block index parameter (index 1)", RpcErrorType.INVALID_BLOCK_INDEX_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockNumberAndIndex.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockNumberAndIndex.java index a6c5e6d89df2..f7c9ecb0dd9a 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockNumberAndIndex.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleByBlockNumberAndIndex.java @@ -18,6 +18,7 @@ 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.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UnsignedIntParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.BlockResult; @@ -39,7 +40,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -51,7 +52,7 @@ protected BlockResult resultByBlockNumber( final int index; try { index = request.getRequiredParameter(1, UnsignedIntParameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block index (index 1)", RpcErrorType.INVALID_BLOCK_INDEX_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleCountByBlockHash.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleCountByBlockHash.java index 9a5a3b225ba4..02cd3c424252 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleCountByBlockHash.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleCountByBlockHash.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -42,7 +43,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash hash; try { hash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameter (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleCountByBlockNumber.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleCountByBlockNumber.java index ddd130542c6b..8d935942adda 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleCountByBlockNumber.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetUncleCountByBlockNumber.java @@ -16,7 +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.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; +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; @@ -33,7 +36,12 @@ public String getName() { @Override protected BlockParameter blockParameter(final JsonRpcRequestContext request) { - return request.getRequiredParameter(0, BlockParameter.class); + try { + return request.getRequiredParameter(0, BlockParameter.class); + } catch (JsonRpcParameterException e) { + throw new InvalidJsonRpcParameters( + "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); + } } @Override diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthNewFilter.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthNewFilter.java index 7578b43a2ed0..d6edccd2e7a6 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthNewFilter.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthNewFilter.java @@ -19,6 +19,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.filter.FilterManager; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.FilterParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -42,7 +43,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final FilterParameter filter; try { filter = requestContext.getRequiredParameter(0, FilterParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter paramters (index 0)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSendRawTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSendRawTransaction.java index 272014d3bc44..10582e7a1ce6 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSendRawTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSendRawTransaction.java @@ -21,6 +21,7 @@ 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.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -72,7 +73,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String rawTransaction; try { rawTransaction = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction parameters (index 0)", RpcErrorType.INVALID_TRANSACTION_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSubmitHashRate.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSubmitHashRate.java index c0763e77f6de..488f89b3a58e 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSubmitHashRate.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSubmitHashRate.java @@ -17,6 +17,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -42,14 +43,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String hashRate; try { hashRate = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid hash rate parameter (index 0)", RpcErrorType.INVALID_HASH_RATE_PARAMS, e); } final String id; try { id = requestContext.getRequiredParameter(1, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid sealer ID parameter (index 1)", RpcErrorType.INVALID_SEALER_ID_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSubmitWork.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSubmitWork.java index 9474fec7bad7..9002b2a0ddff 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSubmitWork.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthSubmitWork.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -54,21 +55,21 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { try { nonce = Bytes.fromHexString(requestContext.getRequiredParameter(0, String.class)).getLong(0); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid nonce parameter (index 0)", RpcErrorType.INVALID_NONCE_PARAMS, e); } Hash mixHash; try { mixHash = requestContext.getRequiredParameter(2, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid mix hash parameter (index 2)", RpcErrorType.INVALID_MIX_HASH_PARAMS, e); } Bytes powHash; try { powHash = Bytes.fromHexString(requestContext.getRequiredParameter(1, String.class)); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid PoW hash parameter (index 1)", RpcErrorType.INVALID_POW_HASH_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthUninstallFilter.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthUninstallFilter.java index b51dc1f4fd34..8771343ecfc9 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthUninstallFilter.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthUninstallFilter.java @@ -18,6 +18,7 @@ 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.filter.FilterManager; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -40,7 +41,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String filterId; try { filterId = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter ID parameter (index 0)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/JsonCallParameterUtil.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/JsonCallParameterUtil.java index 7d7bd013bea5..df593f9fbc31 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/JsonCallParameterUtil.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/JsonCallParameterUtil.java @@ -17,6 +17,7 @@ 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.parameters.JsonCallParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; public class JsonCallParameterUtil { @@ -27,7 +28,7 @@ public static JsonCallParameter validateAndGetCallParams(final JsonRpcRequestCon final JsonCallParameter callParams; try { callParams = request.getRequiredParameter(0, JsonCallParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid call parameters (index 0)", RpcErrorType.INVALID_CALL_PARAMS); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/PluginsReloadConfiguration.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/PluginsReloadConfiguration.java index f895008e232c..3761b8114af1 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/PluginsReloadConfiguration.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/PluginsReloadConfiguration.java @@ -16,6 +16,7 @@ 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.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -55,7 +56,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { } reloadPluginConfig(namedPlugins.get(pluginName)); return new JsonRpcSuccessResponse(requestContext.getRequest().getId()); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { return new JsonRpcErrorResponse( requestContext.getRequest().getId(), RpcErrorType.INVAlID_PLUGIN_NAME_PARAMS); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceBlock.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceBlock.java index 5ec46e08cc43..adacf01e7641 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceBlock.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceBlock.java @@ -21,6 +21,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.FilterParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -72,7 +73,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceCall.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceCall.java index 9882257143ca..082283a8158a 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceCall.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceCall.java @@ -19,6 +19,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TraceTypeParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; @@ -60,7 +61,7 @@ private Set getTraceTypes( final JsonRpcRequestContext requestContext) { try { return requestContext.getRequiredParameter(1, TraceTypeParameter.class).getTraceTypes(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid trace type parameter (index 1)", RpcErrorType.INVALID_TRACE_TYPE_PARAMS, e); } 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 2cbeb8ee7f8d..10d4018bce26 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 @@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; 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.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TraceCallManyParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TraceTypeParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; @@ -67,7 +68,7 @@ protected BlockParameter blockParameter(final JsonRpcRequestContext request) { final Optional maybeBlockParameter; try { maybeBlockParameter = request.getOptionalParameter(1, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 1)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceFilter.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceFilter.java index a3d6b2561f7b..74bfec87c290 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceFilter.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceFilter.java @@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.FilterParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; @@ -90,7 +91,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final FilterParameter filterParameter; try { filterParameter = requestContext.getRequiredParameter(0, FilterParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter parameter (index 0)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceGet.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceGet.java index a1460c5aa244..e1c27aed798c 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceGet.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceGet.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -58,16 +59,16 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash transactionHash; try { transactionHash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( - "Invalid transaction has parameter (index 0)", + "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, e); } final List traceNumbersAsStrings; try { traceNumbersAsStrings = requestContext.getRequiredParameter(1, List.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid trace numbers parameters (index 1)", RpcErrorType.INVALID_TRACE_NUMBERS_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceRawTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceRawTransaction.java index a7205698752b..71c8247784c2 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceRawTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceRawTransaction.java @@ -19,6 +19,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TraceTypeParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; @@ -74,14 +75,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String rawTransaction; try { rawTransaction = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction parameters (index 0)", RpcErrorType.INVALID_TRANSACTION_PARAMS, e); } final TraceTypeParameter traceTypeParameter; try { traceTypeParameter = requestContext.getRequiredParameter(1, TraceTypeParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid trace type parameter (index 1)", RpcErrorType.INVALID_TRACE_TYPE_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceReplayBlockTransactions.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceReplayBlockTransactions.java index a8b3bbc46def..202d2ddbbbcf 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceReplayBlockTransactions.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceReplayBlockTransactions.java @@ -21,6 +21,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.TraceBlock.ChainUpdater; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.TraceTypeParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.Tracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.TransactionTrace; @@ -74,7 +75,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(0, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -86,7 +87,7 @@ protected ArrayNode resultByBlockNumber( final TraceTypeParameter traceTypeParameter; try { traceTypeParameter = request.getRequiredParameter(1, TraceTypeParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid trace type parameter (index 1)", RpcErrorType.INVALID_TRACE_TYPE_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceTransaction.java index b79b9620e8d0..be6942368117 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TraceTransaction.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.BlockTracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -50,7 +51,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash transactionHash; try { transactionHash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TxPoolBesuPendingTransactions.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TxPoolBesuPendingTransactions.java index 8dc38135c600..81c366926a6c 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TxPoolBesuPendingTransactions.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TxPoolBesuPendingTransactions.java @@ -17,6 +17,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.PendingTransactionsParams; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -58,7 +59,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { try { limit = requestContext.getOptionalParameter(0, Integer.class).orElse(pendingTransactions.size()); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction limit parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_LIMIT_PARAMS, @@ -71,7 +72,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { .getOptionalParameter(1, PendingTransactionsParams.class) .map(PendingTransactionsParams::filters) .orElse(Collections.emptyList()); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid pending transactions parameter (index 1)", RpcErrorType.INVALID_PENDING_TRANSACTIONS_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/Web3Sha3.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/Web3Sha3.java index b70ad760519d..e34a462800a5 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/Web3Sha3.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/Web3Sha3.java @@ -18,6 +18,7 @@ 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.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -45,7 +46,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String data; try { data = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid data parameter (index 0)", RpcErrorType.INVALID_DATA_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineForkchoiceUpdated.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineForkchoiceUpdated.java index 7df76973ac99..11ec3d04c59f 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineForkchoiceUpdated.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineForkchoiceUpdated.java @@ -31,6 +31,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.ExecutionEngineJsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.EngineForkchoiceUpdatedParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.EnginePayloadAttributesParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.WithdrawalParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -84,7 +85,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext requestContext) final EngineForkchoiceUpdatedParameter forkChoice; try { forkChoice = requestContext.getRequiredParameter(0, EngineForkchoiceUpdatedParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid engine forkchoice updated parameter (index 0)", RpcErrorType.INVALID_ENGINE_FORKCHOICE_UPDATED_PARAMS, @@ -94,7 +95,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext requestContext) try { maybePayloadAttributes = requestContext.getOptionalParameter(1, EnginePayloadAttributesParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid engine payload attributes parameter (index 1)", RpcErrorType.INVALID_ENGINE_FORKCHOICE_UPDATED_PAYLOAD_ATTRIBUTES, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineGetPayload.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineGetPayload.java index a6f94ac00e06..d95b532e77a3 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineGetPayload.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineGetPayload.java @@ -21,6 +21,7 @@ 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.methods.ExecutionEngineJsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -72,7 +73,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext request) { final PayloadIdentifier payloadId; try { payloadId = request.getRequiredParameter(0, PayloadIdentifier.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid payload ID parameter (index 0)", RpcErrorType.INVALID_PAYLOAD_ID_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineNewPayload.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineNewPayload.java index 02ccf5d23116..78b96796cbd5 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineNewPayload.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/AbstractEngineNewPayload.java @@ -39,6 +39,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.ConsolidationRequestParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.DepositRequestParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.EnginePayloadParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.WithdrawalParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.WithdrawalRequestParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; @@ -109,7 +110,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext requestContext) final EnginePayloadParameter blockParam; try { blockParam = requestContext.getRequiredParameter(0, EnginePayloadParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcRequestException( "Invalid engine payload parameter (index 0)", RpcErrorType.INVALID_ENGINE_NEW_PAYLOAD_PARAMS, @@ -119,7 +120,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext requestContext) final Optional> maybeVersionedHashParam; try { maybeVersionedHashParam = requestContext.getOptionalList(1, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcRequestException( "Invalid versioned hash parameters (index 1)", RpcErrorType.INVALID_VERSIONED_HASH_PARAMS, @@ -131,7 +132,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext requestContext) Optional maybeParentBeaconBlockRootParam; try { maybeParentBeaconBlockRootParam = requestContext.getOptionalParameter(2, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcRequestException( "Invalid parent beacon block root parameters (index 2)", RpcErrorType.INVALID_PARENT_BEACON_BLOCK_ROOT_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineExchangeCapabilities.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineExchangeCapabilities.java index 624d9bebddc1..2666888ed634 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineExchangeCapabilities.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineExchangeCapabilities.java @@ -22,6 +22,7 @@ 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.methods.ExecutionEngineJsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -61,8 +62,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext requestContext) () -> { try { return requestContext.getRequiredParameter(0, String[].class); - } catch ( - Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid remote capabilities parameters (index 0)", RpcErrorType.INVALID_REMOTE_CAPABILITIES_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineExchangeTransitionConfiguration.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineExchangeTransitionConfiguration.java index 67b865753368..924e8ac989c8 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineExchangeTransitionConfiguration.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineExchangeTransitionConfiguration.java @@ -23,6 +23,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.ExecutionEngineJsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.EngineExchangeTransitionConfigurationParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -72,7 +73,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext requestContext) remoteTransitionConfiguration = requestContext.getRequiredParameter( 0, EngineExchangeTransitionConfigurationParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid engine exchange transition configuration parameters (index 0)", RpcErrorType.INVALID_ENGINE_EXCHANGE_TRANSITION_CONFIGURATION_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineGetPayloadBodiesByHashV1.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineGetPayloadBodiesByHashV1.java index 0e6b62d320f6..facbd026d4e8 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineGetPayloadBodiesByHashV1.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineGetPayloadBodiesByHashV1.java @@ -20,6 +20,7 @@ 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.methods.ExecutionEngineJsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -64,7 +65,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext request) { final Hash[] blockHashes; try { blockHashes = request.getRequiredParameter(0, Hash[].class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block hash parameters (index 0)", RpcErrorType.INVALID_BLOCK_HASH_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineGetPayloadBodiesByRangeV1.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineGetPayloadBodiesByRangeV1.java index ec5d5bf6045f..2d21a7282ae8 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineGetPayloadBodiesByRangeV1.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EngineGetPayloadBodiesByRangeV1.java @@ -19,6 +19,7 @@ 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.methods.ExecutionEngineJsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UnsignedLongParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -61,7 +62,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext request) { final long startBlockNumber; try { startBlockNumber = request.getRequiredParameter(0, UnsignedLongParameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid start block number parameter (index 0)", RpcErrorType.INVALID_BLOCK_NUMBER_PARAMS, @@ -70,7 +71,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext request) { final long count; try { count = request.getRequiredParameter(1, UnsignedLongParameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block count params (index 1)", RpcErrorType.INVALID_BLOCK_COUNT_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EnginePreparePayloadDebug.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EnginePreparePayloadDebug.java index e55cfb1506e4..c4bca2180315 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EnginePreparePayloadDebug.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EnginePreparePayloadDebug.java @@ -26,6 +26,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.ExecutionEngineJsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.EnginePreparePayloadParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.WithdrawalParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -72,7 +73,7 @@ public JsonRpcResponse syncResponse(final JsonRpcRequestContext requestContext) Optional.empty(), Optional.empty(), Optional.empty())); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid engine prepare payload parameter (index 0)", RpcErrorType.INVALID_ENGINE_PREPARE_PAYLOAD_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerChangeTargetGasLimit.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerChangeTargetGasLimit.java index f1b949ad639e..cd1b033dc47d 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerChangeTargetGasLimit.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerChangeTargetGasLimit.java @@ -18,6 +18,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -49,7 +50,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { return new JsonRpcErrorResponse( requestContext.getRequest().getId(), RpcErrorType.TARGET_GAS_LIMIT_MODIFICATION_UNSUPPORTED); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid target gas limit parameter (index 0)", RpcErrorType.INVALID_TARGET_GAS_LIMIT_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetCoinbase.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetCoinbase.java index d6676a607401..f30db35e77e4 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetCoinbase.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetCoinbase.java @@ -19,6 +19,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -47,7 +48,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { } catch (final UnsupportedOperationException ex) { return new JsonRpcErrorResponse( requestContext.getRequest().getId(), RpcErrorType.INVALID_REQUEST); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetExtraData.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetExtraData.java index 5b9bc581dbe4..51395e24f772 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetExtraData.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetExtraData.java @@ -17,6 +17,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -60,12 +61,10 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { .addArgument(() -> new String(extraData.toArray(), StandardCharsets.UTF_8)) .log(); return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), true); - } catch (Exception invalidJsonRpcParameters) { // TODO:replace with "IllegalArgumentException | - // JsonRpcParameter.JsonRpcParameterException" + } catch (IllegalArgumentException | JsonRpcParameterException e) { return new JsonRpcErrorResponse( requestContext.getRequest().getId(), - new JsonRpcError( - RpcErrorType.INVALID_EXTRA_DATA_PARAMS, invalidJsonRpcParameters.getMessage())); + new JsonRpcError(RpcErrorType.INVALID_EXTRA_DATA_PARAMS, e.getMessage())); } } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinGasPrice.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinGasPrice.java index 59c18b80dbbc..733ed3a8f3cc 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinGasPrice.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinGasPrice.java @@ -19,6 +19,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -56,7 +57,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { requestContext.getRequest().getId(), new JsonRpcError( RpcErrorType.INVALID_MIN_GAS_PRICE_PARAMS, invalidJsonRpcParameters.getMessage())); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid min gas price parameter (index 0)", RpcErrorType.INVALID_MIN_GAS_PRICE_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java index 9c217b0c23c1..b1bf4338f774 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/miner/MinerSetMinPriorityFee.java @@ -18,6 +18,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -51,11 +52,10 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { LOG.debug( "min priority fee per gas changed to {}", minPriorityFeePerGas.toHumanReadableString()); return new JsonRpcSuccessResponse(requestContext.getRequest().getId(), true); - } catch (final IllegalArgumentException invalidJsonRpcParameters) { + } catch (final IllegalArgumentException | JsonRpcParameterException e) { return new JsonRpcErrorResponse( requestContext.getRequest().getId(), - new JsonRpcError( - RpcErrorType.INVALID_MIN_PRIORITY_FEE_PARAMS, invalidJsonRpcParameters.getMessage())); + new JsonRpcError(RpcErrorType.INVALID_MIN_PRIORITY_FEE_PARAMS, e.getMessage())); } } } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermAddAccountsToAllowlist.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermAddAccountsToAllowlist.java index f3407ba10d67..32459b3b4cb2 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermAddAccountsToAllowlist.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermAddAccountsToAllowlist.java @@ -18,6 +18,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -48,7 +49,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final List accountsList; try { accountsList = requestContext.getRequiredParameter(0, List.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid accounts list parameter (index 0)", RpcErrorType.INVALID_ACCOUNT_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermAddNodesToAllowlist.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermAddNodesToAllowlist.java index 2aec3b6f955f..5f8374a884e1 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermAddNodesToAllowlist.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermAddNodesToAllowlist.java @@ -18,6 +18,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.StringListParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -50,7 +51,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final StringListParameter enodeListParam; try { enodeListParam = requestContext.getRequiredParameter(0, StringListParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid enode list parameter (index 0)", RpcErrorType.INVALID_ENODE_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermRemoveAccountsFromAllowlist.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermRemoveAccountsFromAllowlist.java index a39acd5e9cda..ac7bffdf5780 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermRemoveAccountsFromAllowlist.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermRemoveAccountsFromAllowlist.java @@ -18,6 +18,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -48,7 +49,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final List accountsList; try { accountsList = requestContext.getRequiredParameter(0, List.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid accounts list parameter (index 0)", RpcErrorType.INVALID_ACCOUNT_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermRemoveNodesFromAllowlist.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermRemoveNodesFromAllowlist.java index 862b694f4f8f..16e3bc234ace 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermRemoveNodesFromAllowlist.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/permissioning/PermRemoveNodesFromAllowlist.java @@ -18,6 +18,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.StringListParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -50,7 +51,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final StringListParameter enodeListParam; try { enodeListParam = requestContext.getRequiredParameter(0, StringListParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid enode list parameter (index 0)", RpcErrorType.INVALID_ENODE_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/JsonRpcParameter.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/JsonRpcParameter.java index a8b5fb7dc8a5..22fb511ef4b0 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/JsonRpcParameter.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/JsonRpcParameter.java @@ -14,8 +14,6 @@ */ package org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters; -import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; - import java.util.List; import java.util.Optional; @@ -40,13 +38,12 @@ public class JsonRpcParameter { * @param The type of parameter. * @return Returns the parameter cast as T if available, otherwise throws exception. */ - // TODO: update to throw JsonRpcParameterException as a checked exception, forcing callers to - // handle it to supply appropriate context - public T required(final Object[] params, final int index, final Class paramClass) { + public T required(final Object[] params, final int index, final Class paramClass) + throws JsonRpcParameterException { return optional(params, index, paramClass) .orElseThrow( () -> - new InvalidJsonRpcParameters( + new JsonRpcParameterException( "Missing required json rpc parameter at index " + index)); } @@ -60,11 +57,8 @@ public T required(final Object[] params, final int index, final Class par * @param The type of parameter. * @return Returns the parameter cast as T if available. */ - // TODO: update to throw JsonRpcParameterException as a checked exception, forcing callers to - // handle it to supply appropriate context - @SuppressWarnings("unchecked") - public Optional optional( - final Object[] params, final int index, final Class paramClass) { + public Optional optional(final Object[] params, final int index, final Class paramClass) + throws JsonRpcParameterException { if (params == null || params.length <= index || params[index] == null) { return Optional.empty(); } @@ -73,14 +67,14 @@ public Optional optional( final Object rawParam = params[index]; if (paramClass.isAssignableFrom(rawParam.getClass())) { // If we're dealing with a simple type, just cast the value - param = (T) rawParam; + param = paramClass.cast(rawParam); } else { // Otherwise, serialize param back to json and then deserialize to the paramClass type try { final String json = mapper.writeValueAsString(rawParam); param = mapper.readValue(json, paramClass); } catch (final JsonProcessingException e) { - throw new InvalidJsonRpcParameters( + throw new JsonRpcParameterException( String.format( "Invalid json rpc parameter at index %d. Supplied value was: '%s' of type: '%s' - expected type: '%s'", index, rawParam, rawParam.getClass().getName(), paramClass.getName()), @@ -91,10 +85,9 @@ public Optional optional( return Optional.of(param); } - // TODO: update to throw JsonRpcParameterException as a checked exception, forcing callers to - // handle it to supply appropriate context public Optional> optionalList( - final Object[] params, final int index, final Class listClass) { + final Object[] params, final int index, final Class listClass) + throws JsonRpcParameterException { if (params == null || params.length <= index || params[index] == null) { return Optional.empty(); } @@ -105,7 +98,7 @@ public Optional> optionalList( List returnedList = mapper.readValue(listJson, new TypeReference>() {}); return Optional.of(returnedList); } catch (JsonProcessingException e) { - throw new InvalidJsonRpcParameters( + throw new JsonRpcParameterException( String.format( "Invalid json rpc parameter at index %d. Supplied value was: '%s' of type: '%s' - expected type: '%s'", index, rawParam, rawParam.getClass().getName(), listClass.getName()), diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivGetFilterChanges.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivGetFilterChanges.java index bbd7189ffa3f..4ef7e0aa1c32 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivGetFilterChanges.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivGetFilterChanges.java @@ -19,6 +19,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.filter.FilterManager; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -55,7 +56,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String privacyGroupId; try { privacyGroupId = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, @@ -64,7 +65,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String filterId; try { filterId = requestContext.getRequiredParameter(1, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter ID parameter (index 1)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivGetFilterLogs.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivGetFilterLogs.java index 4436c33b502c..ea6a5894a332 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivGetFilterLogs.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivGetFilterLogs.java @@ -19,6 +19,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.filter.FilterManager; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -55,7 +56,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext request) { final String privacyGroupId; try { privacyGroupId = request.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, @@ -64,7 +65,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext request) { final String filterId; try { filterId = request.getRequiredParameter(1, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter ID parameter (index 1)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivUninstallFilter.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivUninstallFilter.java index c1e122578ab0..eb41a1dad4ec 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivUninstallFilter.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/PrivUninstallFilter.java @@ -19,6 +19,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.filter.FilterManager; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -50,7 +51,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext request) { final String privacyGroupId; try { privacyGroupId = request.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, @@ -59,7 +60,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext request) { final String filterId; try { filterId = request.getRequiredParameter(1, String.class); - } catch (Exception e) { + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter ID parameter (index 1)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/eea/AbstractEeaSendRawTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/eea/AbstractEeaSendRawTransaction.java index 12c496b639df..e96a08eb7d44 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/eea/AbstractEeaSendRawTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/eea/AbstractEeaSendRawTransaction.java @@ -25,6 +25,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -77,7 +78,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String rawPrivateTransaction; try { rawPrivateTransaction = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivCall.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivCall.java index e09d5966cf5d..5d9edc63b9d3 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivCall.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivCall.java @@ -21,6 +21,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.AbstractBlockParameterMethod; 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.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; @@ -55,7 +56,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(2, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 2)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -68,7 +69,7 @@ protected Object resultByBlockNumber( final String privacyGroupId; try { privacyGroupId = request.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, @@ -115,7 +116,7 @@ private JsonCallParameter validateAndGetCallParams(final JsonRpcRequestContext r final JsonCallParameter callParams; try { callParams = request.getRequiredParameter(1, JsonCallParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid call parameters (index 1)", RpcErrorType.INVALID_CALL_PARAMS); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivCreatePrivacyGroup.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivCreatePrivacyGroup.java index ae35506298f0..568125a27628 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivCreatePrivacyGroup.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivCreatePrivacyGroup.java @@ -20,6 +20,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.parameters.CreatePrivacyGroupParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; @@ -55,7 +56,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final CreatePrivacyGroupParameter parameter; try { parameter = requestContext.getRequiredParameter(0, CreatePrivacyGroupParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid create privacy group parameter (index 0)", RpcErrorType.INVALID_CREATE_PRIVACY_GROUP_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDebugGetStateRoot.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDebugGetStateRoot.java index 9ee5d57b3b40..dc0fc90f6613 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDebugGetStateRoot.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDebugGetStateRoot.java @@ -23,6 +23,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.AbstractBlockParameterMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -63,7 +64,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(1, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 1)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -75,7 +76,7 @@ protected Object resultByBlockNumber( final String privacyGroupId; try { privacyGroupId = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDeletePrivacyGroup.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDeletePrivacyGroup.java index 5c6f929c5c2a..61b7791b3c0b 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDeletePrivacyGroup.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDeletePrivacyGroup.java @@ -20,6 +20,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -55,7 +56,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String privacyGroupId; try { privacyGroupId = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDistributeRawTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDistributeRawTransaction.java index 39003358ede1..aac4df3d2c97 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDistributeRawTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivDistributeRawTransaction.java @@ -25,6 +25,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -74,7 +75,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String rawPrivateTransaction; try { rawPrivateTransaction = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid private transaction parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivFindPrivacyGroup.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivFindPrivacyGroup.java index 8f0e82908428..7e823232237c 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivFindPrivacyGroup.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivFindPrivacyGroup.java @@ -21,6 +21,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -60,7 +61,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String[] addresses; try { addresses = requestContext.getRequiredParameter(0, String[].class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameters (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetCode.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetCode.java index 5d9498f3bd43..7042d357f125 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetCode.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetCode.java @@ -20,6 +20,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.AbstractBlockParameterMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.BlockParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.query.BlockchainQueries; @@ -50,7 +51,7 @@ public String getName() { protected BlockParameter blockParameter(final JsonRpcRequestContext request) { try { return request.getRequiredParameter(2, BlockParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 2)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } @@ -62,7 +63,7 @@ protected String resultByBlockNumber( final String privacyGroupId; try { privacyGroupId = request.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, @@ -71,7 +72,7 @@ protected String resultByBlockNumber( final Address address; try { address = request.getRequiredParameter(1, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 1)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetEeaTransactionCount.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetEeaTransactionCount.java index 31bfc52c804e..9f231f41c06d 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetEeaTransactionCount.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetEeaTransactionCount.java @@ -22,6 +22,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -69,21 +70,21 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Address address; try { address = requestContext.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } final String privateFrom; try { privateFrom = requestContext.getRequiredParameter(1, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid private from parameter (index 1)", RpcErrorType.INVALID_PRIVATE_FROM_PARAMS, e); } final String[] privateFor; try { privateFor = requestContext.getRequiredParameter(2, String[].class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid private for parameters (index 2)", RpcErrorType.INVALID_PRIVATE_FOR_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetLogs.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetLogs.java index d0c75da33fb9..6947ea5e546c 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetLogs.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetLogs.java @@ -20,6 +20,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.FilterParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -74,7 +75,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final FilterParameter filter; try { filter = requestContext.getRequiredParameter(1, FilterParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter parameter (index 1)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetPrivateTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetPrivateTransaction.java index 0629b2d55d49..8779181599e5 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetPrivateTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetPrivateTransaction.java @@ -21,6 +21,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -62,7 +63,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash hash; try { hash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetTransactionCount.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetTransactionCount.java index 2cbcc655359d..d8757dc2fbdf 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetTransactionCount.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetTransactionCount.java @@ -21,6 +21,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -60,14 +61,14 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Address address; try { address = requestContext.getRequiredParameter(0, Address.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameter (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } final String privacyGroupId; try { privacyGroupId = requestContext.getRequiredParameter(1, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 1)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetTransactionReceipt.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetTransactionReceipt.java index a1844841f00c..287793ddc01b 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetTransactionReceipt.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivGetTransactionReceipt.java @@ -22,6 +22,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -70,7 +71,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash pmtTransactionHash; try { pmtTransactionHash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivNewFilter.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivNewFilter.java index e73b0c141c61..49fc11f4b824 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivNewFilter.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivNewFilter.java @@ -20,6 +20,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.filter.FilterManager; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.FilterParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -51,9 +52,9 @@ public String getName() { @Override public JsonRpcResponse response(final JsonRpcRequestContext request) { final String privacyGroupId; - try { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + try { privacyGroupId = request.getRequiredParameter(0, String.class); - } catch (Exception e) { + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, @@ -62,7 +63,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext request) { final FilterParameter filter; try { filter = request.getRequiredParameter(1, FilterParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter parameter (index 1)", RpcErrorType.INVALID_FILTER_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivTraceTransaction.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivTraceTransaction.java index b1802b07eb71..07d663bef552 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivTraceTransaction.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/priv/PrivTraceTransaction.java @@ -17,8 +17,10 @@ import org.hyperledger.besu.datatypes.Hash; 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.InvalidJsonRpcParameters; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.JsonRpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.methods.TraceTransaction; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.processor.privateProcessor.PrivateBlockTracer; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; @@ -69,8 +71,24 @@ public String getName() { @Override public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { - final String privacyGroupId = requestContext.getRequiredParameter(0, String.class); - final Hash transactionHash = requestContext.getRequiredParameter(1, Hash.class); + final String privacyGroupId; + try { + privacyGroupId = requestContext.getRequiredParameter(0, String.class); + } catch (JsonRpcParameterException e) { + throw new InvalidJsonRpcParameters( + "Invalid privacy group ID parameter (index 0)", + RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, + e); + } + final Hash transactionHash; + try { + transactionHash = requestContext.getRequiredParameter(1, Hash.class); + } catch (JsonRpcParameterException e) { + throw new InvalidJsonRpcParameters( + "Invalid transaction hash parameter (index 1)", + RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, + e); + } LOG.trace("Received RPC rpcName={} txHash={}", getName(), transactionHash); if (privacyGroupId.isEmpty() || transactionHash.isEmpty()) { diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/privx/PrivxFindFlexiblePrivacyGroup.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/privx/PrivxFindFlexiblePrivacyGroup.java index e6cf056989d0..0a66d1aa73bc 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/privx/PrivxFindFlexiblePrivacyGroup.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/privacy/methods/privx/PrivxFindFlexiblePrivacyGroup.java @@ -21,6 +21,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.privacy.methods.PrivacyIdProvider; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; @@ -59,7 +60,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String[] addresses; try { addresses = requestContext.getRequiredParameter(0, String[].class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid address parameters (index 0)", RpcErrorType.INVALID_ADDRESS_PARAMS, e); } diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/response/RpcErrorType.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/response/RpcErrorType.java index cb19d2e7a356..009fca38fc08 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/response/RpcErrorType.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/response/RpcErrorType.java @@ -66,8 +66,8 @@ public enum RpcErrorType implements RpcMethodError { INVALID_GAS_PRICE_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid gas price params"), INVALID_HASH_RATE_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid hash rate params"), INVALID_ID_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid ID params"), - INVALID_IS_TRANSACTION_COMPLETE_PARAMS( - INVALID_PARAMS_ERROR_CODE, "Invalid is transaction complete params"), + INVALID_RETURN_COMPLETE_TRANSACTION_PARAMS( + INVALID_PARAMS_ERROR_CODE, "Invalid return complete transaction params"), INVALID_LOG_FILTER_PARAMS(INVALID_PARAMS_ERROR_CODE, "Invalid log filter params"), INVALID_LOG_LEVEL_PARAMS( INVALID_PARAMS_ERROR_CODE, "Invalid log level params (missing or incorrect)"), diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/subscription/request/SubscriptionRequestMapper.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/subscription/request/SubscriptionRequestMapper.java index 7235a81987a8..8bc357984958 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/subscription/request/SubscriptionRequestMapper.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/subscription/request/SubscriptionRequestMapper.java @@ -17,6 +17,7 @@ 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.parameters.FilterParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.UnsignedLongParameter; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.methods.WebSocketRpcRequest; @@ -35,7 +36,7 @@ public SubscribeRequest mapSubscribeRequest(final JsonRpcRequestContext jsonRpcR final SubscriptionType subscriptionType; try { subscriptionType = webSocketRpcRequestBody.getRequiredParameter(0, SubscriptionType.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid subscription type parameter (index 0)", RpcErrorType.INVALID_SUBSCRIPTION_PARAMS, @@ -70,7 +71,7 @@ private boolean includeTransactions(final WebSocketRpcRequest webSocketRpcReques final Optional params; try { params = webSocketRpcRequestBody.getOptionalParameter(1, SubscriptionParam.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid subscription parameter (index 1)", RpcErrorType.INVALID_SUBSCRIPTION_PARAMS, e); } @@ -87,7 +88,7 @@ private SubscribeRequest parseLogsRequest(final WebSocketRpcRequest request) { final FilterParameter filterParameter; try { filterParameter = request.getRequiredParameter(1, FilterParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter parameters (index 1)", RpcErrorType.INVALID_FILTER_PARAMS, e); } @@ -104,7 +105,7 @@ public UnsubscribeRequest mapUnsubscribeRequest(final JsonRpcRequestContext json try { subscriptionId = webSocketRpcRequestBody.getRequiredParameter(0, UnsignedLongParameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid subscription ID parameter (index 0)", RpcErrorType.INVALID_SUBSCRIPTION_PARAMS, @@ -125,7 +126,7 @@ public PrivateSubscribeRequest mapPrivateSubscribeRequest( final String privacyGroupId; try { privacyGroupId = webSocketRpcRequestBody.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, @@ -134,7 +135,7 @@ public PrivateSubscribeRequest mapPrivateSubscribeRequest( final SubscriptionType subscriptionType; try { subscriptionType = webSocketRpcRequestBody.getRequiredParameter(1, SubscriptionType.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid subscription type parameter (index 1)", RpcErrorType.INVALID_SUBSCRIPTION_PARAMS, @@ -148,7 +149,7 @@ public PrivateSubscribeRequest mapPrivateSubscribeRequest( try { filterParameter = jsonRpcRequestContext.getRequiredParameter(2, FilterParameter.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid filter parameter (index 2)", RpcErrorType.INVALID_FILTER_PARAMS, e); } @@ -180,7 +181,7 @@ public PrivateUnsubscribeRequest mapPrivateUnsubscribeRequest( final String privacyGroupId; try { privacyGroupId = webSocketRpcRequestBody.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid privacy group ID parameter (index 0)", RpcErrorType.INVALID_PRIVACY_GROUP_PARAMS, @@ -190,7 +191,7 @@ public PrivateUnsubscribeRequest mapPrivateUnsubscribeRequest( try { subscriptionId = webSocketRpcRequestBody.getRequiredParameter(1, UnsignedLongParameter.class).getValue(); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid subscription ID parameter (index 1)", RpcErrorType.INVALID_SUBSCRIPTION_PARAMS, diff --git a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueries.java b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueries.java index 16b683ed712d..6e0f0e3e35c2 100644 --- a/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueries.java +++ b/ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/query/BlockchainQueries.java @@ -60,6 +60,7 @@ import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.LongStream; +import java.util.stream.Stream; import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.units.bigints.UInt256; @@ -976,27 +977,35 @@ public Optional getAndMapWorldState( } public Wei gasPrice() { - final long blockHeight = headBlockNumber(); - final var chainHeadHeader = blockchain.getChainHeadHeader(); + final Block chainHeadBlock = blockchain.getChainHeadBlock(); + final var chainHeadHeader = chainHeadBlock.getHeader(); + final long blockHeight = chainHeadHeader.getNumber(); + final var nextBlockProtocolSpec = protocolSchedule.getForNextBlockHeader(chainHeadHeader, System.currentTimeMillis()); final var nextBlockFeeMarket = nextBlockProtocolSpec.getFeeMarket(); + final Wei[] gasCollection = - LongStream.rangeClosed( - Math.max(0, blockHeight - apiConfig.getGasPriceBlocks() + 1), blockHeight) - .mapToObj( - l -> - blockchain - .getBlockByNumber(l) - .map(Block::getBody) - .map(BlockBody::getTransactions) - .orElseThrow( - () -> new IllegalStateException("Could not retrieve block #" + l))) + Stream.concat( + LongStream.range( + Math.max(0, blockHeight - apiConfig.getGasPriceBlocks() + 1), blockHeight) + .mapToObj( + l -> + blockchain + .getBlockByNumber(l) + .orElseThrow( + () -> + new IllegalStateException( + "Could not retrieve block #" + l))), + Stream.of(chainHeadBlock)) + .map(Block::getBody) + .map(BlockBody::getTransactions) .flatMap(Collection::stream) .filter(t -> t.getGasPrice().isPresent()) .map(t -> t.getGasPrice().get()) .sorted() .toArray(Wei[]::new); + return (gasCollection == null || gasCollection.length == 0) ? gasPriceLowerBound(chainHeadHeader, nextBlockFeeMarket) : UInt256s.max( diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTest.java index dcfd198d6e13..bb5cb68a2ae8 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTest.java @@ -784,7 +784,7 @@ public void getBlockByHashWithMissingBooleanParameter() throws Exception { assertThat(resp.code()).isEqualTo(200); // Check general format of result final JsonObject json = new JsonObject(resp.body().string()); - final RpcErrorType expectedError = RpcErrorType.INVALID_IS_TRANSACTION_COMPLETE_PARAMS; + final RpcErrorType expectedError = RpcErrorType.INVALID_RETURN_COMPLETE_TRANSACTION_PARAMS; testHelper.assertValidJsonRpcError( json, id, expectedError.getCode(), expectedError.getMessage()); } @@ -854,7 +854,7 @@ public void getBlockByHashWithInvalidBooleanParameter() throws Exception { assertThat(resp.code()).isEqualTo(200); // Check general format of result final JsonObject json = new JsonObject(resp.body().string()); - final RpcErrorType expectedError = RpcErrorType.INVALID_IS_TRANSACTION_COMPLETE_PARAMS; + final RpcErrorType expectedError = RpcErrorType.INVALID_RETURN_COMPLETE_TRANSACTION_PARAMS; testHelper.assertValidJsonRpcError( json, id, expectedError.getCode(), expectedError.getMessage()); } diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugMetricsTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugMetricsTest.java index 6e41fc9c1bff..d4830cb85a7c 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugMetricsTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/DebugMetricsTest.java @@ -16,6 +16,7 @@ import static java.util.Arrays.asList; import static org.assertj.core.api.Assertions.assertThat; +import static org.hyperledger.besu.metrics.BesuMetricCategory.BLOCKCHAIN; import static org.hyperledger.besu.metrics.BesuMetricCategory.PEERS; import static org.hyperledger.besu.metrics.BesuMetricCategory.RPC; import static org.mockito.Mockito.mock; @@ -28,6 +29,7 @@ import org.hyperledger.besu.metrics.Observation; import java.util.Collections; +import java.util.List; import java.util.stream.Stream; import com.google.common.collect.ImmutableMap; @@ -84,6 +86,36 @@ public void shouldNestObservationsByLabel() { ImmutableMap.of("label2B", "value3"))))); } + @Test + public void shouldHandleDoubleValuesInNestedStructureWithoutClassCastException() { + // Tests fix for issue# 7383: debug_metrics method error + when(metricsSystem.streamObservations()) + .thenReturn( + Stream.of( + // This creates a double value for "a" + new Observation(BLOCKCHAIN, "nested_metric", 1.0, List.of("a")), + // This attempts to create a nested structure under "a", which was previously a + // double + new Observation(BLOCKCHAIN, "nested_metric", 2.0, asList("a", "b")), + // This adds another level of nesting + new Observation(BLOCKCHAIN, "nested_metric", 3.0, asList("a", "b", "c")))); + + assertResponse( + ImmutableMap.of( + BLOCKCHAIN.getName(), + ImmutableMap.of( + "nested_metric", + ImmutableMap.of( + "a", + ImmutableMap.of( + "value", + 1.0, + "b", + ImmutableMap.of( + "value", 2.0, + "c", 3.0)))))); + } + private void assertResponse(final ImmutableMap expectedResponse) { final JsonRpcSuccessResponse response = (JsonRpcSuccessResponse) method.response(REQUEST); assertThat(response.getResult()).isEqualTo(expectedResponse); diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGasPriceTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGasPriceTest.java index 54e17cb21cbc..5d6aba769425 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGasPriceTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGasPriceTest.java @@ -17,7 +17,9 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.Mockito.lenient; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; @@ -61,7 +63,6 @@ import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.mockito.Mock; -import org.mockito.internal.verification.VerificationModeFactory; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) @@ -106,8 +107,8 @@ public void shouldReturnMinValueWhenNoTransactionsExist() { final JsonRpcResponse actualResponse = method.response(request); assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse); - verify(blockchain).getChainHeadBlockNumber(); - verify(blockchain, VerificationModeFactory.times(100)).getBlockByNumber(anyLong()); + verify(blockchain).getChainHeadBlock(); + verify(blockchain, times(99)).getBlockByNumber(anyLong()); verifyNoMoreInteractions(blockchain); } @@ -127,8 +128,7 @@ public void shouldReturnBaseFeeAsMinValueOnGenesis() { final JsonRpcResponse actualResponse = method.response(request); assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse); - verify(blockchain).getChainHeadBlockNumber(); - verify(blockchain, VerificationModeFactory.times(1)).getBlockByNumber(anyLong()); + verify(blockchain).getChainHeadBlock(); verifyNoMoreInteractions(blockchain); } @@ -146,8 +146,8 @@ public void shouldReturnMedianWhenTransactionsExist() { final JsonRpcResponse actualResponse = method.response(request); assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse); - verify(blockchain).getChainHeadBlockNumber(); - verify(blockchain, VerificationModeFactory.times(100)).getBlockByNumber(anyLong()); + verify(blockchain).getChainHeadBlock(); + verify(blockchain, times(99)).getBlockByNumber(anyLong()); verifyNoMoreInteractions(blockchain); } @@ -165,8 +165,8 @@ public void shortChainQueriesAllBlocks() { final JsonRpcResponse actualResponse = method.response(request); assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse); - verify(blockchain).getChainHeadBlockNumber(); - verify(blockchain, VerificationModeFactory.times(81)).getBlockByNumber(anyLong()); + verify(blockchain).getChainHeadBlock(); + verify(blockchain, times(80)).getBlockByNumber(anyLong()); verifyNoMoreInteractions(blockchain); } @@ -252,8 +252,7 @@ public void ethGasPriceAtGenesis( final JsonRpcResponse actualResponse = method.response(request); assertThat(actualResponse).usingRecursiveComparison().isEqualTo(expectedResponse); - verify(blockchain).getChainHeadBlockNumber(); - verify(blockchain, VerificationModeFactory.times(1)).getBlockByNumber(anyLong()); + verify(blockchain).getChainHeadBlock(); verifyNoMoreInteractions(blockchain); } @@ -328,12 +327,14 @@ private void mockBlockchain( blocksByNumber.put(i, createFakeBlock(i, txsNum, baseFee)); } - when(blockchain.getChainHeadBlockNumber()).thenReturn(chainHeadBlockNumber); - when(blockchain.getBlockByNumber(anyLong())) - .thenAnswer( - invocation -> Optional.of(blocksByNumber.get(invocation.getArgument(0, Long.class)))); - - when(blockchain.getChainHeadHeader()) + when(blockchain.getChainHeadBlock()).thenReturn(blocksByNumber.get(chainHeadBlockNumber)); + if (chainHeadBlockNumber > 1) { + when(blockchain.getBlockByNumber(anyLong())) + .thenAnswer( + invocation -> Optional.of(blocksByNumber.get(invocation.getArgument(0, Long.class)))); + } + lenient() + .when(blockchain.getChainHeadHeader()) .thenReturn(blocksByNumber.get(chainHeadBlockNumber).getHeader()); } diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByHashTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByHashTest.java index 0fc8969c9388..e79fff04f7fb 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByHashTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByHashTest.java @@ -69,7 +69,7 @@ public void exceptionWhenNoHashSupplied() { public void exceptionWhenNoBoolSupplied() { assertThatThrownBy(() -> method.response(requestWithParams(ZERO_HASH))) .isInstanceOf(InvalidJsonRpcParameters.class) - .hasMessage("Invalid is complete transaction parameter (index 1)"); + .hasMessage("Invalid return complete transaction parameter (index 1)"); verifyNoMoreInteractions(blockchainQueries); } @@ -85,7 +85,7 @@ public void exceptionWhenHashParamInvalid() { public void exceptionWhenBoolParamInvalid() { assertThatThrownBy(() -> method.response(requestWithParams(ZERO_HASH, "maybe"))) .isInstanceOf(InvalidJsonRpcParameters.class) - .hasMessage("Invalid is complete transaction parameter (index 1)"); + .hasMessage("Invalid return complete transaction parameter (index 1)"); verifyNoMoreInteractions(blockchainQueries); } diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByNumberTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByNumberTest.java index bc6ec997f347..254d0fbe9e8a 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByNumberTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/EthGetBlockByNumberTest.java @@ -121,7 +121,7 @@ public void exceptionWhenNoNumberSupplied() { public void exceptionWhenNoBoolSupplied() { assertThatThrownBy(() -> method.response(requestWithParams("0"))) .isInstanceOf(InvalidJsonRpcParameters.class) - .hasMessage("Invalid is transaction complete parameter (index 1)"); + .hasMessage("Invalid return complete transaction parameter (index 1)"); verifyNoMoreInteractions(blockchainQueries); } @@ -137,7 +137,7 @@ public void exceptionWhenNumberParamInvalid() { public void exceptionWhenBoolParamInvalid() { assertThatThrownBy(() -> method.response(requestWithParams("0", "maybe"))) .isInstanceOf(InvalidJsonRpcParameters.class) - .hasMessage("Invalid is transaction complete parameter (index 1)"); + .hasMessage("Invalid return complete transaction parameter (index 1)"); verifyNoMoreInteractions(blockchainQueries); } diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TxPoolBesuPendingTransactionsTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TxPoolBesuPendingTransactionsTest.java index 9cc6947b2607..1eef04fb93aa 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TxPoolBesuPendingTransactionsTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/TxPoolBesuPendingTransactionsTest.java @@ -201,7 +201,7 @@ public void shouldReturnsErrorIfInvalidPredicate() { assertThatThrownBy(() -> method.response(request)) .isInstanceOf(InvalidJsonRpcParameters.class) - .hasMessageContaining("Invalid pending transactions parameter (index 1)"); + .hasMessageContaining("Unknown field expected one of `eq`, `gt`, `lt`, `action`"); } @Test @@ -229,7 +229,7 @@ public void shouldReturnsErrorIfInvalidNumberOfPredicate() { assertThatThrownBy(() -> method.response(request)) .isInstanceOf(InvalidJsonRpcParameters.class) - .hasMessageContaining("Invalid pending transactions parameter (index 1)"); + .hasMessageContaining("Only one operator per filter type allowed"); } @Test @@ -256,7 +256,7 @@ public void shouldReturnsErrorIfInvalidPredicateUsedForFromField() { assertThatThrownBy(() -> method.response(request)) .isInstanceOf(InvalidJsonRpcParameters.class) - .hasMessageContaining("Invalid pending transactions parameter (index 1)"); + .hasMessageContaining("The `from` filter only supports the `eq` operator"); } @Test @@ -283,7 +283,7 @@ public void shouldReturnsErrorIfInvalidPredicateUsedForToField() { assertThatThrownBy(() -> method.response(request)) .isInstanceOf(InvalidJsonRpcParameters.class) - .hasMessageContaining("Invalid pending transactions parameter (index 1)"); + .hasMessageContaining("The `to` filter only supports the `eq` or `action` operator"); } private Set getTransactionPool() { diff --git a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EnginePreparePayloadDebugTest.java b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EnginePreparePayloadDebugTest.java index 4de9f8bb56ef..9c5067f7a83c 100644 --- a/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EnginePreparePayloadDebugTest.java +++ b/ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/engine/EnginePreparePayloadDebugTest.java @@ -28,6 +28,7 @@ import org.hyperledger.besu.ethereum.ProtocolContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequestContext; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.EnginePreparePayloadParameter; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.EnginePreparePayloadResult; @@ -56,7 +57,7 @@ public class EnginePreparePayloadDebugTest { @Mock private EnginePreparePayloadParameter param; @BeforeEach - public void setUp() { + public void setUp() throws JsonRpcParameterException { when(protocolContext.safeConsensusContext(MergeContext.class)) .thenReturn(Optional.of(mergeContext)); when(requestContext.getOptionalParameter(0, EnginePreparePayloadParameter.class)) @@ -84,7 +85,7 @@ public void shouldReturnPayloadId() { } @Test - public void shouldReturnPayloadIdWhenNoParams() { + public void shouldReturnPayloadIdWhenNoParams() throws JsonRpcParameterException { when(requestContext.getOptionalParameter(0, EnginePreparePayloadParameter.class)) .thenReturn(Optional.empty()); checkForPayloadId(); diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java index a3dd13bd1b56..f8bf6d50c5cf 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockSelectionContext.java @@ -29,7 +29,7 @@ public record BlockSelectionContext( GasCalculator gasCalculator, GasLimitCalculator gasLimitCalculator, BlockHashProcessor blockHashProcessor, - ProcessableBlockHeader processableBlockHeader, + ProcessableBlockHeader pendingBlockHeader, FeeMarket feeMarket, Wei blobGasPrice, Address miningBeneficiary, diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java index ed028767d6aa..3d56c1fc07be 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/BlockTransactionSelector.java @@ -263,9 +263,10 @@ private TransactionEvaluationContext createTransactionEvaluationContext( .getTransactionPriceCalculator() .price( pendingTransaction.getTransaction(), - blockSelectionContext.processableBlockHeader().getBaseFee()); + blockSelectionContext.pendingBlockHeader().getBaseFee()); return new TransactionEvaluationContext( + blockSelectionContext.pendingBlockHeader(), pendingTransaction, Stopwatch.createStarted(), transactionGasPriceInBlock, @@ -330,10 +331,10 @@ private TransactionSelectionResult evaluatePostProcessing( private TransactionProcessingResult processTransaction( final PendingTransaction pendingTransaction, final WorldUpdater worldStateUpdater) { final BlockHashLookup blockHashLookup = - new CachingBlockHashLookup(blockSelectionContext.processableBlockHeader(), blockchain); + new CachingBlockHashLookup(blockSelectionContext.pendingBlockHeader(), blockchain); return transactionProcessor.processTransaction( worldStateUpdater, - blockSelectionContext.processableBlockHeader(), + blockSelectionContext.pendingBlockHeader(), pendingTransaction.getTransaction(), blockSelectionContext.miningBeneficiary(), pluginOperationTracer, diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/TransactionEvaluationContext.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/TransactionEvaluationContext.java index 0a17812b0f97..7fce600a1a61 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/TransactionEvaluationContext.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/TransactionEvaluationContext.java @@ -17,23 +17,26 @@ import org.hyperledger.besu.datatypes.Wei; import org.hyperledger.besu.ethereum.core.Transaction; import org.hyperledger.besu.ethereum.eth.transactions.PendingTransaction; +import org.hyperledger.besu.plugin.data.ProcessableBlockHeader; import com.google.common.base.Stopwatch; public class TransactionEvaluationContext implements org.hyperledger.besu.plugin.services.txselection.TransactionEvaluationContext< PendingTransaction> { - private final org.hyperledger.besu.ethereum.eth.transactions.PendingTransaction - pendingTransaction; + private final ProcessableBlockHeader pendingBlockHeader; + private final PendingTransaction pendingTransaction; private final Stopwatch evaluationTimer; private final Wei transactionGasPrice; private final Wei minGasPrice; public TransactionEvaluationContext( + final ProcessableBlockHeader pendingBlockHeader, final PendingTransaction pendingTransaction, final Stopwatch evaluationTimer, final Wei transactionGasPrice, final Wei minGasPrice) { + this.pendingBlockHeader = pendingBlockHeader; this.pendingTransaction = pendingTransaction; this.evaluationTimer = evaluationTimer; this.transactionGasPrice = transactionGasPrice; @@ -44,6 +47,11 @@ public Transaction getTransaction() { return pendingTransaction.getTransaction(); } + @Override + public ProcessableBlockHeader getPendingBlockHeader() { + return pendingBlockHeader; + } + @Override public PendingTransaction getPendingTransaction() { return pendingTransaction; diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java index 793f3e93842f..2877c4ce1395 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlockSizeTransactionSelector.java @@ -91,7 +91,7 @@ private boolean transactionTooLargeForBlock( final TransactionSelectionResults transactionSelectionResults) { return transaction.getGasLimit() - > context.processableBlockHeader().getGasLimit() + > context.pendingBlockHeader().getGasLimit() - transactionSelectionResults.getCumulativeGasUsed(); } @@ -104,7 +104,7 @@ private boolean transactionTooLargeForBlock( */ private boolean blockOccupancyAboveThreshold( final TransactionSelectionResults transactionSelectionResults) { - final long gasAvailable = context.processableBlockHeader().getGasLimit(); + final long gasAvailable = context.pendingBlockHeader().getGasLimit(); final long gasUsed = transactionSelectionResults.getCumulativeGasUsed(); final long gasRemaining = gasAvailable - gasUsed; @@ -129,7 +129,7 @@ private boolean blockOccupancyAboveThreshold( * @return True if the block is full, false otherwise. */ private boolean blockFull(final TransactionSelectionResults transactionSelectionResults) { - final long gasAvailable = context.processableBlockHeader().getGasLimit(); + final long gasAvailable = context.pendingBlockHeader().getGasLimit(); final long gasUsed = transactionSelectionResults.getCumulativeGasUsed(); final long gasRemaining = gasAvailable - gasUsed; diff --git a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/MinPriorityFeePerGasTransactionSelector.java b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/MinPriorityFeePerGasTransactionSelector.java index fc32a5c08cae..5783c7e50074 100644 --- a/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/MinPriorityFeePerGasTransactionSelector.java +++ b/ethereum/blockcreation/src/main/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/MinPriorityFeePerGasTransactionSelector.java @@ -68,7 +68,7 @@ private boolean isPriorityFeePriceBelowMinimum(final PendingTransaction pendingT Wei priorityFeePerGas = pendingTransaction .getTransaction() - .getEffectivePriorityFeePerGas(context.processableBlockHeader().getBaseFee()); + .getEffectivePriorityFeePerGas(context.pendingBlockHeader().getBaseFee()); return priorityFeePerGas.lessThan(context.miningParameters().getMinPriorityFeePerGas()); } diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/MinPriorityFeePerGasTransactionSelectorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/MinPriorityFeePerGasTransactionSelectorTest.java index 8122dc3088c4..6f81f4df2c6d 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/MinPriorityFeePerGasTransactionSelectorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/MinPriorityFeePerGasTransactionSelectorTest.java @@ -33,11 +33,16 @@ import com.google.common.base.Stopwatch; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +@ExtendWith(MockitoExtension.class) public class MinPriorityFeePerGasTransactionSelectorTest { private AbstractTransactionSelector transactionSelector; private final int minPriorityFeeParameter = 7; + @Mock private ProcessableBlockHeader pendingBlockHeader; @BeforeEach public void initialize() { @@ -45,15 +50,7 @@ public void initialize() { MiningParameters.newDefault().setMinPriorityFeePerGas(Wei.of(minPriorityFeeParameter)); BlockSelectionContext context = new BlockSelectionContext( - miningParameters, - null, - null, - null, - mock(ProcessableBlockHeader.class), - null, - null, - null, - null); + miningParameters, null, null, null, pendingBlockHeader, null, null, null, null); transactionSelector = new MinPriorityFeePerGasTransactionSelector(context); } @@ -100,6 +97,6 @@ private TransactionEvaluationContext mockTransactionEvaluationContext( when(pendingTransaction.getTransaction()).thenReturn(transaction); when(transaction.getEffectivePriorityFeePerGas(any())).thenReturn(Wei.of(priorityFeePerGas)); return new TransactionEvaluationContext( - pendingTransaction, Stopwatch.createStarted(), Wei.ONE, Wei.ONE); + pendingBlockHeader, pendingTransaction, Stopwatch.createStarted(), Wei.ONE, Wei.ONE); } } diff --git a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlobSizeTransactionSelectorTest.java b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlobSizeTransactionSelectorTest.java index f52a5dfb462c..123faf2d18ab 100644 --- a/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlobSizeTransactionSelectorTest.java +++ b/ethereum/blockcreation/src/test/java/org/hyperledger/besu/ethereum/blockcreation/txselection/selectors/BlobSizeTransactionSelectorTest.java @@ -76,7 +76,9 @@ void notBlobTransactionsAreSelectedWithoutAnyCheck() { final var nonBlobTx = createEIP1559PendingTransaction(); - final var txEvaluationContext = new TransactionEvaluationContext(nonBlobTx, null, null, null); + final var txEvaluationContext = + new TransactionEvaluationContext( + blockSelectionContext.pendingBlockHeader(), nonBlobTx, null, null, null); final var result = selector.evaluateTransactionPreProcessing(txEvaluationContext, selectionResults); @@ -94,7 +96,9 @@ void firstBlobTransactionIsSelected() { final var firstBlobTx = createBlobPendingTransaction(MAX_BLOBS); - final var txEvaluationContext = new TransactionEvaluationContext(firstBlobTx, null, null, null); + final var txEvaluationContext = + new TransactionEvaluationContext( + blockSelectionContext.pendingBlockHeader(), firstBlobTx, null, null, null); when(selectionResults.getCumulativeBlobGasUsed()).thenReturn(0L); @@ -112,7 +116,9 @@ void returnsBlobsFullWhenMaxNumberOfBlobsAlreadyPresent() { final var firstBlobTx = createBlobPendingTransaction(1); - final var txEvaluationContext = new TransactionEvaluationContext(firstBlobTx, null, null, null); + final var txEvaluationContext = + new TransactionEvaluationContext( + blockSelectionContext.pendingBlockHeader(), firstBlobTx, null, null, null); when(selectionResults.getCumulativeBlobGasUsed()).thenReturn(MAX_BLOB_GAS); @@ -132,7 +138,9 @@ void returnsTooLargeForRemainingBlobGas() { final var firstBlobTx = createBlobPendingTransaction(MAX_BLOBS); - final var txEvaluationContext = new TransactionEvaluationContext(firstBlobTx, null, null, null); + final var txEvaluationContext = + new TransactionEvaluationContext( + blockSelectionContext.pendingBlockHeader(), firstBlobTx, null, null, null); when(selectionResults.getCumulativeBlobGasUsed()).thenReturn(MAX_BLOB_GAS - 1); diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/Blockchain.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/Blockchain.java index 3c76ba69f5ca..49b6fea33e15 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/Blockchain.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/Blockchain.java @@ -167,6 +167,15 @@ default boolean contains(final Hash blockHash) { */ Optional getBlockBody(Hash blockHeaderHash); + /** + * Safe version of {@code getBlockBody} (it should take any locks necessary to ensure any block + * updates that might be taking place have been completed first) + * + * @param blockHeaderHash The hash of the block whose header we want to retrieve. + * @return The block body corresponding to this block hash. + */ + Optional getBlockBodySafe(Hash blockHeaderHash); + /** * Given a block's hash, returns the list of transaction receipts associated with this block's * transactions. Associated block is not necessarily on the canonical chain. diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchain.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchain.java index 04eaaa6a353d..5849f3e676c0 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchain.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/chain/DefaultBlockchain.java @@ -299,7 +299,10 @@ public BlockHeader getChainHeadHeader() { @Override public Block getChainHeadBlock() { - return new Block(chainHeader, blockchainStorage.getBlockBody(chainHeader.getHash()).get()); + return new Block( + chainHeader, + getBlockBody(chainHeader.getHash()) + .orElseGet(() -> getBlockBodySafe(chainHeader.getHash()).get())); } @Override @@ -337,6 +340,11 @@ public Optional getBlockBody(final Hash blockHeaderHash) { .orElseGet(() -> blockchainStorage.getBlockBody(blockHeaderHash)); } + @Override + public synchronized Optional getBlockBodySafe(final Hash blockHeaderHash) { + return getBlockBody(blockHeaderHash); + } + @Override public Optional> getTxReceipts(final Hash blockHeaderHash) { return transactionReceiptsCache diff --git a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/worldstate/DataStorageConfiguration.java b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/worldstate/DataStorageConfiguration.java index 8d767f442aa0..320e38733d44 100644 --- a/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/worldstate/DataStorageConfiguration.java +++ b/ethereum/core/src/main/java/org/hyperledger/besu/ethereum/worldstate/DataStorageConfiguration.java @@ -26,7 +26,7 @@ public interface DataStorageConfiguration { boolean DEFAULT_BONSAI_LIMIT_TRIE_LOGS_ENABLED = true; long MINIMUM_BONSAI_TRIE_LOG_RETENTION_LIMIT = DEFAULT_BONSAI_MAX_LAYERS_TO_LOAD; int DEFAULT_BONSAI_TRIE_LOG_PRUNING_WINDOW_SIZE = 5_000; - boolean DEFAULT_RECEIPT_COMPACTION_ENABLED = false; + boolean DEFAULT_RECEIPT_COMPACTION_ENABLED = true; DataStorageConfiguration DEFAULT_CONFIG = ImmutableDataStorageConfiguration.builder() diff --git a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/BlockchainTestSubCommand.java b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/BlockchainTestSubCommand.java index 5b9bc2cdfe01..bec68a3cc398 100644 --- a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/BlockchainTestSubCommand.java +++ b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/BlockchainTestSubCommand.java @@ -44,12 +44,10 @@ import java.util.ArrayList; import java.util.List; import java.util.Map; -import java.util.function.Supplier; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; -import com.google.common.base.Suppliers; import org.apache.tuweni.bytes.Bytes32; import picocli.CommandLine.Command; import picocli.CommandLine.Option; @@ -81,9 +79,6 @@ public class BlockchainTestSubCommand implements Runnable { */ public static final String COMMAND_NAME = "block-test"; - static final Supplier referenceTestProtocolSchedules = - Suppliers.memoize(ReferenceTestProtocolSchedules::create); - @Option( names = {"--test-name"}, description = "Limit execution to one named test.") @@ -177,7 +172,7 @@ private void traceTestSpecs(final String test, final BlockchainReferenceTestCase .orElseThrow(); final ProtocolSchedule schedule = - referenceTestProtocolSchedules.get().getByName(spec.getNetwork()); + ReferenceTestProtocolSchedules.getInstance().getByName(spec.getNetwork()); final MutableBlockchain blockchain = spec.getBlockchain(); final ProtocolContext context = spec.getProtocolContext(); diff --git a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/CodeValidateSubCommand.java b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/CodeValidateSubCommand.java index 6c8b9d5ad3f0..a3fff8e5dc3c 100644 --- a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/CodeValidateSubCommand.java +++ b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/CodeValidateSubCommand.java @@ -36,8 +36,6 @@ import java.util.ArrayList; import java.util.List; import java.util.function.Supplier; -import java.util.stream.Collectors; -import java.util.stream.IntStream; import com.google.common.base.Suppliers; import org.apache.tuweni.bytes.Bytes; @@ -94,7 +92,7 @@ public CodeValidateSubCommand() { Suppliers.memoize( () -> { ProtocolSpec protocolSpec = - ReferenceTestProtocolSchedules.create().geSpecByName(fork); + ReferenceTestProtocolSchedules.getInstance().geSpecByName(fork); return protocolSpec.getEvm(); }); } @@ -175,12 +173,8 @@ public String considerCode(final String hexCode) { ((CodeV1) code).getEofLayout().containerMode().get())) { return "err: code is valid initcode. Runtime code expected"; } else { - return "OK " - + IntStream.range(0, code.getCodeSectionCount()) - .mapToObj(code::getCodeSection) - .map(cs -> code.getBytes().slice(cs.getEntryPoint(), cs.getLength())) - .map(Bytes::toUnprefixedHexString) - .collect(Collectors.joining(",")); + return "OK %d/%d/%d" + .formatted(code.getCodeSectionCount(), code.getSubcontainerCount(), code.getDataSize()); } } } diff --git a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/EOFTestSubCommand.java b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/EOFTestSubCommand.java index bfa873e61cf3..94f8b2cd4925 100644 --- a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/EOFTestSubCommand.java +++ b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/EOFTestSubCommand.java @@ -93,7 +93,7 @@ public void run() { fork = parentCommand.getFork(); } ProtocolSpec protocolSpec = - ReferenceTestProtocolSchedules.create() + ReferenceTestProtocolSchedules.getInstance() .geSpecByName(fork == null ? EvmSpecVersion.PRAGUE.getName() : fork); evm = protocolSpec.getEvm(); diff --git a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/PrettyPrintSubCommand.java b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/PrettyPrintSubCommand.java index 2e1656b13d46..aeff4a96b590 100644 --- a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/PrettyPrintSubCommand.java +++ b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/PrettyPrintSubCommand.java @@ -99,7 +99,7 @@ public void run() { if (parentCommand.hasFork()) { fork = parentCommand.getFork(); } - ProtocolSpec protocolSpec = ReferenceTestProtocolSchedules.create().geSpecByName(fork); + ProtocolSpec protocolSpec = ReferenceTestProtocolSchedules.getInstance().geSpecByName(fork); EVM evm = protocolSpec.getEvm(); EOFLayout layout = evm.parseEOF(container); if (layout.isValid()) { diff --git a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/StateTestSubCommand.java b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/StateTestSubCommand.java index 40f36f18f1c3..f6e05b5a4983 100644 --- a/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/StateTestSubCommand.java +++ b/ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/StateTestSubCommand.java @@ -51,14 +51,12 @@ import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; -import java.util.function.Supplier; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.JavaType; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.base.Stopwatch; -import com.google.common.base.Suppliers; import org.apache.tuweni.bytes.Bytes; import picocli.CommandLine.Command; import picocli.CommandLine.Option; @@ -90,9 +88,6 @@ public class StateTestSubCommand implements Runnable { */ public static final String COMMAND_NAME = "state-test"; - static final Supplier referenceTestProtocolSchedules = - Suppliers.memoize(ReferenceTestProtocolSchedules::create); - @SuppressWarnings({"FieldCanBeFinal"}) @Option( names = {"--fork"}, @@ -258,7 +253,7 @@ private void traceTestSpecs(final String test, final List getBlockBody(final Hash blockHeaderHash) { throw new UnsupportedOperationException(); } + @Override + public synchronized Optional getBlockBodySafe(final Hash blockHeaderHash) { + return getBlockBody(blockHeaderHash); + } + @Override public Optional> getTxReceipts(final Hash blockHeaderHash) { // Deterministic, but just not implemented. diff --git a/ethereum/evmtool/src/test/java/org/hyperledger/besu/evmtool/CodeValidationSubCommandTest.java b/ethereum/evmtool/src/test/java/org/hyperledger/besu/evmtool/CodeValidationSubCommandTest.java index dd7133f862e2..d6b7359413c1 100644 --- a/ethereum/evmtool/src/test/java/org/hyperledger/besu/evmtool/CodeValidationSubCommandTest.java +++ b/ethereum/evmtool/src/test/java/org/hyperledger/besu/evmtool/CodeValidationSubCommandTest.java @@ -47,7 +47,7 @@ void testSingleValidViaInput() { EvmToolCommand parentCommand = new EvmToolCommand(bais, new PrintWriter(baos, true, UTF_8)); final CodeValidateSubCommand codeValidateSubCommand = new CodeValidateSubCommand(parentCommand); codeValidateSubCommand.run(); - assertThat(baos.toString(UTF_8)).contains("OK 00\n"); + assertThat(baos.toString(UTF_8)).contains("OK 1/0/0\n"); } @Test @@ -70,9 +70,9 @@ void testMultipleViaInput() { assertThat(baos.toString(UTF_8)) .contains( """ - OK 00 + OK 1/0/0 err: layout - EOF header byte 1 incorrect - OK 5f5ff3 + OK 1/0/0 """); } @@ -85,7 +85,7 @@ void testSingleValidViaCli() { final CommandLine cmd = new CommandLine(codeValidateSubCommand); cmd.parseArgs(CODE_STOP_ONLY); codeValidateSubCommand.run(); - assertThat(baos.toString(UTF_8)).contains("OK 00\n"); + assertThat(baos.toString(UTF_8)).contains("OK 1/0/0\n"); } @Test @@ -112,9 +112,9 @@ void testMultipleViaCli() { assertThat(baos.toString(UTF_8)) .contains( """ - OK 00 + OK 1/0/0 err: layout - EOF header byte 1 incorrect - OK 5f5ff3 + OK 1/0/0 """); } @@ -127,7 +127,7 @@ void testCliEclipsesInput() { final CommandLine cmd = new CommandLine(codeValidateSubCommand); cmd.parseArgs(CODE_RETURN_ONLY); codeValidateSubCommand.run(); - assertThat(baos.toString(UTF_8)).contains("OK 5f5ff3\n"); + assertThat(baos.toString(UTF_8)).contains("OK 1/0/0\n"); } @Test @@ -139,7 +139,7 @@ void testInteriorCommentsSkipped() { final CommandLine cmd = new CommandLine(codeValidateSubCommand); cmd.parseArgs(CODE_INTERIOR_COMMENTS); codeValidateSubCommand.run(); - assertThat(baos.toString(UTF_8)).contains("OK 59595959e300015000,f8e4\n"); + assertThat(baos.toString(UTF_8)).contains("OK 2/0/0\n"); } @Test @@ -153,9 +153,9 @@ void testBlankLinesAndCommentsSkipped() { assertThat(baos.toString(UTF_8)) .isEqualTo( """ - OK 00 + OK 1/0/0 err: layout - EOF header byte 1 incorrect - OK 5f5ff3 + OK 1/0/0 """); } } diff --git a/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/code-validate/createdata.json b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/code-validate/createdata.json new file mode 100644 index 000000000000..9207cd65e02c --- /dev/null +++ b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/code-validate/createdata.json @@ -0,0 +1,7 @@ +{ + "cli": [ + "code-validate" + ], + "stdin": "0xef0001010004020001000b0300010014040004000080000436600060ff6000ec005000ef000101000402000100010400000000800000feda7ac0de", + "stdout": "OK 1/1/4\n" +} diff --git a/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/code-validate/runtime.json b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/code-validate/runtime.json index 796581555913..fedeaa1bc05b 100644 --- a/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/code-validate/runtime.json +++ b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/code-validate/runtime.json @@ -3,5 +3,5 @@ "code-validate" ], "stdin": "ef00010100040200010001040000000080000000", - "stdout": "OK 00\n" + "stdout": "OK 1/0/0\n" } diff --git a/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/trace/create-eof-error.json b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/trace/create-eof-error.json index 58402eeaa486..cd4c3fa14a1e 100644 --- a/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/trace/create-eof-error.json +++ b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/trace/create-eof-error.json @@ -11,5 +11,5 @@ "CancunEOF" ], "stdin": "", - "stdout": "EOF Code Invalid : STOP is only a valid opcode in containers used for runtime operations.\n" + "stdout": "EOF Code Invalid : incompatible_container_kind opcode STOP is only valid for runtime.\n" } \ No newline at end of file diff --git a/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/trace/eof-section.json b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/trace/eof-section.json index 061d8f0940cf..439c69195a23 100644 --- a/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/trace/eof-section.json +++ b/ethereum/evmtool/src/test/resources/org/hyperledger/besu/evmtool/trace/eof-section.json @@ -12,8 +12,8 @@ "stdin": "", "stdout": [ {"pc":0,"section":0,"op":227,"immediate":"0x0002","gas":"0x2540be400","gasCost":"0x5","memSize":0,"stack":[],"depth":1,"refund":0,"opName":"CALLF"}, - {"pc":0,"section":2,"op":229,"immediate":"0x0002","gas":"0x2540be3fb","gasCost":"0x5","memSize":0,"stack":[],"depth":1,"fdepth":1,"refund":0,"opName":"JUMPF"}, - {"pc":0,"section":1,"op":228,"gas":"0x2540be3f6","gasCost":"0x3","memSize":0,"stack":[],"depth":1,"fdepth":1,"refund":0,"opName":"RETF"}, + {"pc":0,"section":2,"op":229,"immediate":"0x0002","gas":"0x2540be3fb","gasCost":"0x5","memSize":0,"stack":[],"depth":1,"functionDepth":1,"refund":0,"opName":"JUMPF"}, + {"pc":0,"section":1,"op":228,"gas":"0x2540be3f6","gasCost":"0x3","memSize":0,"stack":[],"depth":1,"functionDepth":1,"refund":0,"opName":"RETF"}, {"pc":3,"section":0,"op":97,"immediate":"0x2015","gas":"0x2540be3f3","gasCost":"0x3","memSize":0,"stack":[],"depth":1,"refund":0,"opName":"PUSH2"}, {"pc":6,"section":0,"op":96,"immediate":"0x01","gas":"0x2540be3f0","gasCost":"0x3","memSize":0,"stack":["0x2015"],"depth":1,"refund":0,"opName":"PUSH1"}, {"pc":8,"section":0,"op":85,"gas":"0x2540be3ed","gasCost":"0x5654","memSize":0,"stack":["0x2015","0x1"],"depth":1,"refund":0,"opName":"SSTORE"}, diff --git a/ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/dns/DNSEntry.java b/ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/dns/DNSEntry.java index bb85a3612f31..cd439eea0633 100644 --- a/ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/dns/DNSEntry.java +++ b/ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/dns/DNSEntry.java @@ -243,7 +243,7 @@ class ENRTreeLink implements DNSEntry { public ENRTreeLink(final String enrTreeLink) { final URI uri = URI.create(enrTreeLink); this.domainName = uri.getHost(); - this.encodedPubKey = uri.getUserInfo(); + this.encodedPubKey = uri.getUserInfo() == null ? "" : uri.getUserInfo(); this.pubKey = fromBase32(encodedPubKey); } diff --git a/ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/peers/EnodeURLImpl.java b/ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/peers/EnodeURLImpl.java index e087edd43126..e1d158f3fce6 100644 --- a/ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/peers/EnodeURLImpl.java +++ b/ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/peers/EnodeURLImpl.java @@ -381,11 +381,10 @@ public Builder ipAddress(final String ip) { return ipAddress(ip, EnodeDnsConfiguration.dnsDisabled()); } - public Builder ipAddress( - final String hostField, final EnodeDnsConfiguration enodeDnsConfiguration) { + public Builder ipAddress(final String ip, final EnodeDnsConfiguration enodeDnsConfiguration) { if (enodeDnsConfiguration.dnsEnabled()) { try { - this.ip = InetAddress.getByName(hostField); + this.ip = InetAddress.getByName(ip); if (enodeDnsConfiguration.updateEnabled()) { if (this.ip.isLoopbackAddress()) { this.ip = InetAddress.getLocalHost(); @@ -399,10 +398,10 @@ public Builder ipAddress( this.ip = InetAddresses.forString("127.0.0.1"); } } - } else if (InetAddresses.isUriInetAddress(hostField)) { - this.ip = InetAddresses.forUriString(hostField); - } else if (InetAddresses.isInetAddress(hostField)) { - this.ip = InetAddresses.forString(hostField); + } else if (InetAddresses.isUriInetAddress(ip)) { + this.ip = InetAddresses.forUriString(ip); + } else if (InetAddresses.isInetAddress(ip)) { + this.ip = InetAddresses.forString(ip); } else { throw new IllegalArgumentException("Invalid ip address."); } diff --git a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestBlockchain.java b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestBlockchain.java index 3773c8d1f05b..8f03a01caa7b 100644 --- a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestBlockchain.java +++ b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestBlockchain.java @@ -142,6 +142,11 @@ public Optional getBlockBody(final Hash blockHeaderHash) { throw new UnsupportedOperationException(); } + @Override + public synchronized Optional getBlockBodySafe(final Hash blockHeaderHash) { + return getBlockBody(blockHeaderHash); + } + @Override public Optional> getTxReceipts(final Hash blockHeaderHash) { // Deterministic, but just not implemented. diff --git a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestProtocolSchedules.java b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestProtocolSchedules.java index d6c5afdc4a80..bcdf5e25d5be 100644 --- a/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestProtocolSchedules.java +++ b/ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestProtocolSchedules.java @@ -44,6 +44,15 @@ public class ReferenceTestProtocolSchedules { private static final List SPECS_PRIOR_TO_DELETING_EMPTY_ACCOUNTS = Arrays.asList("Frontier", "Homestead", "EIP150"); + private static ReferenceTestProtocolSchedules instance; + + public static ReferenceTestProtocolSchedules getInstance() { + if (instance == null) { + instance = create(); + } + return instance; + } + public static ReferenceTestProtocolSchedules create() { return create(new StubGenesisConfigOptions()); } diff --git a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/core/TransactionTest.java b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/core/TransactionTest.java index bf17f2f96ec8..9aa04bd0ffe1 100644 --- a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/core/TransactionTest.java +++ b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/core/TransactionTest.java @@ -50,11 +50,8 @@ public class TransactionTest { - private static final ReferenceTestProtocolSchedules REFERENCE_TEST_PROTOCOL_SCHEDULES = - ReferenceTestProtocolSchedules.create(); - private static TransactionValidator transactionValidator(final String name) { - return REFERENCE_TEST_PROTOCOL_SCHEDULES + return ReferenceTestProtocolSchedules.getInstance() .getByName(name) .getByBlockHeader(BlockHeaderBuilder.createDefault().buildBlockHeader()) .getTransactionValidatorFactory() diff --git a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/eof/EOFReferenceTestTools.java b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/eof/EOFReferenceTestTools.java index a15bcb241892..8621b5d08af6 100644 --- a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/eof/EOFReferenceTestTools.java +++ b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/eof/EOFReferenceTestTools.java @@ -113,11 +113,12 @@ public static Collection generateTestParametersForConfig(final String[ @SuppressWarnings("java:S5960") // This is not production code, this is testing code. public static void executeTest( + final String name, final String fork, final Bytes code, final String containerKind, final EOFTestCaseSpec.TestResult expected) { - EVM evm = ReferenceTestProtocolSchedules.create().geSpecByName(fork).getEvm(); + EVM evm = ReferenceTestProtocolSchedules.getInstance().geSpecByName(fork).getEvm(); assertThat(evm).isNotNull(); // hardwire in the magic byte transaction checks @@ -144,26 +145,32 @@ public static void executeTest( .withFailMessage("Code did not parse to valid containerKind of " + expectedMode) .isNotEqualTo(expectedMode); } else { + if (expected.result()) { assertThat(parsedCode.isValid()) .withFailMessage( + () -> "Valid code failed with " + ((CodeInvalid) parsedCode).getInvalidReason()) + .isTrue(); + } else { + assertThat(parsedCode.isValid()) + .withFailMessage("Invalid code expected " + expected.exception() + " but was valid") + .isFalse(); + if (name.contains("eip7692")) { + // if the test is from EEST, validate the exception name. + assertThat(((CodeInvalid) parsedCode).getInvalidReason()) + .withFailMessage( () -> - EOFLayout.parseEOF(code).prettyPrint() - + "\nExpected exception :" - + expected.exception() - + " actual exception :" - + (parsedCode.isValid() + "Expected exception :%s actual exception: %s" + .formatted( + expected.exception(), + (parsedCode.isValid() ? null - : ((CodeInvalid) parsedCode).getInvalidReason())) - .isEqualTo(expected.result()); - - if (expected.result()) { - assertThat(code) - .withFailMessage("Container round trip failed") - .isEqualTo(layout.writeContainer(null)); + : ((CodeInvalid) parsedCode).getInvalidReason()))) + .containsIgnoringCase(expected.exception().replace("EOFException.", "")); + } } } } else { - assertThat(layout.isValid()) + assertThat(false) .withFailMessage( () -> "Expected exception - " 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 00733de1f8ea..cfb56d1ebc1e 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 @@ -60,7 +60,7 @@ public static Stream getTestParametersForConfig() throws IOException "/BasicTests/difficultyMainNetwork.json", MainnetProtocolSchedule.fromConfig( GenesisConfigFile.mainnet() - .getConfigOptions(postMergeOverrides), + .withOverrides(postMergeOverrides).getConfigOptions(), EvmConfiguration.DEFAULT, MiningParameters.newDefault(), new BadBlockManager(), false, new NoOpMetricsSystem())), Arguments.of( "/DifficultyTests/dfGrayGlacier/difficultyGrayGlacierForkBlock.json", diff --git a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/vm/BlockchainReferenceTestTools.java b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/vm/BlockchainReferenceTestTools.java index 1d9ce8eefaa7..aabc6740870f 100644 --- a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/vm/BlockchainReferenceTestTools.java +++ b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/vm/BlockchainReferenceTestTools.java @@ -44,8 +44,6 @@ import org.assertj.core.api.Assertions; public class BlockchainReferenceTestTools { - private static final ReferenceTestProtocolSchedules REFERENCE_TEST_PROTOCOL_SCHEDULES = - ReferenceTestProtocolSchedules.create(); private static final List NETWORKS_TO_RUN; @@ -114,7 +112,7 @@ public static void executeTest(final BlockchainReferenceTestCaseSpec spec) { .orElseThrow(); final ProtocolSchedule schedule = - REFERENCE_TEST_PROTOCOL_SCHEDULES.getByName(spec.getNetwork()); + ReferenceTestProtocolSchedules.getInstance().getByName(spec.getNetwork()); final MutableBlockchain blockchain = spec.getBlockchain(); final ProtocolContext context = spec.getProtocolContext(); diff --git a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/vm/GeneralStateReferenceTestTools.java b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/vm/GeneralStateReferenceTestTools.java index 18d574adc154..354642f1ad74 100644 --- a/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/vm/GeneralStateReferenceTestTools.java +++ b/ethereum/referencetests/src/reference-test/java/org/hyperledger/besu/ethereum/vm/GeneralStateReferenceTestTools.java @@ -44,8 +44,6 @@ import org.hyperledger.besu.testutil.JsonTestParameters; public class GeneralStateReferenceTestTools { - private static final ReferenceTestProtocolSchedules REFERENCE_TEST_PROTOCOL_SCHEDULES = - ReferenceTestProtocolSchedules.create(); private static final List SPECS_PRIOR_TO_DELETING_EMPTY_ACCOUNTS = Arrays.asList("Frontier", "Homestead", "EIP150"); @@ -54,7 +52,7 @@ private static MainnetTransactionProcessor transactionProcessor(final String nam } private static ProtocolSpec protocolSpec(final String name) { - return REFERENCE_TEST_PROTOCOL_SCHEDULES + return ReferenceTestProtocolSchedules.getInstance() .getByName(name) .getByBlockHeader(BlockHeaderBuilder.createDefault().buildBlockHeader()); } @@ -153,11 +151,11 @@ public static void executeTest(final GeneralStateTestCaseEipSpec spec) { .blobGasPricePerGas(blockHeader.getExcessBlobGas().orElse(BlobGas.ZERO)); final TransactionProcessingResult result = processor.processTransaction( - worldStateUpdater, + worldStateUpdater, blockHeader, transaction, blockHeader.getCoinbase(), - new CachingBlockHashLookup(blockHeader, blockchain), + new CachingBlockHashLookup(blockHeader, blockchain), false, TransactionValidationParams.processingBlock(), blobGasPrice); diff --git a/ethereum/referencetests/src/reference-test/templates/EOFReferenceTest.java.template b/ethereum/referencetests/src/reference-test/templates/EOFReferenceTest.java.template index d9e52403d782..a08efec2b6b8 100644 --- a/ethereum/referencetests/src/reference-test/templates/EOFReferenceTest.java.template +++ b/ethereum/referencetests/src/reference-test/templates/EOFReferenceTest.java.template @@ -6,7 +6,6 @@ import static org.junit.jupiter.api.Assumptions.assumeTrue; import org.hyperledger.besu.ethereum.referencetests.EOFTestCaseSpec; -import java.util.Arrays; import java.util.stream.Stream; import org.apache.tuweni.bytes.Bytes; @@ -14,8 +13,6 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; -import static org.junit.jupiter.api.Assumptions.assumeTrue; - /** The general state test operation testing framework entry point. */ public class %%TESTS_NAME%% { @@ -38,6 +35,6 @@ public class %%TESTS_NAME%% { final EOFTestCaseSpec.TestResult results, final boolean runTest) { assumeTrue(runTest, "Test " + name + " was ignored"); - executeTest(fork, code, containerKind, results); + executeTest(name, fork, code, containerKind, results); } } diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestGetLogHash.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestGetLogHash.java index e4fd7bcff27b..398d72d66530 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestGetLogHash.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestGetLogHash.java @@ -18,6 +18,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -45,7 +46,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final Hash txHash; try { txHash = requestContext.getRequiredParameter(0, Hash.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid transaction hash parameter (index 0)", RpcErrorType.INVALID_TRANSACTION_HASH_PARAMS, diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestImportRawBlock.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestImportRawBlock.java index 516dc2f55f19..580b107a8b51 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestImportRawBlock.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestImportRawBlock.java @@ -18,6 +18,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; @@ -56,7 +57,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final String input; try { input = requestContext.getRequiredParameter(0, String.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block parameter (index 0)", RpcErrorType.INVALID_BLOCK_PARAMS, e); } diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java index 7907cee3f78f..80a4872442df 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestMineBlocks.java @@ -18,6 +18,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -49,7 +50,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { long blocksToMine = 0; try { blocksToMine = requestContext.getRequiredParameter(0, Long.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid blocks to mine (index 0)", RpcErrorType.INVALID_BLOCK_COUNT_PARAMS, e); } diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestModifyTimestamp.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestModifyTimestamp.java index d9cfafbaeabb..717cf41b4595 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestModifyTimestamp.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestModifyTimestamp.java @@ -17,6 +17,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -40,7 +41,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final long epochSeconds; try { epochSeconds = requestContext.getRequiredParameter(0, Long.class); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid timestamp parameter (index 0)", RpcErrorType.INVALID_TIMESTAMP_PARAMS, e); } diff --git a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestRewindToBlock.java b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestRewindToBlock.java index d5adb36a243c..d9b847af4256 100644 --- a/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestRewindToBlock.java +++ b/ethereum/retesteth/src/main/java/org/hyperledger/besu/ethereum/retesteth/methods/TestRewindToBlock.java @@ -17,6 +17,7 @@ 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.methods.JsonRpcMethod; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; @@ -41,7 +42,7 @@ public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { final long blockNumber; try { blockNumber = requestContext.getRequiredParameter(0, Long.TYPE); - } catch (Exception e) { // TODO:replace with JsonRpcParameter.JsonRpcParameterException + } catch (JsonRpcParameterException e) { throw new InvalidJsonRpcParameters( "Invalid block number parameter (index 0)", RpcErrorType.INVALID_BLOCK_NUMBER_PARAMS, e); } diff --git a/ethereum/stratum/src/main/java/org/hyperledger/besu/ethereum/stratum/Stratum1Protocol.java b/ethereum/stratum/src/main/java/org/hyperledger/besu/ethereum/stratum/Stratum1Protocol.java index 308d15f6f11e..4311647948dc 100644 --- a/ethereum/stratum/src/main/java/org/hyperledger/besu/ethereum/stratum/Stratum1Protocol.java +++ b/ethereum/stratum/src/main/java/org/hyperledger/besu/ethereum/stratum/Stratum1Protocol.java @@ -18,6 +18,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.RpcMethod; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.JsonRpcRequest; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.exception.InvalidJsonRpcParameters; +import org.hyperledger.besu.ethereum.api.jsonrpc.internal.parameters.JsonRpcParameter.JsonRpcParameterException; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.RpcErrorType; import org.hyperledger.besu.ethereum.blockcreation.MiningCoordinator; @@ -175,18 +176,24 @@ private void handleMiningSubmit(final JsonRpcRequest message, final Consumer maxContainerSize) { - return "EOF container is larger than maximum size of " + maxContainerSize; + return "container_size_above_limit of " + maxContainerSize; } Queue workList = new ArrayDeque<>(layout.getSubcontainerCount()); @@ -90,7 +90,7 @@ public String validate(final EOFLayout layout) { EOFLayout container = workList.poll(); workList.addAll(List.of(container.subContainers())); if (container != layout && container.containerMode().get() == null) { - return "Unreferenced container #" + layout.indexOfSubcontainer(container); + return "orphan_subcontainer #" + layout.indexOfSubcontainer(container); } if (container.containerMode().get() != RUNTIME && container.data().size() != container.dataLength()) { @@ -157,7 +157,7 @@ String validateCode( opcodeInfo = V1_OPCODES[operationNum]; if (!opcodeInfo.valid()) { // undefined instruction - return format("Invalid Instruction 0x%02x", operationNum); + return format("undefined_instruction 0x%02x", operationNum); } pos += 1; int pcPostInstruction = pos; @@ -168,7 +168,7 @@ String validateCode( eofLayout.containerMode().set(RUNTIME); } else if (!eofContainerMode.equals(RUNTIME)) { return format( - "%s is only a valid opcode in containers used for runtime operations.", + "incompatible_container_kind opcode %s is only valid for runtime.", opcodeInfo.name()); } break; @@ -210,54 +210,55 @@ String validateCode( break; case DataLoadNOperation.OPCODE: if (pos + 2 > size) { - return "Truncated DataLoadN offset"; + return "truncated_instruction DATALOADN"; } pcPostInstruction += 2; final int dataLoadOffset = readBigEndianU16(pos, rawCode); // only verfy the last byte of the load is within the minimum data if (dataLoadOffset > eofLayout.dataLength() - 32) { - return "DataLoadN loads data past minimum data length"; + return "invalid_dataloadn_index %d + 32 > %d" + .formatted(dataLoadOffset, eofLayout.dataLength()); } break; case RelativeJumpOperation.OPCODE, RelativeJumpIfOperation.OPCODE: if (pos + 2 > size) { - return "Truncated relative jump offset"; + return "truncated_instruction RJUMP"; } pcPostInstruction += 2; final int offset = readBigEndianI16(pos, rawCode); final int rjumpdest = pcPostInstruction + offset; if (rjumpdest < 0 || rjumpdest >= size) { - return "Relative jump destination out of bounds"; + return "invalid_rjump_destination out of bounds"; } rjumpdests.set(rjumpdest); break; case RelativeJumpVectorOperation.OPCODE: pcPostInstruction += 1; if (pcPostInstruction > size) { - return "Truncated jump table"; + return "truncated_instruction RJUMPV"; } int jumpBasis = pcPostInstruction; final int jumpTableSize = RelativeJumpVectorOperation.getVectorSize(code, pos); pcPostInstruction += 2 * jumpTableSize; if (pcPostInstruction > size) { - return "Truncated jump table"; + return "truncated_instruction RJUMPV"; } for (int offsetPos = jumpBasis; offsetPos < pcPostInstruction; offsetPos += 2) { final int rjumpvOffset = readBigEndianI16(offsetPos, rawCode); final int rjumpvDest = pcPostInstruction + rjumpvOffset; if (rjumpvDest < 0 || rjumpvDest >= size) { - return "Relative jump destination out of bounds"; + return "invalid_rjump_destination out of bounds"; } rjumpdests.set(rjumpvDest); } break; case CallFOperation.OPCODE: if (pos + 2 > size) { - return "Truncated CALLF"; + return "truncated_instruction CALLF"; } int section = readBigEndianU16(pos, rawCode); if (section >= eofLayout.getCodeSectionCount()) { - return "CALLF to non-existent section - " + Integer.toHexString(section); + return "invalid_code_section_index CALLF to " + Integer.toHexString(section); } if (!eofLayout.getCodeSection(section).returning) { return "CALLF to non-returning section - " + Integer.toHexString(section); @@ -269,17 +270,18 @@ String validateCode( break; case JumpFOperation.OPCODE: if (pos + 2 > size) { - return "Truncated JUMPF"; + return "truncated_instruction JUMPF"; } int targetSection = readBigEndianU16(pos, rawCode); if (targetSection >= eofLayout.getCodeSectionCount()) { - return "JUMPF to non-existent section - " + Integer.toHexString(targetSection); + return "invalid_code_section_index JUMPF - " + Integer.toHexString(targetSection); } CodeSection targetCodeSection = eofLayout.getCodeSection(targetSection); - if (targetCodeSection.isReturning() - && thisCodeSection.getOutputs() < targetCodeSection.getOutputs()) { + if (targetCodeSection.isReturning() && !thisCodeSection.isReturning()) { + return "invalid_non_returning_flag non-returning JUMPF source must have non-returning target"; + } else if (thisCodeSection.getOutputs() < targetCodeSection.getOutputs()) { return format( - "JUMPF targeting a returning code section %2x with more outputs %d than current section's outputs %d", + "jumpf_destination_incompatible_outputs target %2x with more outputs %d than current section's outputs %d", targetSection, targetCodeSection.getOutputs(), thisCodeSection.getOutputs()); } hasReturningOpcode |= eofLayout.getCodeSection(targetSection).isReturning(); @@ -288,13 +290,13 @@ String validateCode( case EOFCreateOperation.OPCODE: if (pos + 1 > size) { return format( - "Dangling immediate for %s at pc=%d", + "truncated_instruction dangling immediate for %s at pc=%d", opcodeInfo.name(), pos - opcodeInfo.pcAdvance()); } int subcontainerNum = rawCode[pos] & 0xff; if (subcontainerNum >= eofLayout.getSubcontainerCount()) { return format( - "%s refers to non-existent subcontainer %d at pc=%d", + "invalid_container_section_index %s refers to non-existent subcontainer %d at pc=%d", opcodeInfo.name(), subcontainerNum, pos - opcodeInfo.pcAdvance()); } EOFLayout subContainer = eofLayout.getSubcontainer(subcontainerNum); @@ -303,7 +305,7 @@ String validateCode( subContainer.containerMode().set(INITCODE); } else if (subcontainerMode == RUNTIME) { return format( - "subcontainer %d cannot be used both as initcode and runtime", subcontainerNum); + "incompatible_container_kind subcontainer %d should be initcode", subcontainerNum); } if (subContainer.dataLength() != subContainer.data().size()) { return format( @@ -320,17 +322,18 @@ String validateCode( eofLayout.containerMode().set(INITCODE); } else if (!eofContainerMode.equals(INITCODE)) { return format( - "%s is only a valid opcode in containers used for initcode", opcodeInfo.name()); + "incompatible_container_kind opcode %s is only valid for initcode", + opcodeInfo.name()); } if (pos + 1 > size) { return format( - "Dangling immediate for %s at pc=%d", + "truncated_instruction dangling immediate for %s at pc=%d", opcodeInfo.name(), pos - opcodeInfo.pcAdvance()); } int returnedContractNum = rawCode[pos] & 0xff; if (returnedContractNum >= eofLayout.getSubcontainerCount()) { return format( - "%s refers to non-existent subcontainer %d at pc=%d", + "invalid_container_section_index %s refers to non-existent subcontainer %d at pc=%d", opcodeInfo.name(), returnedContractNum, pos - opcodeInfo.pcAdvance()); } EOFLayout returnedContract = eofLayout.getSubcontainer(returnedContractNum); @@ -339,7 +342,8 @@ String validateCode( returnedContract.containerMode().set(RUNTIME); } else if (returnedContractMode.equals(INITCODE)) { return format( - "subcontainer %d cannot be used both as initcode and runtime", returnedContractNum); + "incompatible_container_kind subcontainer %d should be runtime", + returnedContractNum); } pcPostInstruction += 1; break; @@ -347,9 +351,9 @@ String validateCode( // a few opcodes have potentially dangling immediates if (opcodeInfo.pcAdvance() > 1) { pcPostInstruction += opcodeInfo.pcAdvance() - 1; - if (pcPostInstruction >= size) { + if (pcPostInstruction > size) { return format( - "Dangling immediate for %s at pc=%d", + "truncated_instruction dangling immediate for %s at pc=%d", opcodeInfo.name(), pos - opcodeInfo.pcAdvance()); } } @@ -360,14 +364,14 @@ String validateCode( } if (thisCodeSection.isReturning() != hasReturningOpcode) { return thisCodeSection.isReturning() - ? "No RETF or qualifying JUMPF" - : "Non-returing section has RETF or JUMPF into returning section"; + ? "unreachable_code_sections no RETF or qualifying JUMPF" + : "invalid_non_returning_flag RETF or JUMPF into returning section"; } if (!opcodeInfo.terminal()) { - return "No terminating instruction"; + return "missing_stop_opcode No terminating instruction"; } if (rjumpdests.intersects(immediates)) { - return "Relative jump destinations targets invalid immediate data"; + return "invalid_rjump_destination targets immediate data"; } return null; } @@ -472,7 +476,7 @@ String validateStack( int nextPC; if (!opcodeInfo.valid()) { - return format("Invalid Instruction 0x%02x", thisOp); + return format("undefined_instruction 0x%02x", thisOp); } nextPC = currentPC + pcAdvance; @@ -483,7 +487,7 @@ String validateStack( } if (stack_max[currentPC] < 0) { return format( - "Code that was not forward referenced in section 0x%x pc %d", + "unreachable_instructions section 0x%x pc %d was not forward referenced", codeSectionToValidate, currentPC); } currentMin = min(stack_min[currentPC], currentMin); @@ -491,7 +495,7 @@ String validateStack( if (stackInputs > currentMin) { return format( - "Operation 0x%02X requires stack of %d but may only have %d items", + "stack_underflow operation 0x%02X wants stack of %d but may only have %d", thisOp, stackInputs, currentMin); } @@ -515,13 +519,13 @@ String validateStack( } else { if (stack_min[targetPC] != currentMin) { return format( - "Stack minimum violation on backwards jump from %d to %d, %d != %d", - currentPC, targetPC, stack_min[currentPC], currentMax); + "stack_height_mismatch backwards RJUMP from %d to %d, min %d != %d", + currentPC, targetPC, stack_min[targetPC], currentMin); } if (stack_max[targetPC] != currentMax) { return format( - "Stack maximum violation on backwards jump from %d to %d, %d != %d", - currentPC, targetPC, stack_max[currentPC], currentMax); + "stack_height_mismatch backwards RJUMP from %d to %d, max %d != %d", + currentPC, targetPC, stack_max[targetPC], currentMax); } } @@ -542,13 +546,13 @@ String validateStack( } else { if (stack_min[targetPCi] != currentMin) { return format( - "Stack minimum violation on backwards jump from %d to %d, %d != %d", - currentPC, targetPCi, stack_min[currentPC], currentMin); + "stack_height_mismatch backwards RJUMPI from %d to %d, min %d != %d", + currentPC, targetPCi, stack_min[targetPCi], currentMin); } if (stack_max[targetPCi] != currentMax) { return format( - "Stack maximum violation on backwards jump from %d to %d, %d != %d", - currentPC, targetPCi, stack_max[currentPC], currentMax); + "stack_height_mismatch backwards RJUMPI from %d to %d, max %d != %d", + currentPC, targetPCi, stack_max[targetPCi], currentMax); } } break; @@ -568,13 +572,13 @@ String validateStack( } else { if (stack_min[targetPCv] != currentMin) { return format( - "Stack minimum violation on backwards jump from %d to %d, %d != %d", - currentPC, targetPCv, stack_min[currentPC], currentMin); + "stack_height_mismatch backwards RJUMPV from %d to %d, min %d != %d", + currentPC, targetPCv, stack_min[targetPCv], currentMin); } if (stack_max[targetPCv] != currentMax) { return format( - "Stack maximum violation on backwards jump from %d to %d, %d != %d", - currentPC, targetPCv, stack_max[currentPC], currentMax); + "stack_height_mismatch backwards RJUMPV from %d to %d, max %d != %d", + currentPC, targetPCv, stack_max[targetPCv], currentMax); } } } @@ -589,7 +593,7 @@ String validateStack( if (stack_min[currentPC] != returnStackItems || stack_min[currentPC] != stack_max[currentPC]) { return format( - "RETF in section %d calculated height %d does not match configured return stack %d, min height %d, and max height %d", + "stack_higher_than_outputs RETF in section %d calculated height %d does not match configured return stack %d, min height %d, and max height %d", codeSectionToValidate, currentMin, returnStackItems, @@ -620,9 +624,11 @@ String validateStack( "JUMPF at section %d pc %d has a variable stack height %d/%d", codeSectionToValidate, currentPC, currentMin, currentMax); } - if (currentMax != toValidate.outputs + targetCs.inputs - targetCs.outputs) { + int expectedMax = toValidate.outputs + targetCs.inputs - targetCs.outputs; + if (currentMax != expectedMax) { return format( - "JUMPF at section %d pc %d has incompatible stack height for returning section %d (%d != %d + %d - %d)", + "%s JUMPF at section %d pc %d has incompatible stack height for returning section %d (%d != %d + %d - %d)", + currentMax < expectedMax ? "stack_underflow" : "stack_higher_than_outputs", codeSectionToValidate, currentPC, jumpFTargetSectionNum, @@ -634,7 +640,7 @@ String validateStack( } else { if (currentMin < targetCs.getInputs()) { return format( - "JUMPF at section %d pc %d has insufficient minimum stack height for non returning section %d (%d != %d)", + "stack_underflow JUMPF at section %d pc %d has insufficient minimum stack height for non returning section %d (%d != %d)", codeSectionToValidate, currentPC, jumpFTargetSectionNum, @@ -669,7 +675,7 @@ String validateStack( if (maxStackHeight != toValidate.maxStackHeight) { return format( - "Calculated max stack height (%d) does not match reported stack height (%d)", + "invalid_max_stack_height Calculated (%d) != reported (%d)", maxStackHeight, toValidate.maxStackHeight); } if (unusedBytes != 0) { diff --git a/evm/src/main/java/org/hyperledger/besu/evm/code/EOFLayout.java b/evm/src/main/java/org/hyperledger/besu/evm/code/EOFLayout.java index 39723f7fd373..d5abb05f8685 100644 --- a/evm/src/main/java/org/hyperledger/besu/evm/code/EOFLayout.java +++ b/evm/src/main/java/org/hyperledger/besu/evm/code/EOFLayout.java @@ -766,7 +766,7 @@ public void prettyPrint( out.print(" "); } out.printf("%02x", byteCode[pc]); - for (int j = 1; j < advance; j++) { + for (int j = 1; j < advance && (pc + j) < byteCode.length; j++) { out.printf("%02x", byteCode[pc + j]); } out.printf(" # [%d] %s", pc, ci.name()); @@ -774,9 +774,12 @@ public void prettyPrint( out.printf("(%d)", byteCode[pc + 1] & 0xff); } else if (advance > 2) { out.print("(0x"); - for (int j = 1; j < advance; j++) { + for (int j = 1; j < advance && (pc + j) < byteCode.length; j++) { out.printf("%02x", byteCode[pc + j]); } + if ((pc + advance) >= byteCode.length) { + out.print(" "); + } out.print(")"); } out.printf("%n"); diff --git a/evm/src/main/java/org/hyperledger/besu/evm/tracing/StandardJsonTracer.java b/evm/src/main/java/org/hyperledger/besu/evm/tracing/StandardJsonTracer.java index 2a71fb70cd1a..a289c665d2dd 100644 --- a/evm/src/main/java/org/hyperledger/besu/evm/tracing/StandardJsonTracer.java +++ b/evm/src/main/java/org/hyperledger/besu/evm/tracing/StandardJsonTracer.java @@ -216,7 +216,7 @@ public void tracePostExecution( } sb.append("\"depth\":").append(depth).append(","); if (subdepth >= 1) { - sb.append("\"fdepth\":").append(subdepth).append(","); + sb.append("\"functionDepth\":").append(subdepth).append(","); } sb.append("\"refund\":").append(messageFrame.getGasRefund()).append(","); sb.append("\"opName\":\"").append(currentOp.getName()).append("\""); diff --git a/evm/src/test/java/org/hyperledger/besu/evm/code/CodeFactoryTest.java b/evm/src/test/java/org/hyperledger/besu/evm/code/CodeFactoryTest.java index e1f1e767d211..6f60ab7865b6 100644 --- a/evm/src/test/java/org/hyperledger/besu/evm/code/CodeFactoryTest.java +++ b/evm/src/test/java/org/hyperledger/besu/evm/code/CodeFactoryTest.java @@ -478,7 +478,7 @@ void invalidComboEOFCreateStop() { # Subcontainer 0 ends # Data section (empty) """, - "STOP is only a valid opcode in containers used for runtime operations."); + "incompatible_container_kind"); } @Test @@ -527,7 +527,7 @@ void invalidComboEOFCretateReturn() { # Subcontainer 0 ends # Data section (empty) """, - "RETURN is only a valid opcode in containers used for runtime operations."); + "incompatible_container_kind"); } @Test @@ -590,7 +590,7 @@ void invalidReturncontractReturncontract() { # Subcontainer 0 ends # Data section (empty) """, - "RETURNCONTRACT is only a valid opcode in containers used for initcode"); + "incompatible_container_kind"); } private static void validCode(final String str) { diff --git a/evm/src/test/java/org/hyperledger/besu/evm/code/CodeV1Test.java b/evm/src/test/java/org/hyperledger/besu/evm/code/CodeV1Test.java index 08cbbedf75cd..9b7edf80b405 100644 --- a/evm/src/test/java/org/hyperledger/besu/evm/code/CodeV1Test.java +++ b/evm/src/test/java/org/hyperledger/besu/evm/code/CodeV1Test.java @@ -192,7 +192,7 @@ private static Stream rjumptableValidImmediateArguments() { @ParameterizedTest @MethodSource("invalidCodeArguments") void testInvalidCode(final String code) { - assertValidation("Invalid Instruction 0x", code); + assertValidation("undefined_instruction", code); } private static Stream invalidCodeArguments() { @@ -214,7 +214,7 @@ private static Stream invalidCodeArguments() { @ParameterizedTest @MethodSource("pushTruncatedImmediateArguments") void testPushTruncatedImmediate(final String code) { - assertValidation("No terminating instruction", code); + assertValidation("missing_stop_opcode", code); } private static Stream pushTruncatedImmediateArguments() { @@ -228,13 +228,13 @@ private static Stream pushTruncatedImmediateArguments() { @ParameterizedTest @ValueSource(strings = {"e0", "e000"}) void testRjumpTruncatedImmediate(final String code) { - assertValidation("Truncated relative jump offset", code); + assertValidation("truncated_instruction", code); } @ParameterizedTest @ValueSource(strings = {"6001e1", "6001e100"}) void testRjumpiTruncatedImmediate(final String code) { - assertValidation("Truncated relative jump offset", code); + assertValidation("truncated_instruction", code); } @ParameterizedTest @@ -248,7 +248,7 @@ void testRjumpiTruncatedImmediate(final String code) { "6001e2030000000100" }) void testRjumpvTruncatedImmediate(final String code) { - assertValidation("Truncated jump table", code); + assertValidation("truncated_instruction", code); } @ParameterizedTest @@ -264,7 +264,7 @@ void testRjumpvTruncatedImmediate(final String code) { "6001e200fff900" }) void testRjumpsOutOfBounds(final String code) { - assertValidation("Relative jump destination out of bounds", code); + assertValidation("invalid_rjump_destination", code); } @ParameterizedTest @@ -317,7 +317,7 @@ void testRjumpsOutOfBounds(final String code) { "6001e2000005e2010000000000" }) void testRjumpsIntoImmediate(final String code) { - assertValidation("Relative jump destinations targets invalid immediate data", code); + assertValidation("invalid_rjump_destination", code); } private static Stream rjumpsIntoImmediateExtraArguments() { @@ -357,25 +357,25 @@ private static Stream rjumpsIntoImmediateExtraArguments() { @ParameterizedTest @ValueSource(strings = {"e3", "e300"}) void testCallFTruncated(final String code) { - assertValidation("Truncated CALLF", code); + assertValidation("truncated_instruction", code); } @ParameterizedTest @ValueSource(strings = {"e5", "e500"}) void testJumpCallFTruncated(final String code) { - assertValidation("Truncated JUMPF", code); + assertValidation("truncated_instruction", code); } @ParameterizedTest @ValueSource(strings = {"e30004", "e303ff", "e3ffff"}) void testCallFWrongSection(final String code) { - assertValidation("CALLF to non-existent section -", code, false, 3); + assertValidation("invalid_code_section_index", code, false, 3); } @ParameterizedTest @ValueSource(strings = {"e50004", "e503ff", "e5ffff"}) void testJumpFWrongSection(final String code) { - assertValidation("JUMPF to non-existent section -", code, false, 3); + assertValidation("invalid_code_section_index", code, false, 3); } @ParameterizedTest @@ -476,8 +476,13 @@ void validateStackAnalysis( EOFLayout eofLayout = EOFLayout.parseEOF(Bytes.fromHexString(sb)); CodeV1Validation validator = new CodeV1Validation(0xc000); - assertThat(validator.validateStack(sectionToTest, eofLayout, new WorkList(sectionCount))) - .isEqualTo(expectedError); + String validation = + validator.validateStack(sectionToTest, eofLayout, new WorkList(sectionCount)); + if (expectedError != null) { + assertThat(validation).contains(expectedError); + } else { + assertThat(validation).isNull(); + } } /** @@ -517,13 +522,10 @@ static Stream stackImmediateBytes() { static Stream stackUnderflow() { return Stream.of( Arguments.of( - "Stack underflow", - "Operation 0x50 requires stack of 1 but may only have 0 items", - 0, - List.of(List.of("50 00", 0, 0x80, 1))), + "Stack underflow", "stack_underflow", 0, List.of(List.of("50 00", 0, 0x80, 1))), Arguments.of( "double rjumpi", - "Operation 0xF3 requires stack of 2 but may only have 1 items", + "stack_underflow", 0, List.of(List.of("5f 5f e10005 5f 5f e10000 f3", 0, 0x80, 1)))); } @@ -533,17 +535,17 @@ static Stream stackRJumpForward() { Arguments.of("RJUMP 0", null, 0, List.of(List.of("e00000 00", 0, 0x80, 0))), Arguments.of( "RJUMP 1 w/ dead code", - "Code that was not forward referenced in section 0x0 pc 3", + "unreachable_instructions", 0, List.of(List.of("e00001 43 00", 0, 0x80, 0))), Arguments.of( "RJUMP 2 w/ dead code", - "Code that was not forward referenced in section 0x0 pc 3", + "unreachable_instructions", 0, List.of(List.of("e00002 43 50 00", 0, 0x80, 0))), Arguments.of( "RJUMP 3 and -10", - "Code that was not forward referenced in section 0x0 pc 3", + "unreachable_instructions", 0, List.of(List.of("e00003 01 50 00 6001 6001 e0fff6", 0, 0x80, 2)))); } @@ -554,12 +556,12 @@ static Stream stackRJumpBackward() { Arguments.of("RJUMP -4", null, 0, List.of(List.of("5B e0fffc", 0, 0x80, 0))), Arguments.of( "RJUMP -4 unmatched stack", - "Stack minimum violation on backwards jump from 1 to 0, 1 != 1", + "stack_height_mismatch", 0, List.of(List.of("43 e0fffc", 0, 0x80, 0))), Arguments.of( "RJUMP -4 unmatched stack", - "Stack minimum violation on backwards jump from 2 to 1, 0 != 0", + "stack_height_mismatch", 0, List.of(List.of("43 50 e0fffc 00", 0, 0x80, 0))), Arguments.of( @@ -570,7 +572,7 @@ static Stream stackRJumpBackward() { "RJUMP -5 matched stack", null, 0, List.of(List.of("43 50 43 e0fffb", 0, 0x80, 1))), Arguments.of( "RJUMP -4 unmatched stack", - "Stack minimum violation on backwards jump from 3 to 2, 1 != 1", + "stack_height_mismatch", 0, List.of(List.of("43 50 43 e0fffc 50 00", 0, 0x80, 0)))); } @@ -611,17 +613,17 @@ static Stream stackRJumpI() { List.of(List.of("6001 e10003 30 50 00 30 30 30 50 50 50 00", 0, 0x80, 3))), Arguments.of( "RJUMPI Missing stack argument", - "Operation 0xE1 requires stack of 1 but may only have 0 items", + "stack_underflow", 0, List.of(List.of("e10000 00", 0, 0x80, 0))), Arguments.of( "Stack underflow one branch", - "Operation 0x02 requires stack of 2 but may only have 1 items", + "stack_underflow", 0, List.of(List.of("60ff 6001 e10002 50 00 02 50 00", 0, 0x80, 0))), Arguments.of( "Stack underflow another branch", - "Operation 0x02 requires stack of 2 but may only have 1 items", + "stack_underflow", 0, List.of(List.of("60ff 6001 e10002 02 00 19 50 00", 0, 0x80, 0))), // this depends on requiring stacks to be "clean" returns @@ -722,22 +724,22 @@ static Stream stackCallF() { List.of("e4", 2, 2, 2))), Arguments.of( "underflow", - "Operation 0xE3 requires stack of 1 but may only have 0 items", + "stack_underflow", 0, List.of(List.of("e30001 00", 0, 0x80, 0), List.of("e4", 1, 0, 0))), Arguments.of( "underflow 2", - "Operation 0xE3 requires stack of 2 but may only have 1 items", + "stack_underflow", 0, List.of(List.of("30 e30001 00", 0, 0x80, 0), List.of("e4", 2, 0, 2))), Arguments.of( "underflow 3", - "Operation 0xE3 requires stack of 1 but may only have 0 items", + "stack_underflow", 1, List.of(List.of("00", 0, 0x80, 0), List.of("50 e30001 e4", 1, 0, 1))), Arguments.of( "underflow 4", - "Operation 0xE3 requires stack of 3 but may only have 2 items", + "stack_underflow", 0, List.of( List.of("44 e30001 80 e30002 00", 0, 0x80, 0), @@ -816,32 +818,32 @@ static Stream stackUnreachable() { return Stream.of( Arguments.of( "Max stack not changed by unreachable code", - "Code that was not forward referenced in section 0x0 pc 3", + "unreachable_instructions", 0, List.of(List.of("30 50 00 30 30 30 50 50 50 00", 0, 0x80, 1))), Arguments.of( "Max stack not changed by unreachable code RETf", - "Code that was not forward referenced in section 0x0 pc 3", + "unreachable_instructions", 0, List.of(List.of("30 50 e4 30 30 30 50 50 50 00", 0, 0x80, 1))), Arguments.of( "Max stack not changed by unreachable code RJUMP", - "Code that was not forward referenced in section 0x0 pc 5", + "unreachable_instructions", 0, List.of(List.of("30 50 e00006 30 30 30 50 50 50 00", 0, 0x80, 1))), Arguments.of( "Stack underflow in unreachable code", - "Code that was not forward referenced in section 0x0 pc 3", + "unreachable_instructions", 0, List.of(List.of("30 50 00 50 00", 0, 0x80, 1))), Arguments.of( "Stack underflow in unreachable code RETF", - "Code that was not forward referenced in section 0x0 pc 3", + "unreachable_instructions", 0, List.of(List.of("30 50 e4 50 00", 0, 0x80, 1))), Arguments.of( "Stack underflow in unreachable code RJUMP", - "Code that was not forward referenced in section 0x0 pc 5", + "unreachable_instructions", 0, List.of(List.of("30 50 e00001 50 00", 0, 0x80, 1)))); } @@ -850,12 +852,12 @@ static Stream stackHeight() { return Stream.of( Arguments.of( "Stack height mismatch backwards", - "Stack minimum violation on backwards jump from 1 to 0, 1 != 1", + "stack_height_mismatch", 0, List.of(List.of("30 e0fffc00", 0, 0x80, 1))), Arguments.of( "Stack height mismatch forwards", - "Calculated max stack height (5) does not match reported stack height (2)", + "invalid_max_stack_height", 0, List.of(List.of("30e10003303030303000", 0, 0x80, 2)))); } @@ -867,7 +869,7 @@ static Stream invalidInstructions() { opcode -> Arguments.of( String.format("Invalid opcode %02x", opcode), - String.format("Invalid Instruction 0x%02x", opcode), + "undefined_instruction", 0, List.of(List.of(String.format("0x%02x", opcode), 0, 0x80, 0)))); } diff --git a/gradle/verification-metadata.xml b/gradle/verification-metadata.xml index 46029c87c876..49c1e7f00c4d 100644 --- a/gradle/verification-metadata.xml +++ b/gradle/verification-metadata.xml @@ -546,6 +546,19 @@ + + + + + + + + + + + + + @@ -5372,6 +5385,14 @@ + + + + + + + + diff --git a/gradle/versions.gradle b/gradle/versions.gradle index 57f2acae37d0..e0baf3bb46f6 100644 --- a/gradle/versions.gradle +++ b/gradle/versions.gradle @@ -41,6 +41,8 @@ dependencyManagement { dependency 'org.hyperledger.besu:besu-errorprone-checks:1.0.0' + dependency 'com.gitlab.javafuzz:core:1.26' + dependency 'com.google.guava:guava:33.0.0-jre' dependency 'com.graphql-java:graphql-java:21.5' @@ -153,8 +155,6 @@ dependencyManagement { } dependency 'org.fusesource.jansi:jansi:2.4.1' - dependency 'org.openjdk.jol:jol-core:0.17' - dependency 'tech.pegasys:jc-kzg-4844:1.0.0' dependencySet(group: 'org.hyperledger.besu', version: '0.9.4') { entry 'arithmetic' @@ -173,6 +173,9 @@ dependencyManagement { dependency 'org.java-websocket:Java-WebSocket:1.5.5' + dependency 'org.jacoco:org.jacoco.agent:0.8.11' + dependency 'org.jacoco:org.jacoco.core:0.8.11' + dependency 'org.jetbrains.kotlin:kotlin-stdlib:1.9.22' dependencySet(group: 'org.junit.jupiter', version: '5.10.1') { @@ -182,6 +185,8 @@ dependencyManagement { entry 'junit-jupiter-params' } + dependency 'org.openjdk.jol:jol-core:0.17' + dependency 'org.junit.platform:junit-platform-runner:1.9.2' dependency 'org.junit.vintage:junit-vintage-engine:5.10.1' @@ -232,6 +237,8 @@ dependencyManagement { dependency 'org.apache.maven:maven-artifact:3.9.6' + dependency 'tech.pegasys:jc-kzg-4844:1.0.0' + dependency 'tech.pegasys.discovery:discovery:22.12.0' } } diff --git a/plugin-api/build.gradle b/plugin-api/build.gradle index 4440a4f0691c..af8da71a7f1f 100644 --- a/plugin-api/build.gradle +++ b/plugin-api/build.gradle @@ -70,7 +70,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 = '6Hy3eaCpnxehyDO3smSAr1i2DsB2q/V37/m8POycikI=' + knownHash = '2tFIKwEd8T5I37ywbFnVcMwTR8HiiCC6gO1Chd3hZp8=' } check.dependsOn('checkAPIChanges') diff --git a/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/txselection/TransactionEvaluationContext.java b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/txselection/TransactionEvaluationContext.java index 93eae92dc7b8..8938ef881b45 100644 --- a/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/txselection/TransactionEvaluationContext.java +++ b/plugin-api/src/main/java/org/hyperledger/besu/plugin/services/txselection/TransactionEvaluationContext.java @@ -16,6 +16,7 @@ import org.hyperledger.besu.datatypes.PendingTransaction; import org.hyperledger.besu.datatypes.Wei; +import org.hyperledger.besu.plugin.data.ProcessableBlockHeader; import com.google.common.base.Stopwatch; @@ -27,6 +28,13 @@ */ public interface TransactionEvaluationContext { + /** + * Gets the pending block header + * + * @return the pending block header + */ + ProcessableBlockHeader getPendingBlockHeader(); + /** * Gets the pending transaction. * diff --git a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValuePrivacyStorageFactory.java b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValuePrivacyStorageFactory.java index 909a2c5e90e6..6debcc046e52 100644 --- a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValuePrivacyStorageFactory.java +++ b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValuePrivacyStorageFactory.java @@ -45,9 +45,7 @@ public class RocksDBKeyValuePrivacyStorageFactory implements PrivacyKeyValueStor LoggerFactory.getLogger(RocksDBKeyValuePrivacyStorageFactory.class); private static final Set SUPPORTED_VERSIONS = EnumSet.of( - PrivacyVersionedStorageFormat.FOREST_WITH_VARIABLES, PrivacyVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION, - PrivacyVersionedStorageFormat.BONSAI_WITH_VARIABLES, PrivacyVersionedStorageFormat.BONSAI_WITH_RECEIPT_COMPACTION); private static final String PRIVATE_DATABASE_PATH = "private"; private final RocksDBKeyValueStorageFactory publicFactory; @@ -230,8 +228,12 @@ private Optional handleVersionUpgrade( // reflect the change to the runtime version, and return it. // Besu supports both formats of receipts so no upgrade is needed other than updating metadata - if (runtimeVersion == PrivacyVersionedStorageFormat.BONSAI_WITH_RECEIPT_COMPACTION - || runtimeVersion == PrivacyVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION) { + final VersionedStorageFormat existingVersionedStorageFormat = + existingPrivacyMetadata.getVersionedStorageFormat(); + if ((existingVersionedStorageFormat == PrivacyVersionedStorageFormat.BONSAI_WITH_VARIABLES + && runtimeVersion == PrivacyVersionedStorageFormat.BONSAI_WITH_RECEIPT_COMPACTION) + || (existingVersionedStorageFormat == PrivacyVersionedStorageFormat.FOREST_WITH_VARIABLES + && runtimeVersion == PrivacyVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION)) { final DatabaseMetadata metadata = new DatabaseMetadata(runtimeVersion); try { metadata.writeToDirectory(dataDir); @@ -247,8 +249,8 @@ private Optional handleVersionUpgrade( "Database unsafe upgrade detect: DB at %s is %s with version %s but version %s is expected. " + "Please check your config and review release notes for supported upgrade procedures.", dataDir, - existingPrivacyMetadata.getVersionedStorageFormat().getFormat().name(), - existingPrivacyMetadata.getVersionedStorageFormat().getVersion(), + existingVersionedStorageFormat.getFormat().name(), + existingVersionedStorageFormat.getVersion(), runtimeVersion.getVersion()); throw new StorageException(error); diff --git a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValueStorageFactory.java b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValueStorageFactory.java index 8e1a4fa52135..d53c9e57fde3 100644 --- a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValueStorageFactory.java +++ b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValueStorageFactory.java @@ -57,11 +57,7 @@ public class RocksDBKeyValueStorageFactory implements KeyValueStorageFactory { private static final Logger LOG = LoggerFactory.getLogger(RocksDBKeyValueStorageFactory.class); private static final EnumSet SUPPORTED_VERSIONED_FORMATS = - EnumSet.of( - FOREST_WITH_VARIABLES, - FOREST_WITH_RECEIPT_COMPACTION, - BONSAI_WITH_VARIABLES, - BONSAI_WITH_RECEIPT_COMPACTION); + EnumSet.of(FOREST_WITH_RECEIPT_COMPACTION, BONSAI_WITH_RECEIPT_COMPACTION); private static final String NAME = "rocksdb"; private final RocksDBMetricsFactory rocksDBMetricsFactory; private DatabaseMetadata databaseMetadata; @@ -329,8 +325,12 @@ private Optional handleVersionUpgrade( // reflect the change to the runtime version, and return it. // Besu supports both formats of receipts so no upgrade is needed other than updating metadata - if (runtimeVersion == BONSAI_WITH_RECEIPT_COMPACTION - || runtimeVersion == FOREST_WITH_RECEIPT_COMPACTION) { + final VersionedStorageFormat existingVersionedStorageFormat = + existingMetadata.getVersionedStorageFormat(); + if ((existingVersionedStorageFormat == BONSAI_WITH_VARIABLES + && runtimeVersion == BONSAI_WITH_RECEIPT_COMPACTION) + || (existingVersionedStorageFormat == FOREST_WITH_VARIABLES + && runtimeVersion == FOREST_WITH_RECEIPT_COMPACTION)) { final DatabaseMetadata metadata = new DatabaseMetadata(runtimeVersion); try { metadata.writeToDirectory(dataDir); @@ -346,8 +346,8 @@ private Optional handleVersionUpgrade( "Database unsafe downgrade detect: DB at %s is %s with version %s but version %s is expected. " + "Please check your config and review release notes for supported downgrade procedures.", dataDir, - existingMetadata.getVersionedStorageFormat().getFormat().name(), - existingMetadata.getVersionedStorageFormat().getVersion(), + existingVersionedStorageFormat.getFormat().name(), + existingVersionedStorageFormat.getVersion(), runtimeVersion.getVersion()); throw new StorageException(error); diff --git a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/BaseVersionedStorageFormat.java b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/BaseVersionedStorageFormat.java index 658bb24a0f86..ad3557636d21 100644 --- a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/BaseVersionedStorageFormat.java +++ b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/BaseVersionedStorageFormat.java @@ -63,14 +63,8 @@ public enum BaseVersionedStorageFormat implements VersionedStorageFormat { public static BaseVersionedStorageFormat defaultForNewDB( final DataStorageConfiguration configuration) { return switch (configuration.getDatabaseFormat()) { - case FOREST -> - configuration.getReceiptCompactionEnabled() - ? FOREST_WITH_RECEIPT_COMPACTION - : FOREST_WITH_VARIABLES; - case BONSAI -> - configuration.getReceiptCompactionEnabled() - ? BONSAI_WITH_RECEIPT_COMPACTION - : BONSAI_WITH_VARIABLES; + case FOREST -> FOREST_WITH_RECEIPT_COMPACTION; + case BONSAI -> BONSAI_WITH_RECEIPT_COMPACTION; }; } diff --git a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/DatabaseMetadata.java b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/DatabaseMetadata.java index 46dbb9e7403d..a72db7c322b2 100644 --- a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/DatabaseMetadata.java +++ b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/DatabaseMetadata.java @@ -74,7 +74,7 @@ public static DatabaseMetadata defaultForNewDb(final BesuConfiguration besuConfi * @return the metadata to use for new db */ public static DatabaseMetadata defaultForNewPrivateDb() { - return new DatabaseMetadata(PrivacyVersionedStorageFormat.FOREST_WITH_VARIABLES); + return new DatabaseMetadata(PrivacyVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION); } /** diff --git a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/PrivacyVersionedStorageFormat.java b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/PrivacyVersionedStorageFormat.java index 87ff357e16de..ca5988dc75fe 100644 --- a/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/PrivacyVersionedStorageFormat.java +++ b/plugins/rocksdb/src/main/java/org/hyperledger/besu/plugin/services/storage/rocksdb/configuration/PrivacyVersionedStorageFormat.java @@ -32,7 +32,7 @@ public enum PrivacyVersionedStorageFormat implements VersionedStorageFormat { * Current Forest version, with receipts using compaction, in order to make Receipts use less disk * space */ - FOREST_WITH_RECEIPT_COMPACTION(BaseVersionedStorageFormat.FOREST_WITH_VARIABLES, 2), + FOREST_WITH_RECEIPT_COMPACTION(BaseVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION, 2), /** Original Bonsai version, not used since replace by BONSAI_WITH_VARIABLES */ BONSAI_ORIGINAL(BaseVersionedStorageFormat.BONSAI_ORIGINAL, 1), /** @@ -64,14 +64,8 @@ public enum PrivacyVersionedStorageFormat implements VersionedStorageFormat { public static VersionedStorageFormat defaultForNewDB( final DataStorageConfiguration configuration) { return switch (configuration.getDatabaseFormat()) { - case FOREST -> - configuration.getReceiptCompactionEnabled() - ? FOREST_WITH_RECEIPT_COMPACTION - : FOREST_WITH_VARIABLES; - case BONSAI -> - configuration.getReceiptCompactionEnabled() - ? BONSAI_WITH_RECEIPT_COMPACTION - : BONSAI_WITH_VARIABLES; + case FOREST -> FOREST_WITH_RECEIPT_COMPACTION; + case BONSAI -> BONSAI_WITH_RECEIPT_COMPACTION; }; } diff --git a/plugins/rocksdb/src/test/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValuePrivacyStorageFactoryTest.java b/plugins/rocksdb/src/test/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValuePrivacyStorageFactoryTest.java index 5dd485cb7af0..17a3fb874a4a 100644 --- a/plugins/rocksdb/src/test/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValuePrivacyStorageFactoryTest.java +++ b/plugins/rocksdb/src/test/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValuePrivacyStorageFactoryTest.java @@ -77,7 +77,7 @@ public void shouldDetectVersion1MetadataIfPresent() throws Exception { try (final var storage = storageFactory.create(segment, commonConfiguration, metricsSystem)) { assertThat(DatabaseMetadata.lookUpFrom(tempDataDir).getVersionedStorageFormat()) - .isEqualTo(PrivacyVersionedStorageFormat.FOREST_WITH_VARIABLES); + .isEqualTo(PrivacyVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION); } } @@ -97,7 +97,7 @@ public void shouldCreateCorrectMetadataFileForLatestVersion() throws Exception { // Side effect is creation of the Metadata version file try (final var storage = storageFactory.create(segment, commonConfiguration, metricsSystem)) { assertThat(DatabaseMetadata.lookUpFrom(tempDataDir).getVersionedStorageFormat()) - .isEqualTo(PrivacyVersionedStorageFormat.FOREST_WITH_VARIABLES); + .isEqualTo(PrivacyVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION); } } @@ -116,8 +116,8 @@ public void shouldUpdateCorrectMetadataFileForLatestVersion( try (final var storage = storageFactory.create(segment, commonConfiguration, metricsSystem)) { final BaseVersionedStorageFormat expectedBaseVersion = dataStorageFormat == BONSAI - ? BaseVersionedStorageFormat.BONSAI_WITH_VARIABLES - : BaseVersionedStorageFormat.FOREST_WITH_VARIABLES; + ? BaseVersionedStorageFormat.BONSAI_WITH_RECEIPT_COMPACTION + : BaseVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION; assertThat(DatabaseMetadata.lookUpFrom(tempDataDir).getVersionedStorageFormat()) .isEqualTo(expectedBaseVersion); } @@ -130,8 +130,8 @@ public void shouldUpdateCorrectMetadataFileForLatestVersion( privacyStorageFactory.create(segment, commonConfiguration, metricsSystem)) { final PrivacyVersionedStorageFormat expectedPrivacyVersion = dataStorageFormat == BONSAI - ? PrivacyVersionedStorageFormat.BONSAI_WITH_VARIABLES - : PrivacyVersionedStorageFormat.FOREST_WITH_VARIABLES; + ? PrivacyVersionedStorageFormat.BONSAI_WITH_RECEIPT_COMPACTION + : PrivacyVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION; assertThat(DatabaseMetadata.lookUpFrom(tempDataDir).getVersionedStorageFormat()) .isEqualTo(expectedPrivacyVersion); } @@ -145,7 +145,6 @@ public void shouldUpdateCorrectMetadataFileForLatestVersionWithReceiptCompaction final Path tempDataDir = temporaryFolder.resolve("data"); final Path tempDatabaseDir = temporaryFolder.resolve("db"); mockCommonConfiguration(tempDataDir, tempDatabaseDir, dataStorageFormat); - when(dataStorageConfiguration.getReceiptCompactionEnabled()).thenReturn(true); final RocksDBKeyValueStorageFactory storageFactory = new RocksDBKeyValueStorageFactory( diff --git a/plugins/rocksdb/src/test/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValueStorageFactoryTest.java b/plugins/rocksdb/src/test/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValueStorageFactoryTest.java index a86c5ba807b0..7148f601cbda 100644 --- a/plugins/rocksdb/src/test/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValueStorageFactoryTest.java +++ b/plugins/rocksdb/src/test/java/org/hyperledger/besu/plugin/services/storage/rocksdb/RocksDBKeyValueStorageFactoryTest.java @@ -76,8 +76,8 @@ public void shouldCreateCorrectMetadataFileForLatestVersionForNewDb( // Side effect is creation of the Metadata version file final BaseVersionedStorageFormat expectedVersion = dataStorageFormat == BONSAI - ? BaseVersionedStorageFormat.BONSAI_WITH_VARIABLES - : BaseVersionedStorageFormat.FOREST_WITH_VARIABLES; + ? BaseVersionedStorageFormat.BONSAI_WITH_RECEIPT_COMPACTION + : BaseVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION; assertThat(DatabaseMetadata.lookUpFrom(tempDataDir).getVersionedStorageFormat()) .isEqualTo(expectedVersion); } @@ -90,7 +90,6 @@ public void shouldCreateCorrectMetadataFileForLatestVersionForNewDbWithReceiptCo final Path tempDataDir = temporaryFolder.resolve("data"); final Path tempDatabaseDir = temporaryFolder.resolve("db"); mockCommonConfiguration(tempDataDir, tempDatabaseDir, dataStorageFormat); - when(dataStorageConfiguration.getReceiptCompactionEnabled()).thenReturn(true); final RocksDBKeyValueStorageFactory storageFactory = new RocksDBKeyValueStorageFactory( @@ -129,7 +128,7 @@ public void shouldFailIfDbExistsAndNoMetadataFileFound() throws Exception { } @Test - public void shouldDetectCorrectMetadataV1() throws Exception { + public void shouldDetectCorrectMetadataV1AndUpgrade() throws Exception { final Path tempDataDir = temporaryFolder.resolve("data"); final Path tempDatabaseDir = temporaryFolder.resolve("db"); Files.createDirectories(tempDataDir); @@ -143,7 +142,7 @@ public void shouldDetectCorrectMetadataV1() throws Exception { try (final var storage = storageFactory.create(segment, commonConfiguration, metricsSystem)) { assertThat(DatabaseMetadata.lookUpFrom(tempDataDir).getVersionedStorageFormat()) - .isEqualTo(BaseVersionedStorageFormat.BONSAI_WITH_VARIABLES); + .isEqualTo(BaseVersionedStorageFormat.BONSAI_WITH_RECEIPT_COMPACTION); assertThat(storageFactory.isSegmentIsolationSupported()).isTrue(); } } @@ -240,7 +239,7 @@ public void shouldDetectCorrectMetadataV2AndSetSegmentationFieldDuringCreation() () -> rocksDbConfiguration, segments, RocksDBMetricsFactory.PUBLIC_ROCKS_DB_METRICS); try (final var storage = storageFactory.create(segment, commonConfiguration, metricsSystem)) { assertThat(DatabaseMetadata.lookUpFrom(tempDataDir).getVersionedStorageFormat()) - .isEqualTo(BaseVersionedStorageFormat.FOREST_WITH_VARIABLES); + .isEqualTo(BaseVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION); assertThatCode(storageFactory::isSegmentIsolationSupported).doesNotThrowAnyException(); } } @@ -299,7 +298,7 @@ public void shouldCreateDBCorrectlyIfSymlink() throws Exception { // created correctly try (final var storage = storageFactory.create(segment, commonConfiguration, metricsSystem)) { assertThat(DatabaseMetadata.lookUpFrom(tempRealDataDir).getVersionedStorageFormat()) - .isEqualTo(BaseVersionedStorageFormat.FOREST_WITH_VARIABLES); + .isEqualTo(BaseVersionedStorageFormat.FOREST_WITH_RECEIPT_COMPACTION); } } diff --git a/settings.gradle b/settings.gradle index 09a8d20d4c6c..322383b32ca2 100644 --- a/settings.gradle +++ b/settings.gradle @@ -68,5 +68,6 @@ include 'privacy-contracts' include 'services:kvstore' include 'services:pipeline' include 'services:tasks' +include 'testfuzz' include 'testutil' include 'util' diff --git a/testfuzz/README.md b/testfuzz/README.md new file mode 100644 index 000000000000..8f436d701179 --- /dev/null +++ b/testfuzz/README.md @@ -0,0 +1,29 @@ +# BesuFuzz + +BesuFuzz is where all the besu guided fuzzing tools live. + +## eof-container + +Performs differential fuzzing between Ethereum clients based on +the [txparse eofparse](https://github.com/holiman/txparse/blob/main/README.md#eof-parser-eofparse) +format. Note that only the inital `OK` and `err` values are used to determine if +there is a difference. + +### Prototypical CLI Usage: + +```shell +BesuFuzz eof-container \ + --tests-dir=~/git/ethereum/tests/EOFTests \ + --client=evm1=evmone-eofparse \ + --client=revm=revme bytecode +``` + +### Prototypical Gradle usage: + +```shell +./gradlew fuzzEvmone fuzzReth +``` + +There are pre-written Gradle targets for `fuzzEthereumJS`, `fuzzEvmone`, +`fuzzGeth`, `fuzzNethermind`, and `fuzzReth`. Besu is always a fuzzing target. +The `fuzzAll` target will fuzz all clients. \ No newline at end of file diff --git a/testfuzz/build.gradle b/testfuzz/build.gradle new file mode 100644 index 000000000000..1c9679815592 --- /dev/null +++ b/testfuzz/build.gradle @@ -0,0 +1,148 @@ +/* + * Copyright contributors to Hyperledger 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 + */ + +apply plugin: 'application' +apply plugin: 'java-library' +apply plugin: 'jacoco' + +jar { + archiveBaseName = 'besu-test-fuzz' + manifest { + attributes( + 'Specification-Title': archiveBaseName, + 'Specification-Version': project.version, + 'Implementation-Title': archiveBaseName, + 'Implementation-Version': calculateVersion() + ) + } +} + +dependencies { + implementation project(':besu') + implementation project(':crypto:algorithms') + implementation project(':datatypes') + implementation project(':ethereum:referencetests') + implementation project(':evm') + implementation project(':util') + + implementation 'com.fasterxml.jackson.core:jackson-databind' + implementation 'com.gitlab.javafuzz:core' + implementation 'info.picocli:picocli' + implementation 'io.tmio:tuweni-bytes' + implementation 'org.jacoco:org.jacoco.agent' + implementation 'org.jacoco:org.jacoco.core' +} + +application { + applicationName = 'BesuFuzz' + mainClass = 'org.hyperledger.besu.testfuzz.BesuFuzz' + applicationDefaultJvmArgs = [ + '-javaagent:$APP_HOME/lib/jacocoagent.jar' + ] +} + +def corpusDir = "${buildDir}/generated/corpus" + +tasks.register("runFuzzer", JavaExec) { + classpath = sourceSets.main.runtimeClasspath + mainClass = 'org.hyperledger.besu.testfuzz.BesuFuzz' + + args = [ + "eof-container", + "--tests-dir=${projectDir}/../ethereum/referencetests/src/reference-test/external-resources/EOFTests", + "--corpus-dir=${corpusDir}" + ] + doFirst { + mkdir corpusDir + } +} + +tasks.register("fuzzEvmone") { + doLast { + runFuzzer.args += "--client=evm1=evmone-eofparse" + } + finalizedBy("runFuzzer") +} + +tasks.register("fuzzEthereumJS") { + doLast { + runFuzzer.args += "--client=etjs=tsx ../../../ethereumjs/ethereumjs-monorepo/packages/evm/scripts/eofContainerValidator.ts" + } + finalizedBy("runFuzzer") +} + +tasks.register("fuzzGeth") { + doLast { + runFuzzer.args += "--client=geth=eofdump eofparser" + } + finalizedBy("runFuzzer") +} + +tasks.register("fuzzNethermind") { + doLast { + runFuzzer.args += "--client=neth=netheofparse -x" + } + finalizedBy("runFuzzer") +} + +tasks.register("fuzzReth") { + doLast { + runFuzzer.args += "--client=revm=revme bytecode" + } + finalizedBy("runFuzzer") +} + +tasks.register("fuzzAll") { + dependsOn fuzzEvm1, fuzzEthJS, fuzzGeth, fuzzNethermind, fuzzReth +} + +jacoco { + applyTo run + applyTo runFuzzer +} + +// Copies jacoco into the lib directory +tasks.register("copyJacoco", Copy) { + // The jacocoagent.jar is embedded within the jar + from zipTree(configurations.jacocoAgent.singleFile).filter { it.name == 'jacocoagent.jar' }.singleFile + into layout.buildDirectory.dir("install/${application.applicationName}/lib") +} + +installDist.finalizedBy copyJacoco + +startScripts { + defaultJvmOpts = [ + "-Dsecp256k1.randomize=false" + ] + unixStartScriptGenerator.template = resources.text.fromFile("${projectDir}/src/main/scripts/unixStartScript.txt") + windowsStartScriptGenerator.template = resources.text.fromFile("${projectDir}/src/main/scripts/windowsStartScript.txt") + doLast { tweakStartScript(startScripts) } +} + +static def tweakStartScript(createScriptTask) { + def shortenWindowsClasspath = { line -> + line.replaceAll(/^set CLASSPATH=.*$/, "set CLASSPATH=%APP_HOME%/lib/*") + } + + createScriptTask.unixScript.text = createScriptTask.unixScript.text.replace('BESU_HOME', '\$APP_HOME') + createScriptTask.windowsScript.text = createScriptTask.windowsScript.text.replace('BESU_HOME', '%~dp0..') + + // Prevent the error originating from the 8191 chars limit on Windows + createScriptTask.windowsScript.text = + createScriptTask.windowsScript + .readLines() + .collect(shortenWindowsClasspath) + .join('\r\n') +} diff --git a/besu/src/test/java/org/hyperledger/besu/components/NoOpMetricsSystemModule.java b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/BesuFuzz.java similarity index 50% rename from besu/src/test/java/org/hyperledger/besu/components/NoOpMetricsSystemModule.java rename to testfuzz/src/main/java/org/hyperledger/besu/testfuzz/BesuFuzz.java index e7807e3d759c..6cde75880454 100644 --- a/besu/src/test/java/org/hyperledger/besu/components/NoOpMetricsSystemModule.java +++ b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/BesuFuzz.java @@ -12,29 +12,27 @@ * * SPDX-License-Identifier: Apache-2.0 */ -package org.hyperledger.besu.components; +package org.hyperledger.besu.testfuzz; -import org.hyperledger.besu.metrics.ObservableMetricsSystem; -import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem; -import org.hyperledger.besu.plugin.services.MetricsSystem; +import org.hyperledger.besu.util.LogConfigurator; -import javax.inject.Singleton; +/** The main entry point for the EVM (Ethereum Virtual Machine) tool. */ +public final class BesuFuzz { -import dagger.Module; -import dagger.Provides; - -@Module -public class NoOpMetricsSystemModule { - - @Provides - @Singleton - MetricsSystem provideMetricsSystem() { - return new NoOpMetricsSystem(); + /** Default constructor for the EvmTool class. */ + public BesuFuzz() { + // this is here only for Javadoc linting } - @Provides - @Singleton - ObservableMetricsSystem provideObservableMetricsSystem() { - return new NoOpMetricsSystem(); + /** + * The main entry point for the EVM (Ethereum Virtual Machine) tool. + * + * @param args The command line arguments. + */ + public static void main(final String... args) { + LogConfigurator.setLevel("", "DEBUG"); + final BesuFuzzCommand besuFuzzCommand = new BesuFuzzCommand(); + + besuFuzzCommand.execute(args); } } diff --git a/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/BesuFuzzCommand.java b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/BesuFuzzCommand.java new file mode 100644 index 000000000000..22165b5ffe87 --- /dev/null +++ b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/BesuFuzzCommand.java @@ -0,0 +1,78 @@ +/* + * Copyright contributors to Hyperledger 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.testfuzz; + +import static java.nio.charset.StandardCharsets.UTF_8; + +import org.hyperledger.besu.util.LogConfigurator; + +import java.io.InputStream; +import java.io.PrintWriter; + +import picocli.CommandLine; +import picocli.CommandLine.Command; + +/** + * This is the root command for the `BesuFuzz` command line tool. It is a collection of fuzzers that + * are guided by Besu's implementations. + */ +@Command( + description = "Executes Besu based fuzz tests", + abbreviateSynopsis = true, + name = "evm", + mixinStandardHelpOptions = true, + versionProvider = VersionProvider.class, + sortOptions = false, + header = "Usage:", + synopsisHeading = "%n", + descriptionHeading = "%nDescription:%n%n", + optionListHeading = "%nOptions:%n", + footerHeading = "%n", + footer = "Hyperledger Besu is licensed under the Apache License 2.0", + subcommands = {EofContainerSubCommand.class}) +@SuppressWarnings("java:S106") +public class BesuFuzzCommand implements Runnable { + + PrintWriter out; + InputStream in; + + /** Default Constructor */ + BesuFuzzCommand() { + // this method is here only for JavaDoc linting + } + + void execute(final String... args) { + execute(System.in, new PrintWriter(System.out, true, UTF_8), args); + } + + void execute(final InputStream input, final PrintWriter output, final String[] args) { + final CommandLine commandLine = new CommandLine(this).setOut(output); + out = output; + in = input; + + // don't require exact case to match enum values + commandLine.setCaseInsensitiveEnumValuesAllowed(true); + + commandLine.setExecutionStrategy(new CommandLine.RunLast()); + commandLine.execute(args); + } + + @Override + public void run() { + LogConfigurator.setLevel("", "OFF"); + System.out.println("No default command, please select a subcommand"); + System.exit(1); + } +} diff --git a/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/EofContainerSubCommand.java b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/EofContainerSubCommand.java new file mode 100644 index 000000000000..efe84296cf01 --- /dev/null +++ b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/EofContainerSubCommand.java @@ -0,0 +1,258 @@ +/* + * Copyright contributors to Hyperledger 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.testfuzz; + +import static org.hyperledger.besu.testfuzz.EofContainerSubCommand.COMMAND_NAME; + +import org.hyperledger.besu.datatypes.Address; +import org.hyperledger.besu.ethereum.referencetests.EOFTestCaseSpec; +import org.hyperledger.besu.evm.Code; +import org.hyperledger.besu.evm.EVM; +import org.hyperledger.besu.evm.MainnetEVMs; +import org.hyperledger.besu.evm.code.CodeInvalid; +import org.hyperledger.besu.evm.code.CodeV1; +import org.hyperledger.besu.evm.code.EOFLayout; +import org.hyperledger.besu.evm.code.EOFLayout.EOFContainerMode; +import org.hyperledger.besu.evm.internal.EvmConfiguration; + +import java.io.File; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.security.NoSuchAlgorithmException; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; + +import com.fasterxml.jackson.core.JsonParser.Feature; +import com.fasterxml.jackson.core.util.DefaultIndenter; +import com.fasterxml.jackson.core.util.DefaultPrettyPrinter; +import com.fasterxml.jackson.core.util.Separators; +import com.fasterxml.jackson.core.util.Separators.Spacing; +import com.fasterxml.jackson.databind.JavaType; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.module.SimpleModule; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import com.gitlab.javafuzz.core.AbstractFuzzTarget; +import org.apache.tuweni.bytes.Bytes; +import picocli.CommandLine; +import picocli.CommandLine.Option; + +/** Fuzzes the parsing and validation of an EOF container. */ +@SuppressWarnings({"java:S106", "CallToPrintStackTrace"}) // we use lots the console, on purpose +@CommandLine.Command( + name = COMMAND_NAME, + description = "Fuzzes EOF container parsing and validation", + mixinStandardHelpOptions = true, + versionProvider = VersionProvider.class) +public class EofContainerSubCommand extends AbstractFuzzTarget implements Runnable { + + static final String COMMAND_NAME = "eof-container"; + + @Option( + names = {"--corpus-dir"}, + paramLabel = "", + description = "Directory to store corpus files") + private final Path corpusDir = Path.of("corpus"); + + @Option( + names = {"--tests-dir"}, + paramLabel = "", + description = "Directory where EOF tests references file tree lives") + private final Path testsDir = null; + + @Option( + names = {"--client"}, + paramLabel = "=", + description = "Add a client for differential fuzzing") + private final Map clients = new LinkedHashMap<>(); + + @CommandLine.ParentCommand private final BesuFuzzCommand parentCommand; + + static final ObjectMapper eofTestMapper = createObjectMapper(); + static final JavaType javaType = + eofTestMapper + .getTypeFactory() + .constructParametricType(Map.class, String.class, EOFTestCaseSpec.class); + + List externalClients = new ArrayList<>(); + EVM evm = MainnetEVMs.pragueEOF(EvmConfiguration.DEFAULT); + long validContainers; + long totalContainers; + + /** + * Default constructor for the EofContainerSubCommand class. This constructor initializes the + * parentCommand to null. + */ + public EofContainerSubCommand() { + this(null); + } + + /** + * Constructs a new EofContainerSubCommand with the specified parent command. + * + * @param parentCommand The parent command for this subcommand. + */ + public EofContainerSubCommand(final BesuFuzzCommand parentCommand) { + this.parentCommand = parentCommand; + } + + private static ObjectMapper createObjectMapper() { + final ObjectMapper objectMapper = new ObjectMapper(); + objectMapper.setDefaultPrettyPrinter( + (new DefaultPrettyPrinter()) + .withSeparators( + Separators.createDefaultInstance().withObjectFieldValueSpacing(Spacing.BOTH)) + .withObjectIndenter(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE.withIndent(" ")) + .withArrayIndenter(DefaultIndenter.SYSTEM_LINEFEED_INSTANCE.withIndent(" "))); + objectMapper.disable(Feature.AUTO_CLOSE_SOURCE); + SimpleModule serializers = new SimpleModule("Serializers"); + serializers.addSerializer(Address.class, ToStringSerializer.instance); + serializers.addSerializer(Bytes.class, ToStringSerializer.instance); + objectMapper.registerModule(serializers); + + return objectMapper; + } + + @Override + public void run() { + // load test dir into corpus dir + if (testsDir != null) { + File f = testsDir.toFile(); + if (f.isDirectory()) { + try (var files = Files.walk(f.toPath(), Integer.MAX_VALUE)) { + files.forEach( + ff -> { + File file = ff.toFile(); + if (file.isFile()) { + extractFile(file, corpusDir.toFile()); + } + }); + } catch (IOException e) { + parentCommand.out.println("Exception walking " + f + ": " + e.getMessage()); + } + } + } + + clients.forEach((k, v) -> externalClients.add(new StreamingClient(k, v.split(" ")))); + System.out.println("Fuzzing client set: " + clients.keySet()); + + try { + new Fuzzer(this, corpusDir.toString(), this::fuzzStats).start(); + } catch (NoSuchAlgorithmException + | ClassNotFoundException + | InvocationTargetException + | IllegalAccessException + | NoSuchMethodException e) { + throw new RuntimeException(e); + } + } + + private void extractFile(final File f, final File initialCorpus) { + final Map eofTests; + try { + eofTests = eofTestMapper.readValue(f, javaType); + } catch (IOException e) { + // presume parse failed because it's a corpus file + return; + } + for (var entry : eofTests.entrySet()) { + int index = 0; + for (var vector : entry.getValue().getVector().entrySet()) { + try (FileOutputStream fos = + new FileOutputStream( + new File( + initialCorpus, + f.toPath().getFileName() + "_" + (index++) + "_" + vector.getKey()))) { + Bytes codeBytes = Bytes.fromHexString(vector.getValue().code()); + evm.getCodeUncached(codeBytes); + fos.write(codeBytes.toArrayUnsafe()); + } catch (IOException e) { + parentCommand.out.println("Invalid file " + f + ": " + e.getMessage()); + e.printStackTrace(); + System.exit(1); + } + } + } + } + + @Override + public void fuzz(final byte[] bytes) { + Bytes eofUnderTest = Bytes.wrap(bytes); + String eofUnderTestHexString = eofUnderTest.toHexString(); + Code code = evm.getCodeUncached(eofUnderTest); + Map results = new LinkedHashMap<>(); + boolean mismatch = false; + for (var client : externalClients) { + String value = client.differentialFuzz(eofUnderTestHexString); + results.put(client.getName(), value); + if (value == null || value.startsWith("fail: ")) { + mismatch = true; // if an external client fails, always report it as an error + } + } + boolean besuValid = false; + String besuReason; + if (!code.isValid()) { + besuReason = ((CodeInvalid) code).getInvalidReason(); + } else if (code.getEofVersion() != 1) { + EOFLayout layout = EOFLayout.parseEOF(eofUnderTest); + if (layout.isValid()) { + besuReason = "Besu Parsing Error"; + parentCommand.out.println(layout.version()); + parentCommand.out.println(layout.invalidReason()); + parentCommand.out.println(code.getEofVersion()); + parentCommand.out.println(code.getClass().getName()); + System.exit(1); + mismatch = true; + } else { + besuReason = layout.invalidReason(); + } + } else if (EOFContainerMode.INITCODE.equals( + ((CodeV1) code).getEofLayout().containerMode().get())) { + besuReason = "Code is initcode, not runtime"; + } else { + besuReason = "OK"; + besuValid = true; + } + for (var entry : results.entrySet()) { + mismatch = + mismatch + || besuValid != entry.getValue().toUpperCase(Locale.getDefault()).startsWith("OK"); + } + if (mismatch) { + parentCommand.out.println("besu: " + besuReason); + for (var entry : results.entrySet()) { + parentCommand.out.println(entry.getKey() + ": " + entry.getValue()); + } + parentCommand.out.println("code: " + eofUnderTest.toUnprefixedHexString()); + parentCommand.out.println("size: " + eofUnderTest.size()); + parentCommand.out.println(); + } else { + if (besuValid) { + validContainers++; + } + totalContainers++; + } + } + + String fuzzStats() { + return " / %5.2f%% valid %d/%d" + .formatted((100.0 * validContainers) / totalContainers, validContainers, totalContainers); + } +} diff --git a/besu/src/test/java/org/hyperledger/besu/components/GenesisConfigModule.java b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/ExternalClient.java similarity index 57% rename from besu/src/test/java/org/hyperledger/besu/components/GenesisConfigModule.java rename to testfuzz/src/main/java/org/hyperledger/besu/testfuzz/ExternalClient.java index ae82b8b9288e..e5505239ab78 100644 --- a/besu/src/test/java/org/hyperledger/besu/components/GenesisConfigModule.java +++ b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/ExternalClient.java @@ -12,27 +12,11 @@ * * SPDX-License-Identifier: Apache-2.0 */ -package org.hyperledger.besu.components; +package org.hyperledger.besu.testfuzz; -import org.hyperledger.besu.config.GenesisConfigFile; +interface ExternalClient { -import javax.inject.Named; + String getName(); -import dagger.Module; -import dagger.Provides; - -@Module -public class GenesisConfigModule { - - @Named("default") - @Provides - GenesisConfigFile provideDefaultGenesisConfigFile() { - return GenesisConfigFile.DEFAULT; - } - - @Named("mainnet") - @Provides - GenesisConfigFile provideMainnetGenesisConfigFile() { - return GenesisConfigFile.mainnet(); - } + String differentialFuzz(String data); } diff --git a/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/Fuzzer.java b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/Fuzzer.java new file mode 100644 index 000000000000..e4ebb68cc88f --- /dev/null +++ b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/Fuzzer.java @@ -0,0 +1,239 @@ +/* + * Copyright contributors to Hyperledger 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.testfuzz; + +import org.hyperledger.besu.crypto.Hash; +import org.hyperledger.besu.crypto.MessageDigestFactory; + +import java.io.ByteArrayInputStream; +import java.io.FileOutputStream; +import java.io.IOException; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.math.BigInteger; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; +import java.util.HashMap; +import java.util.Map; +import java.util.function.Supplier; + +import com.gitlab.javafuzz.core.AbstractFuzzTarget; +import com.gitlab.javafuzz.core.Corpus; +import org.apache.tuweni.bytes.Bytes; +import org.jacoco.core.data.ExecutionData; +import org.jacoco.core.data.ExecutionDataReader; +import org.jacoco.core.data.IExecutionDataVisitor; +import org.jacoco.core.data.ISessionInfoVisitor; +import org.jacoco.core.data.SessionInfo; + +/** Ported from javafuzz because JaCoCo APIs changed. */ +@SuppressWarnings({"java:S106", "CallToPrintStackTrace"}) // we use lots the console, on purpose +public class Fuzzer { + private final AbstractFuzzTarget target; + private final Corpus corpus; + private final Object agent; + private final Method getExecutionDataMethod; + private long executionsInSample; + private long lastSampleTime; + private long totalExecutions; + private long totalCoverage; + + Supplier fuzzStats; + + /** + * Create a new fuzzer + * + * @param target The target to fuzz + * @param dirs the list of corpus dirs and files, comma separated. + * @param fuzzStats additional fuzzing data from the client + * @throws ClassNotFoundException If Jacoco RT is not found (because jacocoagent.jar is not + * loaded) + * @throws NoSuchMethodException If the wrong version of Jacoco is loaded + * @throws InvocationTargetException If the wrong version of Jacoco is loaded + * @throws IllegalAccessException If the wrong version of Jacoco is loaded + * @throws NoSuchAlgorithmException If the SHA-256 crypto algo cannot be loaded. + */ + public Fuzzer( + final AbstractFuzzTarget target, final String dirs, final Supplier fuzzStats) + throws ClassNotFoundException, + NoSuchMethodException, + InvocationTargetException, + IllegalAccessException, + NoSuchAlgorithmException { + this.target = target; + this.corpus = new Corpus(dirs); + this.fuzzStats = fuzzStats; + Class c = Class.forName("org.jacoco.agent.rt.RT"); + Method getAgentMethod = c.getMethod("getAgent"); + this.agent = getAgentMethod.invoke(null); + this.getExecutionDataMethod = agent.getClass().getMethod("getExecutionData", boolean.class); + fileNameForBuffer(new byte[0]); + } + + void writeCrash(final byte[] buf) { + Bytes hash = Hash.sha256(Bytes.wrap(buf)); + String filepath = "crash-" + hash.toUnprefixedHexString(); + try (FileOutputStream fos = new FileOutputStream(filepath)) { + fos.write(buf); + System.out.printf("crash was written to %s%n", filepath); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + void logStats(final String type) { + long rss = + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / 1024 / 1024; + long endTime = System.currentTimeMillis(); + long execs_per_second = -1; + if ((endTime - this.lastSampleTime) != 0) { + execs_per_second = (this.executionsInSample * 1000 / (endTime - this.lastSampleTime)); + } + this.lastSampleTime = endTime; + this.executionsInSample = 0; + + System.out.printf( + "#%d %s cov: %d corp: %d exec/s: %d rss: %d MB %s%n", + this.totalExecutions, + type, + this.totalCoverage, + this.corpus.getLength(), + execs_per_second, + rss, + fuzzStats.get()); + } + + /** + * Runs the fuzzer until the VM is shut down + * + * @throws InvocationTargetException if the wrong version of jacoco is loaded + * @throws IllegalAccessException if the wrong version of jacoco is loaded + * @throws NoSuchAlgorithmException if our favorite hash algo is not loaded + */ + @SuppressWarnings("java:S2189") // the endless loop is on purpose + public void start() + throws InvocationTargetException, IllegalAccessException, NoSuchAlgorithmException { + System.out.printf("#0 READ units: %d%n", this.corpus.getLength()); + this.totalCoverage = 0; + this.totalExecutions = 0; + this.executionsInSample = 0; + this.lastSampleTime = System.currentTimeMillis(); + + Map hitMap = new HashMap<>(); + + while (true) { + byte[] buf = this.corpus.generateInput(); + // The next version will run this in a different thread. + try { + this.target.fuzz(buf); + } catch (Exception e) { + e.printStackTrace(System.out); + this.writeCrash(buf); + System.exit(1); + break; + } + + this.totalExecutions++; + this.executionsInSample++; + + long newCoverage = getHitCount(hitMap); + if (newCoverage > this.totalCoverage) { + this.totalCoverage = newCoverage; + this.corpus.putBuffer(buf); + this.logStats("NEW"); + + // If you want hex strings of new hits, uncomment the following. + // String filename = fileNameForBuffer(buf); + // try (var pw = + // new PrintWriter( + // new BufferedWriter( + // new OutputStreamWriter(new FileOutputStream(filename), UTF_8)))) { + // pw.println(Bytes.wrap(buf).toHexString()); + // System.out.println(filename); + // } catch (IOException e) { + // e.printStackTrace(System.out); + // } + } else if ((System.currentTimeMillis() - this.lastSampleTime) > 30000) { + this.logStats("PULSE"); + } + } + } + + private static String fileNameForBuffer(final byte[] buf) throws NoSuchAlgorithmException { + MessageDigest md = MessageDigestFactory.create(MessageDigestFactory.SHA256_ALG); + md.update(buf); + byte[] digest = md.digest(); + return String.format("./new-%064x.hex", new BigInteger(1, digest)); + } + + private long getHitCount(final Map hitMap) + throws IllegalAccessException, InvocationTargetException { + byte[] dumpData = (byte[]) this.getExecutionDataMethod.invoke(this.agent, false); + ExecutionDataReader edr = new ExecutionDataReader(new ByteArrayInputStream(dumpData)); + HitCounter hc = new HitCounter(hitMap); + edr.setExecutionDataVisitor(hc); + edr.setSessionInfoVisitor(hc); + try { + edr.read(); + } catch (IOException e) { + e.printStackTrace(); + this.writeCrash(dumpData); + } + + return hc.getHits(); + } + + static class HitCounter implements IExecutionDataVisitor, ISessionInfoVisitor { + long hits = 0; + Map hitMap; + + public HitCounter(final Map hitMap) { + this.hitMap = hitMap; + } + + @Override + public void visitClassExecution(final ExecutionData executionData) { + int hit = 0; + for (boolean b : executionData.getProbes()) { + if (executionData.getName().startsWith("org/hyperledger/besu/testfuzz/") + || executionData.getName().startsWith("org/bouncycastle/") + || executionData.getName().startsWith("com/gitlab/javafuzz/")) { + continue; + } + if (b) { + hit++; + } + } + String name = executionData.getName(); + if (hitMap.containsKey(name)) { + if (hitMap.get(name) < hit) { + hitMap.put(name, hit); + } + } else { + hitMap.put(name, hit); + } + hits += hit; + } + + public long getHits() { + return hits; + } + + @Override + public void visitSessionInfo(final SessionInfo sessionInfo) { + // nothing to do. Data parser requires a session listener. + } + } +} diff --git a/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/SingleQueryClient.java b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/SingleQueryClient.java new file mode 100644 index 000000000000..802a6011aaf1 --- /dev/null +++ b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/SingleQueryClient.java @@ -0,0 +1,89 @@ +/* + * Copyright contributors to Hyperledger 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.testfuzz; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +@SuppressWarnings({"java:S106", "CallToPrintStackTrace"}) // we use lots the console, on purpose +class SingleQueryClient implements ExternalClient { + final String name; + String[] command; + Pattern okRegexp; + String okRegexpStr; + int okGroup; + Pattern failRegexp; + int failGroup; + String failRegexpStr; + + public SingleQueryClient( + final String clientName, + final String okRegexp, + final int okGroup, + final String errorRegexp, + final int failGroup, + final String... command) { + this.name = clientName; + this.okRegexp = Pattern.compile(okRegexp); + this.okRegexpStr = okRegexp; + this.okGroup = okGroup; + this.failRegexp = Pattern.compile(errorRegexp); + this.failGroup = failGroup; + this.failRegexpStr = errorRegexp; + this.command = command; + } + + @Override + public String getName() { + return name; + } + + @Override + @SuppressWarnings("java:S2142") + public String differentialFuzz(final String data) { + if (!data.startsWith("0xef")) { + return "err: invalid_magic"; + } + try { + List localCommand = new ArrayList<>(command.length + 1); + localCommand.addAll(Arrays.asList(command)); + localCommand.add(data); + Process p = new ProcessBuilder().command(localCommand).redirectErrorStream(true).start(); + if (!p.waitFor(1, TimeUnit.SECONDS)) { + System.out.println("Process Hang for " + name); + return "fail: process took more than 1 sec " + p.pid(); + } + String s = new String(p.getInputStream().readAllBytes(), StandardCharsets.UTF_8); + Matcher m = okRegexp.matcher(s); + if (m.find()) { + return "OK " + m.group(okGroup); + } + m = failRegexp.matcher(s); + if (m.find()) { + return "err: " + m.group(failGroup); + } + return "fail: SingleClientQuery failed to get data"; + } catch (InterruptedException | IOException e) { + e.printStackTrace(); + return "fail: " + e.getMessage(); + } + } +} diff --git a/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/StreamingClient.java b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/StreamingClient.java new file mode 100644 index 000000000000..a59cd9326ffb --- /dev/null +++ b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/StreamingClient.java @@ -0,0 +1,52 @@ +/* + * Copyright contributors to Hyperledger 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.testfuzz; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; + +class StreamingClient implements ExternalClient { + final String name; + final BufferedReader reader; + final PrintWriter writer; + + public StreamingClient(final String clientName, final String... command) { + try { + Process p = new ProcessBuilder().redirectErrorStream(true).command(command).start(); + this.name = clientName; + this.reader = new BufferedReader(p.inputReader(StandardCharsets.UTF_8)); + this.writer = new PrintWriter(p.getOutputStream(), true, StandardCharsets.UTF_8); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + @Override + public String getName() { + return name; + } + + @Override + public String differentialFuzz(final String data) { + try { + writer.println(data); + return reader.readLine(); + } catch (IOException ioe) { + throw new RuntimeException(ioe); + } + } +} diff --git a/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/VersionProvider.java b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/VersionProvider.java new file mode 100644 index 000000000000..6a184dd90e94 --- /dev/null +++ b/testfuzz/src/main/java/org/hyperledger/besu/testfuzz/VersionProvider.java @@ -0,0 +1,47 @@ +/* + * Copyright contributors to Hyperledger 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.testfuzz; + +import org.hyperledger.besu.BesuInfo; + +import picocli.CommandLine; + +/** + * The VersionProvider class is responsible for providing the version of the Hyperledger Besu EVM + * tool. It implements the IVersionProvider interface from the picocli library. + * + *

The getVersion method returns a string array containing the version of the Hyperledger Besu + * EVM tool. + */ +public class VersionProvider implements CommandLine.IVersionProvider { + + /** + * Default constructor for the VersionProvider class. This constructor does not perform any + * operations. + */ + public VersionProvider() { + // this constructor is here only for javadoc linting + } + + /** + * This method returns the version of the Hyperledger Besu EVM tool. + * + * @return A string array containing the version of the Hyperledger Besu EVM tool. + */ + @Override + public String[] getVersion() { + return new String[] {"Hyperledger Besu evm " + BesuInfo.shortVersion()}; + } +} diff --git a/testfuzz/src/main/scripts/unixStartScript.txt b/testfuzz/src/main/scripts/unixStartScript.txt new file mode 100644 index 000000000000..59d8b83fbc7c --- /dev/null +++ b/testfuzz/src/main/scripts/unixStartScript.txt @@ -0,0 +1,200 @@ +#!/usr/bin/env sh + +# +# Copyright 2015 the original author or authors. +# +# 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 +# +# https://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. +# + +############################################################################## +## +## ${applicationName} start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: \$0 may be a link +PRG="\$0" +# Need this for relative symlinks. +while [ -h "\$PRG" ] ; do + ls=`ls -ld "\$PRG"` + link=`expr "\$ls" : '.*-> \\(.*\\)\$'` + if expr "\$link" : '/.*' > /dev/null; then + PRG="\$link" + else + PRG=`dirname "\$PRG"`"/\$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"\$PRG\"`/${appHomeRelativePath}" >/dev/null +APP_HOME="`pwd -P`" +cd "\$SAVED" >/dev/null + +APP_NAME="${applicationName}" +APP_BASE_NAME=`basename "\$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and ${optsEnvironmentVar} to pass JVM options to this script. +DEFAULT_JVM_OPTS=${defaultJvmOpts} + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "\$*" +} + +die () { + echo + echo "\$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MSYS* | MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$classpath +<% if ( mainClassName.startsWith('--module ') ) { %>MODULE_PATH=$modulePath<% } %> + +# Determine the Java command to use to start the JVM. +if [ -n "\$JAVA_HOME" ] ; then + if [ -x "\$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="\$JAVA_HOME/jre/sh/java" + else + JAVACMD="\$JAVA_HOME/bin/java" + fi + if [ ! -x "\$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: \$JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "\$cygwin" = "false" -a "\$darwin" = "false" -a "\$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ \$? -eq 0 ] ; then + if [ "\$MAX_FD" = "maximum" -o "\$MAX_FD" = "max" ] ; then + MAX_FD="\$MAX_FD_LIMIT" + fi + ulimit -n \$MAX_FD + if [ \$? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: \$MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: \$MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if \$darwin; then + GRADLE_OPTS="\$GRADLE_OPTS \\"-Xdock:name=\$APP_NAME\\" \\"-Xdock:icon=\$APP_HOME/media/gradle.icns\\"" +fi + +# For Cygwin or MSYS, switch paths to Windows format before running java +if [ "\$cygwin" = "true" -o "\$msys" = "true" ] ; then + APP_HOME=`cygpath --path --mixed "\$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "\$CLASSPATH"` +<% if ( mainClassName.startsWith('--module ') ) { %> MODULE_PATH=`cygpath --path --mixed "\$MODULE_PATH"`<% } %> + JAVACMD=`cygpath --unix "\$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in \$ROOTDIRSRAW ; do + ROOTDIRS="\$ROOTDIRS\$SEP\$dir" + SEP="|" + done + OURCYGPATTERN="(^(\$ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "\$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="\$OURCYGPATTERN|(\$GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "\$@" ; do + CHECK=`echo "\$arg"|egrep -c "\$OURCYGPATTERN" -` + CHECK2=`echo "\$arg"|egrep -c "^-"` ### Determine if an option + + if [ \$CHECK -ne 0 ] && [ \$CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args\$i`=`cygpath --path --ignore --mixed "\$arg"` + else + eval `echo args\$i`="\"\$arg\"" + fi + i=`expr \$i + 1` + done + case \$i in + 0) set -- ;; + 1) set -- "\$args0" ;; + 2) set -- "\$args0" "\$args1" ;; + 3) set -- "\$args0" "\$args1" "\$args2" ;; + 4) set -- "\$args0" "\$args1" "\$args2" "\$args3" ;; + 5) set -- "\$args0" "\$args1" "\$args2" "\$args3" "\$args4" ;; + 6) set -- "\$args0" "\$args1" "\$args2" "\$args3" "\$args4" "\$args5" ;; + 7) set -- "\$args0" "\$args1" "\$args2" "\$args3" "\$args4" "\$args5" "\$args6" ;; + 8) set -- "\$args0" "\$args1" "\$args2" "\$args3" "\$args4" "\$args5" "\$args6" "\$args7" ;; + 9) set -- "\$args0" "\$args1" "\$args2" "\$args3" "\$args4" "\$args5" "\$args6" "\$args7" "\$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\\\n "\$i" | sed "s/'/'\\\\\\\\''/g;1s/^/'/;\\\$s/\\\$/' \\\\\\\\/" ; done + echo " " +} +APP_ARGS=`save "\$@"` + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- -javaagent:\$APP_HOME/lib/jacocoagent.jar \$DEFAULT_JVM_OPTS \$JAVA_OPTS \$${optsEnvironmentVar} <% if ( appNameSystemProperty ) { %>"\"-D${appNameSystemProperty}=\$APP_BASE_NAME\"" <% } %>-classpath "\"\$CLASSPATH\"" <% if ( mainClassName.startsWith('--module ') ) { %>--module-path "\"\$MODULE_PATH\"" <% } %>${mainClassName} "\$APP_ARGS" + +unset BESU_USING_JEMALLOC +if [ "\$darwin" = "false" -a "\$msys" = "false" ]; then + # check if jemalloc is available + TEST_JEMALLOC=\$(LD_PRELOAD=libjemalloc.so sh -c true 2>&1) + + # if jemalloc is available the output is empty, otherwise the output has an error line + if [ -z "\$TEST_JEMALLOC" ]; then + export LD_PRELOAD=libjemalloc.so + export BESU_USING_JEMALLOC=true + else + # jemalloc not available, as fallback limit malloc to 2 arenas + export MALLOC_ARENA_MAX=2 + fi +fi + +exec "\$JAVACMD" "\$@" diff --git a/testfuzz/src/main/scripts/windowsStartScript.txt b/testfuzz/src/main/scripts/windowsStartScript.txt new file mode 100644 index 000000000000..2ce40892ef22 --- /dev/null +++ b/testfuzz/src/main/scripts/windowsStartScript.txt @@ -0,0 +1,91 @@ +@rem +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem ${applicationName} startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=.\ + +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME%${appHomeRelativePath} + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and ${optsEnvironmentVar} to pass JVM options to this script. +set DEFAULT_JVM_OPTS=${defaultJvmOpts} + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=$classpath +<% if ( mainClassName.startsWith('--module ') ) { %>set MODULE_PATH=$modulePath<% } %> + +@rem Execute ${applicationName} +"%JAVA_EXE%" -javaagent:%APP_HOME%/lib/jacocoagent.jar %DEFAULT_JVM_OPTS% %JAVA_OPTS% %${optsEnvironmentVar}% <% if ( appNameSystemProperty ) { %>"-D${appNameSystemProperty}=%APP_BASE_NAME%"<% } %> -classpath "%CLASSPATH%" <% if ( mainClassName.startsWith('--module ') ) { %>--module-path "%MODULE_PATH%" <% } %>${mainClassName} %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable ${exitEnvironmentVar} if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%${exitEnvironmentVar}%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega