build - Refactor Besu custom error prone dependency (#6692)

Move Besu custom error-prone checks into its own repository and use it as an external dependency. This allows to move to a newer version of Google errorprone checks as well while cleaning up build.gradle file.

Key changes resulted due to this change:

* String toLowerCase and toUpperCase to use Locale.ROOT as argument
* Use interface such as List,Map or NavigatableMap instead of concrete class where appropriate.
* Simplify StringBuilder to plain String
* Suppress warnings where appropriate.
-----
Signed-off-by: Usman Saleem <usman@usmans.info>
pull/6823/head
Usman Saleem 8 months ago committed by GitHub
parent 56e1844415
commit e954537fcc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
  1. 5
      acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/node/BesuNode.java
  2. 3
      acceptance-tests/dsl/src/main/java/org/hyperledger/besu/tests/acceptance/dsl/transaction/DeploySmartContractTransaction.java
  3. 7
      besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java
  4. 5
      besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java
  5. 3
      besu/src/main/java/org/hyperledger/besu/cli/config/NetworkName.java
  6. 4
      besu/src/main/java/org/hyperledger/besu/cli/config/ProfileName.java
  7. 3
      besu/src/main/java/org/hyperledger/besu/cli/converter/MetricCategoryConverter.java
  8. 3
      besu/src/main/java/org/hyperledger/besu/cli/options/stable/DataStorageOptions.java
  9. 5
      besu/src/main/java/org/hyperledger/besu/cli/options/stable/LoggingLevelOption.java
  10. 13
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/GenerateBlockchainConfig.java
  11. 1
      besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java
  12. 9
      besu/src/main/java/org/hyperledger/besu/services/RpcEndpointServiceImpl.java
  13. 38
      build.gradle
  14. 3
      config/src/main/java/org/hyperledger/besu/config/BftFork.java
  15. 3
      config/src/main/java/org/hyperledger/besu/config/JsonBftConfigOptions.java
  16. 3
      config/src/main/java/org/hyperledger/besu/config/JsonUtil.java
  17. 9
      consensus/common/src/test-support/java/org/hyperledger/besu/consensus/common/bft/inttest/NetworkLayout.java
  18. 6
      crypto/algorithms/src/main/java/org/hyperledger/besu/crypto/SignatureAlgorithmFactory.java
  19. 8
      crypto/algorithms/src/main/java/org/hyperledger/besu/crypto/SignatureAlgorithmType.java
  20. 2
      crypto/algorithms/src/test/java/org/hyperledger/besu/crypto/SECP256R1Test.java
  21. 3
      datatypes/src/main/java/org/hyperledger/besu/datatypes/Wei.java
  22. 3
      enclave/src/integration-test/java/org/hyperledger/besu/enclave/TlsHelpers.java
  23. 9
      errorprone-checks/README.md
  24. 70
      errorprone-checks/build.gradle
  25. 60
      errorprone-checks/src/main/java/org/hyperledger/errorpronechecks/BannedMethod.java
  26. 59
      errorprone-checks/src/main/java/org/hyperledger/errorpronechecks/DoNotCreateSecureRandomDirectly.java
  27. 44
      errorprone-checks/src/main/java/org/hyperledger/errorpronechecks/DoNotInvokeMessageDigestDirectly.java
  28. 69
      errorprone-checks/src/main/java/org/hyperledger/errorpronechecks/DoNotReturnNullOptionals.java
  29. 76
      errorprone-checks/src/main/java/org/hyperledger/errorpronechecks/ExperimentalCliOptionMustBeCorrectlyDisplayed.java
  30. 131
      errorprone-checks/src/main/java/org/hyperledger/errorpronechecks/MethodInputParametersMustBeFinal.java
  31. 75
      errorprone-checks/src/main/java/org/hyperledger/errorpronechecks/PreferCommonAnnotations.java
  32. 70
      errorprone-checks/src/main/java/org/hyperledger/errorpronechecks/PrivateStaticFinalLoggers.java
  33. 39
      errorprone-checks/src/test/java/org/hyperledger/errorpronechecks/BannedMethodTest.java
  34. 40
      errorprone-checks/src/test/java/org/hyperledger/errorpronechecks/DoNotCreateSecureRandomDirectlyTest.java
  35. 40
      errorprone-checks/src/test/java/org/hyperledger/errorpronechecks/DoNotInvokeMessageDigestDirectlyTest.java
  36. 40
      errorprone-checks/src/test/java/org/hyperledger/errorpronechecks/DoNotReturnNullOptionalsTest.java
  37. 45
      errorprone-checks/src/test/java/org/hyperledger/errorpronechecks/ExperimentalCliOptionMustBeCorrectlyDisplayedTest.java
  38. 54
      errorprone-checks/src/test/java/org/hyperledger/errorpronechecks/MethodInputParametersMustBeFinalTest.java
  39. 40
      errorprone-checks/src/test/java/org/hyperledger/errorpronechecks/PreferCommonAnnotationsTest.java
  40. 40
      errorprone-checks/src/test/java/org/hyperledger/errorpronechecks/PrivateStaticFinalLoggersTest.java
  41. 29
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/BannedMethodNegativeCases.java
  42. 50
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/BannedMethodPositiveCases.java
  43. 34
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/DoNotCreateSecureRandomDirectlyNegativeCases.java
  44. 41
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/DoNotCreateSecureRandomDirectlyPositiveCases.java
  45. 26
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/DoNotInvokeMessageDigestDirectlyNegativeCases.java
  46. 26
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/DoNotInvokeMessageDigestDirectlyPositiveCases.java
  47. 36
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/DoNotReturnNullOptionalsNegativeCases.java
  48. 35
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/DoNotReturnNullOptionalsPositiveCases.java
  49. 50
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/ExperimentalCliOptionMustBeCorrectlyDisplayedNegativeCases.java
  50. 41
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/ExperimentalCliOptionMustBeCorrectlyDisplayedPositiveCases.java
  51. 40
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/MethodInputParametersMustBeFinalInterfaceNegativeCases.java
  52. 24
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/MethodInputParametersMustBeFinalInterfacePositiveCases.java
  53. 63
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/MethodInputParametersMustBeFinalNegativeCases.java
  54. 41
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/MethodInputParametersMustBeFinalPositiveCases.java
  55. 32
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/PreferCommonAnnotationsNegativeCases.java
  56. 27
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/PreferCommonAnnotationsPositiveCases.java
  57. 25
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/PrivateStaticFinalLoggersNegativeCases.java
  58. 25
      errorprone-checks/src/test/resources/org/hyperledger/errorpronechecks/PrivateStaticFinalLoggersPositiveCases.java
  59. 3
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/GraphQLHttpService.java
  60. 4
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/graphql/internal/Scalars.java
  61. 3
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpService.java
  62. 3
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/BlockParameter.java
  63. 3
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/BlockParameterOrBlockHash.java
  64. 3
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/parameters/PendingTransactionsParams.java
  65. 4
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/websocket/WebSocketService.java
  66. 3
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/JsonRpcHttpServiceTest.java
  67. 1
      ethereum/core/build.gradle
  68. 5
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/mainnet/ProtocolScheduleBuilder.java
  69. 14
      ethereum/core/src/main/java/org/hyperledger/besu/ethereum/privacy/PrivateTransactionReceipt.java
  70. 50
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/mainnet/EthHashTest.java
  71. 3
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/messages/snap/AccountRangeMessage.java
  72. 9
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/messages/snap/StorageRangeMessage.java
  73. 5
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/SyncMode.java
  74. 7
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/SnapWorldDownloadState.java
  75. 4
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/SnapWorldStateDownloader.java
  76. 7
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/StackTrie.java
  77. 3
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/context/SnapSyncStatePersistenceManager.java
  78. 6
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/request/AccountRangeDataRequest.java
  79. 6
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/request/SnapDataRequest.java
  80. 6
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/request/StorageRangeDataRequest.java
  81. 7
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/request/heal/AccountFlatDatabaseHealingRangeRequest.java
  82. 7
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/request/heal/AccountTrieNodeHealingRequest.java
  83. 5
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/sync/snapsync/request/heal/StorageFlatDatabaseHealingRangeRequest.java
  84. 3
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/layered/AbstractPrioritizedTransactions.java
  85. 3
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/layered/AbstractSequentialTransactionsLayer.java
  86. 4
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/layered/AbstractTransactionsLayer.java
  87. 6
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/layered/ReadyTransactions.java
  88. 3
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/layered/SparseTransactions.java
  89. 3
      ethereum/eth/src/main/java/org/hyperledger/besu/ethereum/eth/transactions/layered/TransactionsLayer.java
  90. 3
      ethereum/eth/src/test/java/org/hyperledger/besu/ethereum/eth/messages/snap/StorageRangeMessageTest.java
  91. 3
      ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/benchmarks/BenchmarkExecutor.java
  92. 4
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/discovery/PeerDiscoveryStatus.java
  93. 3
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/peers/EnodeURLImpl.java
  94. 2
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/wire/Capability.java
  95. 2
      ethereum/p2p/src/main/java/org/hyperledger/besu/ethereum/p2p/rlpx/wire/PeerInfo.java
  96. 31
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/discovery/PeerDiscoveryTimestampsTest.java
  97. 3
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/MockConnectionInitializer.java
  98. 4
      ethereum/p2p/src/test/java/org/hyperledger/besu/ethereum/p2p/rlpx/connections/netty/DeFramerTest.java
  99. 1
      ethereum/referencetests/src/main/java/org/hyperledger/besu/ethereum/referencetests/ReferenceTestBlockchain.java
  100. 5
      ethereum/trie/src/main/java/org/hyperledger/besu/ethereum/trie/RangeManager.java
  101. Some files were not shown because too many files have changed in this diff Show More

@ -62,6 +62,7 @@ import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Properties;
@ -431,7 +432,9 @@ public class BesuNode implements NodeConfiguration, RunnableNode, AutoCloseable
getGenesisConfig()
.map(
gc ->
gc.toLowerCase().contains("ibft") ? ConsensusType.IBFT2 : ConsensusType.QBFT)
gc.toLowerCase(Locale.ROOT).contains("ibft")
? ConsensusType.IBFT2
: ConsensusType.QBFT)
.orElse(ConsensusType.IBFT2);
nodeRequests =

@ -20,6 +20,7 @@ import java.lang.reflect.Method;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import org.web3j.crypto.Credentials;
@ -83,7 +84,7 @@ public class DeploySmartContractTransaction<T extends Contract> implements Trans
@SuppressWarnings("rawtypes")
private boolean parameterTypesAreEqual(
final Class<?>[] expectedTypes, final ArrayList<Object> actualObjects) {
final Class<?>[] expectedTypes, final List<Object> actualObjects) {
if (expectedTypes.length != actualObjects.size()) {
return false;
}

@ -133,6 +133,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
@ -800,7 +801,7 @@ public class RunnerBuilder {
metricsSystem,
supportedCapabilities,
jsonRpcConfiguration.getRpcApis().stream()
.filter(apiGroup -> !apiGroup.toLowerCase().startsWith("engine"))
.filter(apiGroup -> !apiGroup.toLowerCase(Locale.ROOT).startsWith("engine"))
.collect(Collectors.toList()),
filterManager,
accountLocalConfigPermissioningController,
@ -938,7 +939,7 @@ public class RunnerBuilder {
metricsSystem,
supportedCapabilities,
webSocketConfiguration.getRpcApis().stream()
.filter(apiGroup -> !apiGroup.toLowerCase().startsWith("engine"))
.filter(apiGroup -> !apiGroup.toLowerCase(Locale.ROOT).startsWith("engine"))
.collect(Collectors.toList()),
filterManager,
accountLocalConfigPermissioningController,
@ -1021,7 +1022,7 @@ public class RunnerBuilder {
metricsSystem,
supportedCapabilities,
jsonRpcIpcConfiguration.getEnabledApis().stream()
.filter(apiGroup -> !apiGroup.toLowerCase().startsWith("engine"))
.filter(apiGroup -> !apiGroup.toLowerCase(Locale.ROOT).startsWith("engine"))
.collect(Collectors.toList()),
filterManager,
accountLocalConfigPermissioningController,

@ -2623,10 +2623,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
SignatureAlgorithmFactory.setInstance(SignatureAlgorithmType.create(ecCurve.get()));
} catch (final IllegalArgumentException e) {
throw new CommandLine.InitializationException(
new StringBuilder()
.append("Invalid genesis file configuration for ecCurve. ")
.append(e.getMessage())
.toString());
"Invalid genesis file configuration for ecCurve. " + e.getMessage());
}
}

@ -15,6 +15,7 @@
package org.hyperledger.besu.cli.config;
import java.math.BigInteger;
import java.util.Locale;
import java.util.Optional;
import org.apache.commons.lang3.StringUtils;
@ -91,7 +92,7 @@ public enum NetworkName {
* @return the string
*/
public String normalize() {
return StringUtils.capitalize(name().toLowerCase());
return StringUtils.capitalize(name().toLowerCase(Locale.ROOT));
}
/**

@ -14,6 +14,8 @@
*/
package org.hyperledger.besu.cli.config;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
/** Enum for profile names. Each profile corresponds to a configuration file. */
@ -51,6 +53,6 @@ public enum ProfileName {
@Override
public String toString() {
return StringUtils.capitalize(name().replaceAll("_", " ").toLowerCase());
return StringUtils.capitalize(name().replaceAll("_", " ").toLowerCase(Locale.ROOT));
}
}

@ -18,6 +18,7 @@ import org.hyperledger.besu.plugin.services.metrics.MetricCategory;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import com.google.common.annotations.VisibleForTesting;
@ -54,7 +55,7 @@ public class MetricCategoryConverter implements CommandLine.ITypeConverter<Metri
* @param metricCategory the metric category
*/
public void addRegistryCategory(final MetricCategory metricCategory) {
metricCategories.put(metricCategory.getName().toUpperCase(), metricCategory);
metricCategories.put(metricCategory.getName().toUpperCase(Locale.ROOT), metricCategory);
}
/**

@ -30,6 +30,7 @@ import org.hyperledger.besu.ethereum.worldstate.ImmutableDataStorageConfiguratio
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import java.util.List;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
import picocli.CommandLine;
@ -193,6 +194,6 @@ public class DataStorageOptions implements CLIOptions<DataStorageConfiguration>
* @return the normalized string
*/
public String normalizeDataStorageFormat() {
return StringUtils.capitalize(dataStorageFormat.toString().toLowerCase());
return StringUtils.capitalize(dataStorageFormat.toString().toLowerCase(Locale.ROOT));
}
}

@ -14,6 +14,7 @@
*/
package org.hyperledger.besu.cli.options.stable;
import java.util.Locale;
import java.util.Set;
import picocli.CommandLine;
@ -52,8 +53,8 @@ public class LoggingLevelOption {
if ("FATAL".equalsIgnoreCase(logLevel)) {
System.out.println("FATAL level is deprecated");
this.logLevel = "ERROR";
} else if (ACCEPTED_VALUES.contains(logLevel.toUpperCase())) {
this.logLevel = logLevel.toUpperCase();
} else if (ACCEPTED_VALUES.contains(logLevel.toUpperCase(Locale.ROOT))) {
this.logLevel = logLevel.toUpperCase(Locale.ROOT);
} else {
throw new CommandLine.ParameterException(
spec.commandLine(), "Unknown logging value: " + logLevel);

@ -178,11 +178,9 @@ class GenerateBlockchainConfig implements Runnable {
if (!SIGNATURE_ALGORITHM.get().isValidPublicKey(publicKey)) {
throw new IllegalArgumentException(
new StringBuilder()
.append(publicKeyText)
.append(" is not a valid public key for elliptic curve ")
.append(SIGNATURE_ALGORITHM.get().getCurveName())
.toString());
publicKeyText
+ " is not a valid public key for elliptic curve "
+ SIGNATURE_ALGORITHM.get().getCurveName());
}
writeKeypair(publicKey, null);
@ -297,10 +295,7 @@ class GenerateBlockchainConfig implements Runnable {
SignatureAlgorithmFactory.setInstance(SignatureAlgorithmType.create(ecCurve.get()));
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException(
new StringBuilder()
.append("Invalid parameter for ecCurve in genesis config: ")
.append(e.getMessage())
.toString());
"Invalid parameter for ecCurve in genesis config: " + e.getMessage());
}
}

@ -249,6 +249,7 @@ public class TransitionBesuControllerBuilder extends BesuControllerBuilder {
return sync;
}
@SuppressWarnings("UnusedVariable")
private void initTransitionWatcher(
final ProtocolContext protocolContext, final TransitionCoordinator composedCoordinator) {

@ -24,6 +24,7 @@ import org.hyperledger.besu.plugin.services.rpc.PluginRpcRequest;
import java.util.Collection;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
@ -58,7 +59,10 @@ public class RpcEndpointServiceImpl implements RpcEndpointService {
namespaces.stream()
.anyMatch(
namespace ->
entry.getKey().toUpperCase().startsWith(namespace.toUpperCase())))
entry
.getKey()
.toUpperCase(Locale.ROOT)
.startsWith(namespace.toUpperCase(Locale.ROOT))))
.map(entry -> new PluginJsonRpcMethod(entry.getKey(), entry.getValue()))
.collect(Collectors.toMap(PluginJsonRpcMethod::getName, e -> e));
}
@ -71,6 +75,7 @@ public class RpcEndpointServiceImpl implements RpcEndpointService {
*/
public boolean hasNamespace(final String namespace) {
return rpcMethods.keySet().stream()
.anyMatch(key -> key.toUpperCase().startsWith(namespace.toUpperCase()));
.anyMatch(
key -> key.toUpperCase(Locale.ROOT).startsWith(namespace.toUpperCase(Locale.ROOT)));
}
}

@ -29,7 +29,7 @@ plugins {
id 'com.jfrog.artifactory' version '5.1.11'
id 'io.spring.dependency-management' version '1.1.4'
id 'me.champeau.jmh' version '0.7.2' apply false
id 'net.ltgt.errorprone' version '3.0.1'
id 'net.ltgt.errorprone' version '3.1.0'
id 'maven-publish'
id 'org.sonarqube' version '4.4.1.3373'
}
@ -132,12 +132,12 @@ allprojects {
}
task sourcesJar(type: Jar, dependsOn: classes) {
classifier = 'sources'
archiveClassifier = 'sources'
from sourceSets.main.allSource
}
task javadocJar(type: Jar, dependsOn: javadoc) {
classifier = 'javadoc'
archiveClassifier = 'javadoc'
from javadoc.outputDirectory
}
@ -160,6 +160,7 @@ allprojects {
url 'https://splunk.jfrog.io/splunk/ext-releases-local'
content { includeGroupByRegex('com\\.splunk\\..*') }
}
mavenCentral()
// ethereum execution spec tests fixtures. Exclusively for ethereum submodule to run ref tests
@ -181,6 +182,8 @@ allprojects {
dependencies {
components.all(BouncyCastleCapability)
errorprone 'com.google.errorprone:error_prone_core'
// https://github.com/hyperledger/besu-errorprone-checks/
errorprone "org.hyperledger.besu:besu-errorprone-checks"
}
configurations.all {
@ -216,7 +219,7 @@ allprojects {
format 'sol', { target '**/*.sol' }
}
tasks.withType(JavaCompile) {
tasks.withType(JavaCompile).configureEach {
options.compilerArgs += [
'-Xlint:unchecked',
'-Xlint:cast',
@ -229,8 +232,8 @@ allprojects {
]
options.errorprone {
excludedPaths = '.*/(generated/*.*|.*ReferenceTest_.*|build/.*/annotation-output/.*)'
excludedPaths = '.*/generated/*.*'
disableWarningsInGeneratedCode = true
// Our equals need to be symmetric, this checker doesn't respect that.
check('EqualsGetClass', CheckSeverity.OFF)
// We like to use futures with no return values.
@ -292,7 +295,7 @@ allprojects {
*
*/
test {
jvmArgs = [
jvmArgs += [
'-Xmx4g',
'-XX:-UseGCOverheadLimit',
// Mockito and jackson-databind do some strange reflection during tests.
@ -397,7 +400,7 @@ subprojects {
task testSupportJar(type: Jar) {
archiveBaseName = "${project.name}-support-test"
classifier = 'test-support'
archiveClassifier = 'test-support'
from sourceSets.testSupport.output
}
}
@ -997,7 +1000,7 @@ task checkSpdxHeader(type: CheckSpdxHeader) {
jacocoTestReport {
reports {
xml.enabled true
xml.required = true
}
}
@ -1008,25 +1011,12 @@ task jacocoRootReport(type: org.gradle.testing.jacoco.tasks.JacocoReport) {
executionData.from fileTree(dir: '.', includes: ['**/jacoco/*.exec'])
reports {
xml.required = true
xml.enabled = true
csv.required = true
html.destination file("build/reports/jacocoHtml")
}
onlyIf = { true }
}
configurations { annotationProcessor }
// Prevent errorprone-checks being dependent upon errorprone-checks!
// However, ensure all subprojects comply with the custom rules.
configure(subprojects.findAll { it.name != 'errorprone-checks' }) {
dependencies { annotationProcessor project(":errorprone-checks") }
tasks.withType(JavaCompile) {
options.annotationProcessorPath = configurations.annotationProcessor
}
}
// http://label-schema.org/rc1/
// using the RFC3339 format "2016-04-12T23:20:50.52Z"
def buildTime() {
@ -1107,9 +1097,11 @@ tasks.register("verifyDistributions") {
}
dependencies {
errorprone 'com.google.errorprone:error_prone_core'
// https://github.com/hyperledger/besu-errorprone-checks/
errorprone 'org.hyperledger.besu:besu-errorprone-checks'
implementation project(':besu')
implementation project(':ethereum:evmtool')
errorprone 'com.google.errorprone:error_prone_core'
}
@CompileStatic

@ -18,6 +18,7 @@ import org.hyperledger.besu.datatypes.Address;
import java.math.BigInteger;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.OptionalInt;
@ -89,7 +90,7 @@ public class BftFork implements Fork {
return Optional.empty();
}
final String weiStr = configFileContent.get();
if (weiStr.toLowerCase().startsWith("0x")) {
if (weiStr.toLowerCase(Locale.ROOT).startsWith("0x")) {
return Optional.of(new BigInteger(1, Bytes.fromHexStringLenient(weiStr).toArrayUnsafe()));
}
return Optional.of(new BigInteger(weiStr));

@ -17,6 +17,7 @@ package org.hyperledger.besu.config;
import org.hyperledger.besu.datatypes.Address;
import java.math.BigInteger;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
@ -117,7 +118,7 @@ public class JsonBftConfigOptions implements BftConfigOptions {
return BigInteger.ZERO;
}
final String weiStr = configFileContent.get();
if (weiStr.toLowerCase().startsWith("0x")) {
if (weiStr.toLowerCase(Locale.ROOT).startsWith("0x")) {
return new BigInteger(1, Bytes.fromHexStringLenient(weiStr).toArrayUnsafe());
}
return new BigInteger(weiStr);

@ -446,7 +446,8 @@ public class JsonUtil {
final String errorMessage =
String.format(
"Expected %s value but got %s",
expectedType.toString().toLowerCase(), node.getNodeType().toString().toLowerCase());
expectedType.toString().toLowerCase(Locale.ROOT),
node.getNodeType().toString().toLowerCase(Locale.ROOT));
throw new IllegalArgumentException(errorMessage);
}
return true;

@ -21,6 +21,7 @@ import org.hyperledger.besu.ethereum.core.Util;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.Set;
import java.util.TreeMap;
@ -29,11 +30,11 @@ import com.google.common.collect.Iterables;
public class NetworkLayout {
private final NodeParams localNode;
private final TreeMap<Address, NodeParams> addressKeyMap;
private final NavigableMap<Address, NodeParams> addressKeyMap;
private final List<NodeParams> remotePeers;
public NetworkLayout(
final NodeParams localNode, final TreeMap<Address, NodeParams> addressKeyMap) {
final NodeParams localNode, final NavigableMap<Address, NodeParams> addressKeyMap) {
this.localNode = localNode;
this.addressKeyMap = addressKeyMap;
this.remotePeers = new ArrayList<>(addressKeyMap.values());
@ -42,14 +43,14 @@ public class NetworkLayout {
public static NetworkLayout createNetworkLayout(
final int validatorCount, final int firstLocalNodeBlockNum) {
final TreeMap<Address, NodeParams> addressKeyMap = createValidators(validatorCount);
final NavigableMap<Address, NodeParams> addressKeyMap = createValidators(validatorCount);
final NodeParams localNode = Iterables.get(addressKeyMap.values(), firstLocalNodeBlockNum);
return new NetworkLayout(localNode, addressKeyMap);
}
private static TreeMap<Address, NodeParams> createValidators(final int validatorCount) {
private static NavigableMap<Address, NodeParams> createValidators(final int validatorCount) {
// Map is required to be sorted by address
final TreeMap<Address, NodeParams> addressKeyMap = new TreeMap<>();

@ -49,10 +49,8 @@ public class SignatureAlgorithmFactory {
if (!SignatureAlgorithmType.isDefault(instance)) {
LOG.info(
new StringBuilder("The signature algorithm uses the elliptic curve ")
.append(instance.getCurveName())
.append(". The usage of alternative elliptic curves is still experimental.")
.toString());
"The signature algorithm uses the elliptic curve {}. The usage of alternative elliptic curves is still experimental.",
instance.getCurveName());
}
}

@ -94,11 +94,9 @@ public class SignatureAlgorithmType {
}
private static String invalidTypeErrorMessage(final String invalidEcCurve) {
return new StringBuilder()
.append(invalidEcCurve)
.append(" is not in the list of valid elliptic curves ")
.append(getEcCurvesListAsString())
.toString();
return invalidEcCurve
+ " is not in the list of valid elliptic curves "
+ getEcCurvesListAsString();
}
private static String getEcCurvesListAsString() {

@ -160,7 +160,7 @@ public class SECP256R1Test {
final BigInteger recoveredPubKeyBigInt =
secp256R1.recoverFromSignature(
signature.getRecId(), signature.getR(), signature.getS(), dataHash);
assertThat(recoveredPubKeyBigInt).isEqualTo(recoveredPubKeyBigInt);
assertThat(recoveredPubKeyBigInt).isEqualTo(publicKeyBigInt);
});
}

@ -16,6 +16,7 @@ package org.hyperledger.besu.datatypes;
import java.math.BigInteger;
import java.util.Arrays;
import java.util.Locale;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.BaseUInt256Value;
@ -224,7 +225,7 @@ public final class Wei extends BaseUInt256Value<Wei> implements Quantity {
@Override
public String toString() {
return name().toLowerCase();
return name().toLowerCase(Locale.ROOT);
}
}
}

@ -32,6 +32,7 @@ import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Enumeration;
import java.util.List;
import java.util.Locale;
import java.util.Optional;
import java.util.StringJoiner;
@ -93,6 +94,6 @@ public class TlsHelpers {
joiner.add(String.format("%02X", b));
}
return joiner.toString().toLowerCase();
return joiner.toString().toLowerCase(Locale.ROOT);
}
}

@ -1,9 +0,0 @@
The creation of custom errorprone checkers was largely derived from:
* https://github.com/tbroyer/gradle-errorprone-plugin
* https://errorprone.info/docs/installation
* https://github.com/google/error-prone/wiki/Writing-a-check
To allow for debugging from within intellij, the following must be added to the VM args
in the run/debug configuration (this assumes your gradle cache is at the default location under
your home):
-Xbootclasspath/p:${HOME}/.gradle/caches/./modules-2/files-2.1/com.google.errorprone/javac/9+181-r4173-1/bdf4c0aa7d540ee1f7bf14d47447aea4bbf450c5/javac-9+181-r4173-1.jar

@ -1,70 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
// we use this config to get the path of the JDK 9 javac jar, to
// stick it in the bootclasspath when running tests
configurations.maybeCreate("epJavac")
apply plugin: 'java'
apply plugin: 'net.ltgt.errorprone'
sourceCompatibility = 17
targetCompatibility = 17
dependencies {
api 'org.slf4j:slf4j-api'
annotationProcessor 'com.google.auto.service:auto-service'
implementation 'com.google.auto.service:auto-service'
implementation 'com.google.errorprone:error_prone_annotation'
implementation 'com.google.errorprone:error_prone_core'
implementation 'info.picocli:picocli'
testImplementation 'com.google.errorprone:error_prone_test_helpers'
testImplementation 'org.assertj:assertj-core'
testImplementation 'org.junit.jupiter:junit-jupiter'
// imported to get org.jetbrains.annotations.NotNull
testImplementation 'org.jetbrains.kotlin:kotlin-stdlib'
epJavac 'com.google.errorprone:error_prone_check_api'
}
test { testLogging { showStandardStreams = true } }
tasks.withType(JavaCompile) {
options.compilerArgs += [
'--add-exports',
'jdk.compiler/com.sun.tools.javac.api=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.code=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.comp=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.file=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.parser=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.tree=ALL-UNNAMED',
'--add-exports',
'jdk.compiler/com.sun.tools.javac.util=ALL-UNNAMED'
]
}
javadoc { enabled = false }

@ -1,60 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.matchers.method.MethodMatchers.staticMethod;
import java.util.Map;
import com.google.auto.service.AutoService;
import com.google.common.collect.ImmutableMap;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.MethodInvocationTree;
@AutoService(BugChecker.class)
@BugPattern(
summary = "Some methods should not be used, make sure that doesn't happen.",
severity = WARNING,
linkType = BugPattern.LinkType.NONE)
public class BannedMethod extends BugChecker implements MethodInvocationTreeMatcher {
private static final ImmutableMap<Matcher<ExpressionTree>, String> BANNED_METHOD_LIST =
ImmutableMap.of(
staticMethod().onClass("com.google.common.base.Objects").withAnyName(),
"Do not use com.google.common.base.Objects methods, use java.util.Objects methods instead.",
staticMethod().onClass("org.junit.Assert"),
"Do not use junit assertions. Use assertj assertions instead.",
staticMethod().onClass("org.apache.logging.log4j.LogManager"),
"Do not use org.apache.logging.log4j.LogManager, use org.slf4j.LoggerFactory methods instead.");
@Override
public Description matchMethodInvocation(
final MethodInvocationTree tree, final VisitorState state) {
for (final Map.Entry<Matcher<ExpressionTree>, String> entry : BANNED_METHOD_LIST.entrySet()) {
if (entry.getKey().matches(tree, state)) {
return buildDescription(tree).setMessage(entry.getValue()).build();
}
}
return NO_MATCH;
}
}

@ -1,59 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.NewClassTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.NewClassTree;
import com.sun.tools.javac.code.Symbol;
@AutoService(BugChecker.class)
@BugPattern(
summary = "Do not create SecureRandom directly.",
severity = WARNING,
linkType = BugPattern.LinkType.NONE)
public class DoNotCreateSecureRandomDirectly extends BugChecker
implements MethodInvocationTreeMatcher, NewClassTreeMatcher {
@SuppressWarnings("TreeToString")
@Override
public Description matchMethodInvocation(
final MethodInvocationTree tree, final VisitorState state) {
if (tree.getMethodSelect().toString().equals("SecureRandom.getInstance")) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
@Override
public Description matchNewClass(final NewClassTree tree, final VisitorState state) {
final Symbol sym = ASTHelpers.getSymbol(tree.getIdentifier());
if (sym != null && sym.toString().equals("java.security.SecureRandom")) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
}

@ -1,44 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.sun.source.tree.MethodInvocationTree;
@AutoService(BugChecker.class)
@BugPattern(
summary = "Do not invoke MessageDigest.getInstance directly.",
severity = WARNING,
linkType = BugPattern.LinkType.NONE)
public class DoNotInvokeMessageDigestDirectly extends BugChecker
implements MethodInvocationTreeMatcher {
@SuppressWarnings("TreeToString")
@Override
public Description matchMethodInvocation(
final MethodInvocationTree tree, final VisitorState state) {
if (tree.getMethodSelect().toString().equals("MessageDigest.getInstance")) {
return describeMatch(tree);
}
return Description.NO_MATCH;
}
}

@ -1,69 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import static com.google.errorprone.BugPattern.SeverityLevel.SUGGESTION;
import static com.google.errorprone.matchers.Matchers.contains;
import static com.sun.source.tree.Tree.Kind.NULL_LITERAL;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ReturnTree;
import com.sun.source.tree.Tree;
/*
* This is reworked from an example found at:
* https://github.com/google/error-prone/wiki/Writing-a-check
*/
@AutoService(BugChecker.class) // the service descriptor
@BugPattern(
summary = "Do not return null optionals.",
severity = SUGGESTION,
linkType = BugPattern.LinkType.NONE)
public class DoNotReturnNullOptionals extends BugChecker implements MethodTreeMatcher {
private static class ReturnNullMatcher implements Matcher<Tree> {
@Override
public boolean matches(final Tree tree, final VisitorState state) {
if ((tree instanceof ReturnTree) && (((ReturnTree) tree).getExpression() != null)) {
return ((ReturnTree) tree).getExpression().getKind() == NULL_LITERAL;
}
return false;
}
}
private static final Matcher<Tree> RETURN_NULL = new ReturnNullMatcher();
private static final Matcher<Tree> CONTAINS_RETURN_NULL = contains(RETURN_NULL);
@SuppressWarnings("TreeToString")
@Override
public Description matchMethod(final MethodTree tree, final VisitorState state) {
if ((tree.getReturnType() == null)
|| !tree.getReturnType().toString().startsWith("Optional<")
|| (tree.getBody() == null)
|| (!CONTAINS_RETURN_NULL.matches(tree.getBody(), state))) {
return Description.NO_MATCH;
}
return describeMatch(tree);
}
}

@ -1,76 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import java.util.Map;
import java.util.Optional;
import javax.lang.model.element.AnnotationMirror;
import javax.lang.model.element.AnnotationValue;
import javax.lang.model.element.ExecutableElement;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.AnnotationTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.AnnotationTree;
import com.sun.tools.javac.tree.JCTree;
@AutoService(BugChecker.class)
@BugPattern(
summary = "Experimental options must be hidden and not present in the BesuCommand class.",
severity = WARNING,
linkType = BugPattern.LinkType.NONE)
public class ExperimentalCliOptionMustBeCorrectlyDisplayed extends BugChecker
implements AnnotationTreeMatcher {
@Override
public Description matchAnnotation(AnnotationTree tree, VisitorState state) {
final AnnotationMirror annotationMirror = ASTHelpers.getAnnotationMirror(tree);
if (annotationMirror.getAnnotationType().toString().equals("picocli.CommandLine.Option")) {
final Optional<? extends AnnotationValue> names =
getAnnotationValue(annotationMirror, "names");
if (names.isPresent() && names.get().getValue().toString().contains("--X")) {
final JCTree.JCCompilationUnit compilation =
(JCTree.JCCompilationUnit) state.getPath().getCompilationUnit();
if (compilation.getSourceFile().getName().endsWith("BesuCommand.java")) {
return describeMatch(tree);
}
final Optional<? extends AnnotationValue> isHidden =
getAnnotationValue(annotationMirror, "hidden");
if (isHidden.isEmpty() || !((boolean) isHidden.get().getValue())) {
return describeMatch(tree);
}
}
}
return Description.NO_MATCH;
}
private Optional<? extends AnnotationValue> getAnnotationValue(
final AnnotationMirror annotationMirror, final String name) {
final Map<? extends ExecutableElement, ? extends AnnotationValue> elementValues =
annotationMirror.getElementValues();
final Optional<? extends AnnotationValue> retValue =
elementValues.keySet().stream()
.filter(k -> k.getSimpleName().toString().equals(name))
.map(elementValues::get)
.findAny();
return retValue;
}
}

@ -1,131 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import javax.lang.model.element.Modifier;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ClassTreeMatcher;
import com.google.errorprone.bugpatterns.BugChecker.MethodTreeMatcher;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.ModifiersTree;
import com.sun.source.tree.VariableTree;
@AutoService(BugChecker.class)
@BugPattern(
summary = "Method input parameters must be final.",
severity = WARNING,
linkType = BugPattern.LinkType.NONE)
public class MethodInputParametersMustBeFinal extends BugChecker
implements MethodTreeMatcher, ClassTreeMatcher {
private boolean isAbstraction = false;
private boolean isGenerated = false;
@Override
public Description matchClass(final ClassTree tree, final VisitorState state) {
isAbstraction =
isInterface(tree.getModifiers())
|| isAnonymousClassInAbstraction(tree)
|| isEnumInAbstraction(tree);
isGenerated = ASTHelpers.hasDirectAnnotationWithSimpleName(tree, "Generated");
return Description.NO_MATCH;
}
@Override
public Description matchMethod(final MethodTree tree, final VisitorState state) {
if (isGenerated) {
return Description.NO_MATCH;
}
final ModifiersTree mods = tree.getModifiers();
if (isAbstraction) {
if (isConcreteMethod(mods)) {
return matchParameters(tree);
}
} else if (isNotAbstract(mods)) {
return matchParameters(tree);
}
return Description.NO_MATCH;
}
private Description matchParameters(final MethodTree tree) {
for (final VariableTree inputParameter : tree.getParameters()) {
if (isMissingFinalModifier(inputParameter)) {
return describeMatch(tree);
}
}
return Description.NO_MATCH;
}
private boolean isMissingFinalModifier(final VariableTree inputParameter) {
return !inputParameter.getModifiers().getFlags().contains(Modifier.FINAL);
}
private boolean isNotAbstract(final ModifiersTree mods) {
return !mods.getFlags().contains(Modifier.ABSTRACT);
}
@SuppressWarnings("TreeToString")
private boolean isInterface(final ModifiersTree mods) {
return mods.toString().contains("interface");
}
private boolean isConcreteMethod(final ModifiersTree mods) {
return mods.getFlags().contains(Modifier.DEFAULT) || mods.getFlags().contains(Modifier.STATIC);
}
private boolean isAnonymousClassInAbstraction(final ClassTree tree) {
return isAbstraction && isAnonymousClass(tree);
}
private boolean isAnonymousClass(final ClassTree tree) {
return tree.getSimpleName().contentEquals("");
}
private boolean isEnumInAbstraction(final ClassTree tree) {
return isAbstraction && isEnum(tree);
}
@SuppressWarnings("TreeToString")
private boolean isEnum(final ClassTree tree) {
return tree.toString().contains("enum");
}
@Override
public boolean equals(Object o) {
// isAbstract and isGenerated are transient calculations, not relevant to equality checks
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
return super.equals(o);
}
@Override
public int hashCode() {
// isAbstract and isGenerated are transient calculations, not relevant to equality checks
return super.hashCode();
}
}

@ -1,75 +0,0 @@
/*
* (c) Copyright 2023 Palantir Technologies Inc. All rights reserved.
* Copyright Hyperledger Besu contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
/* Derived from https://github.com/palantir/gradle-baseline/blob/6fe385a80291473e7fc1441f176454bec4184d6b/baseline-error-prone/src/main/java/com/palantir/baseline/errorprone/PreferCommonAnnotations.java */
package org.hyperledger.errorpronechecks;
import java.util.Map;
import java.util.Objects;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.BugPattern.SeverityLevel;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.ImportTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.ImportTree;
import com.sun.tools.javac.code.Type;
/**
* Checker that recommends using the common version of an annotation.
*
* <p>Examples: - Guava's version of {@code @VisibleForTesting} over other copies.
*/
@AutoService(BugChecker.class)
@BugPattern(
summary = "Prefer the common version of annotations over other copies.",
severity = SeverityLevel.WARNING)
public final class PreferCommonAnnotations extends BugChecker implements ImportTreeMatcher {
/** ClassName -> preferred import. */
private static final Map<String, String> PREFERRED_IMPORTS =
Map.of("org.jetbrains.annotations.NotNull", "javax.annotation.Nonnull");
@Override
public Description matchImport(ImportTree tree, VisitorState state) {
Type importType = ASTHelpers.getType(tree.getQualifiedIdentifier());
if (importType == null) {
return Description.NO_MATCH;
}
String importName = importType.toString();
for (Map.Entry<String, String> entry : PREFERRED_IMPORTS.entrySet()) {
String affectedClassName = entry.getKey();
String preferredType = entry.getValue();
if (importName.endsWith(affectedClassName) && !Objects.equals(importName, preferredType)) {
SuggestedFix fix =
SuggestedFix.builder().removeImport(importName).addImport(preferredType).build();
return this.buildDescription(tree)
.setMessage("Do not use " + importName + " use " + preferredType + " instead.")
.addFix(fix)
.build();
}
}
return Description.NO_MATCH;
}
}

@ -1,70 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import static com.google.errorprone.BugPattern.SeverityLevel.WARNING;
import static com.google.errorprone.fixes.SuggestedFixes.addModifiers;
import static com.google.errorprone.matchers.Description.NO_MATCH;
import static com.google.errorprone.util.ASTHelpers.getType;
import static com.google.errorprone.util.ASTHelpers.isSubtype;
import java.util.List;
import java.util.Optional;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;
import com.google.auto.service.AutoService;
import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.bugpatterns.BugChecker;
import com.google.errorprone.bugpatterns.BugChecker.VariableTreeMatcher;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.suppliers.Supplier;
import com.google.errorprone.suppliers.Suppliers;
import com.google.errorprone.util.ASTHelpers;
import com.sun.source.tree.VariableTree;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Type;
@AutoService(BugChecker.class)
@BugPattern(
summary = "Logger classes should be private, static, and final.",
severity = WARNING,
linkType = BugPattern.LinkType.NONE)
public class PrivateStaticFinalLoggers extends BugChecker implements VariableTreeMatcher {
static final Supplier<Type> ORG_SLF4J_LOGGER = Suppliers.typeFromString("org.slf4j.Logger");
@Override
public Description matchVariable(final VariableTree tree, final VisitorState state) {
final Symbol.VarSymbol sym = ASTHelpers.getSymbol(tree);
if (sym == null || sym.getKind() != ElementKind.FIELD) {
return NO_MATCH;
}
if (sym.getModifiers()
.containsAll(List.of(Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL))) {
return NO_MATCH;
}
if (!isSubtype(getType(tree), ORG_SLF4J_LOGGER.get(state), state)) {
return NO_MATCH;
}
Optional<SuggestedFix> fixes =
addModifiers(tree, state, Modifier.PRIVATE, Modifier.STATIC, Modifier.FINAL);
return buildDescription(tree)
.addFix(fixes.isPresent() ? fixes.get() : SuggestedFix.emptyFix())
.build();
}
}

@ -1,39 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class BannedMethodTest {
private CompilationTestHelper compilationHelper;
@BeforeEach
public void setup() {
compilationHelper = CompilationTestHelper.newInstance(BannedMethod.class, getClass());
}
@Test
public void bannedMethodsPositiveCases() {
compilationHelper.addSourceFile("BannedMethodPositiveCases.java").doTest();
}
@Test
public void bannedMethodsNegativeCases() {
compilationHelper.addSourceFile("BannedMethodNegativeCases.java").doTest();
}
}

@ -1,40 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DoNotCreateSecureRandomDirectlyTest {
private CompilationTestHelper compilationHelper;
@BeforeEach
public void setup() {
compilationHelper =
CompilationTestHelper.newInstance(DoNotCreateSecureRandomDirectly.class, getClass());
}
@Test
public void doNotCreateSecureRandomDirectlyPositiveCases() {
compilationHelper.addSourceFile("DoNotCreateSecureRandomDirectlyPositiveCases.java").doTest();
}
@Test
public void doNotCreateSecureRandomDirectlyNegativeCases() {
compilationHelper.addSourceFile("DoNotCreateSecureRandomDirectlyNegativeCases.java").doTest();
}
}

@ -1,40 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DoNotInvokeMessageDigestDirectlyTest {
private CompilationTestHelper compilationHelper;
@BeforeEach
public void setup() {
compilationHelper =
CompilationTestHelper.newInstance(DoNotInvokeMessageDigestDirectly.class, getClass());
}
@Test
public void doNotInvokeMessageDigestDirectlyPositiveCases() {
compilationHelper.addSourceFile("DoNotInvokeMessageDigestDirectlyPositiveCases.java").doTest();
}
@Test
public void doNotInvokeMessageDigestDirectlyNegativeCases() {
compilationHelper.addSourceFile("DoNotInvokeMessageDigestDirectlyNegativeCases.java").doTest();
}
}

@ -1,40 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class DoNotReturnNullOptionalsTest {
private CompilationTestHelper compilationHelper;
@BeforeEach
public void setup() {
compilationHelper =
CompilationTestHelper.newInstance(DoNotReturnNullOptionals.class, getClass());
}
@Test
public void doNotReturnNullPositiveCases() {
compilationHelper.addSourceFile("DoNotReturnNullOptionalsPositiveCases.java").doTest();
}
@Test
public void doNotReturnNullNegativeCases() {
compilationHelper.addSourceFile("DoNotReturnNullOptionalsNegativeCases.java").doTest();
}
}

@ -1,45 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class ExperimentalCliOptionMustBeCorrectlyDisplayedTest {
private CompilationTestHelper compilationHelper;
@BeforeEach
public void setup() {
compilationHelper =
CompilationTestHelper.newInstance(
ExperimentalCliOptionMustBeCorrectlyDisplayed.class, getClass());
}
@Test
public void experimentalCliOptionMustBeHiddenPositiveCases() {
compilationHelper
.addSourceFile("ExperimentalCliOptionMustBeCorrectlyDisplayedPositiveCases.java")
.doTest();
}
@Test
public void experimentalCliOptionMustBeHiddenNegativeCases() {
compilationHelper
.addSourceFile("ExperimentalCliOptionMustBeCorrectlyDisplayedNegativeCases.java")
.doTest();
}
}

@ -1,54 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class MethodInputParametersMustBeFinalTest {
private CompilationTestHelper compilationHelper;
@BeforeEach
public void setup() {
compilationHelper =
CompilationTestHelper.newInstance(MethodInputParametersMustBeFinal.class, getClass());
}
@Test
public void methodInputParametersMustBeFinalPositiveCases() {
compilationHelper.addSourceFile("MethodInputParametersMustBeFinalPositiveCases.java").doTest();
}
@Test
public void methodInputParametersMustBeFinalInterfacePositiveCases() {
compilationHelper
.addSourceFile("MethodInputParametersMustBeFinalInterfacePositiveCases.java")
.doTest();
}
@Test
public void methodInputParametersMustBeFinalNegativeCases() {
compilationHelper.addSourceFile("MethodInputParametersMustBeFinalNegativeCases.java").doTest();
}
@Test
public void methodInputParametersMustBeFinalInterfaceNegativeCases() {
compilationHelper
.addSourceFile("MethodInputParametersMustBeFinalInterfaceNegativeCases.java")
.doTest();
}
}

@ -1,40 +0,0 @@
/*
* Copyright Hyperledger Besu contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
class PreferCommonAnnotationsTest {
private CompilationTestHelper compilationHelper;
@BeforeEach
public void setup() {
compilationHelper =
CompilationTestHelper.newInstance(PreferCommonAnnotations.class, getClass());
}
@Test
void preferCommonAnnotationsPositiveCases() {
compilationHelper.addSourceFile("PreferCommonAnnotationsPositiveCases.java").doTest();
}
@Test
void preferCommonAnnotationsNegativeCases() {
compilationHelper.addSourceFile("PreferCommonAnnotationsNegativeCases.java").doTest();
}
}

@ -1,40 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.errorprone.CompilationTestHelper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
public class PrivateStaticFinalLoggersTest {
private CompilationTestHelper compilationHelper;
@BeforeEach
public void setup() {
compilationHelper =
CompilationTestHelper.newInstance(PrivateStaticFinalLoggers.class, getClass());
}
@Test
public void privateStaticFinalLoggersPositiveCases() {
compilationHelper.addSourceFile("PrivateStaticFinalLoggersPositiveCases.java").doTest();
}
@Test
public void privateStaticFinalLoggersNegativeCases() {
compilationHelper.addSourceFile("PrivateStaticFinalLoggersNegativeCases.java").doTest();
}
}

@ -1,29 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import java.util.Objects;
public class BannedMethodNegativeCases {
public void callsObjectsEquals() throws Exception {
Objects.equals("1", "1");
}
public void callsObjectsHashCode() throws Exception {
Objects.hash("1", "1");
}
}

@ -1,50 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import com.google.common.base.Objects;
public class BannedMethodPositiveCases {
public void callsObjectsEquals() throws Exception {
// BUG: Diagnostic contains: Do not use com.google.common.base.Objects methods, use
// java.util.Objects methods instead.
Objects.equal("1", "1");
}
public void callsObjectsHashCode() throws Exception {
// BUG: Diagnostic contains: Do not use com.google.common.base.Objects methods, use
// java.util.Objects methods instead.
Objects.hashCode("1", "1");
}
public void usesJUnitAssertions() throws Exception {
// BUG: Diagnostic contains: Do not use junit assertions. Use assertj assertions instead.
org.junit.Assert.assertEquals(1, 1);
// BUG: Diagnostic contains: Do not use junit assertions. Use assertj assertions instead.
org.junit.Assert.assertNotEquals(1, 2);
// BUG: Diagnostic contains: Do not use junit assertions. Use assertj assertions instead.
org.junit.Assert.assertTrue(true);
// BUG: Diagnostic contains: Do not use junit assertions. Use assertj assertions instead.
org.junit.Assert.assertFalse(false);
// BUG: Diagnostic contains: Do not use junit assertions. Use assertj assertions instead.
org.junit.Assert.assertNull(null);
// BUG: Diagnostic contains: Do not use junit assertions. Use assertj assertions instead.
org.junit.Assert.assertNotNull("foo");
// BUG: Diagnostic contains: Do not use junit assertions. Use assertj assertions instead.
org.junit.Assert.assertArrayEquals(new int[] {1}, new int[] {1});
}
}

@ -1,34 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import java.security.Provider;
import java.security.SecureRandom;
public class DoNotCreateSecureRandomDirectlyNegativeCases {
public void callsNonJRESecureRandomGetInstance() throws Exception {
TestSecureRandom.getInstance("");
TestSecureRandom.getInstance("", "");
TestSecureRandom.getInstance("", new Provider("", 0, "") {});
}
public void invokesNonJRESecureRandomConstructor() throws Exception {
new TestSecureRandom();
}
private class TestSecureRandom extends SecureRandom {}
}

@ -1,41 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import java.security.Provider;
import java.security.SecureRandom;
public class DoNotCreateSecureRandomDirectlyPositiveCases {
public void callsSecureRandomGetInstance() throws Exception {
// BUG: Diagnostic contains: Do not create SecureRandom directly.
SecureRandom.getInstance("");
// BUG: Diagnostic contains: Do not create SecureRandom directly.
SecureRandom.getInstance("", "");
// BUG: Diagnostic contains: Do not create SecureRandom directly.
SecureRandom.getInstance("", new Provider("", 0, "") {});
}
public void invokesSecureRandomConstructor() throws Exception {
// BUG: Diagnostic contains: Do not create SecureRandom directly.
new SecureRandom();
// BUG: Diagnostic contains: Do not create SecureRandom directly.
new SecureRandom(new byte[] {});
}
}

@ -1,26 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class DoNotInvokeMessageDigestDirectlyNegativeCases {
public void callsMessageDigestGetInstance() throws NoSuchAlgorithmException {
MessageDigest dig = null;
}
}

@ -1,26 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class DoNotInvokeMessageDigestDirectlyPositiveCases {
public void callsMessageDigestGetInstance() throws NoSuchAlgorithmException {
// BUG: Diagnostic contains: Do not invoke MessageDigest.getInstance directly.
MessageDigest dig = MessageDigest.getInstance("SHA-256");
}
}

@ -1,36 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import java.util.Optional;
import javax.annotation.Nullable;
public class DoNotReturnNullOptionalsNegativeCases {
public interface allInterfacesAreValid {
public Optional<Long> ExpectToBeOverridden();
}
public DoNotReturnNullOptionalsNegativeCases() {}
public Optional<Long> doesNotReturnNull() {
return Optional.of(3L);
}
@Nullable
public Optional<Long> returnsNullButAnnotatedWithNullable() {
return Optional.empty();
}
}

@ -1,35 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import java.util.Optional;
public class DoNotReturnNullOptionalsPositiveCases {
// BUG: Diagnostic contains: Do not return null optionals.
public Optional<Long> returnsNull() {
return null;
}
// BUG: Diagnostic contains: Do not return null optionals.
public Optional<Long> sometimesReturnsNull(boolean random) {
if (random) {
return null;
}
return Optional.of(2L);
}
}

@ -1,50 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import picocli.CommandLine;
public class ExperimentalCliOptionMustBeCorrectlyDisplayedNegativeCases {
@CommandLine.Option(
hidden = true,
names = {"--Xexperimental"})
private String experimental = "";
@CommandLine.Option(
hidden = false,
names = {"--notExperimental"})
private String notExperimental = "";
@CommandLine.Option(names = {"--notExperimental2"})
private String notExperimental2 = "";
private class AnotherClass {
@CommandLine.Option(names = {"--notExperimentalInAnotherClass"})
private String notExperimentalInAnotherClass = "";
@CommandLine.Option(
hidden = true,
names = {"--XexperimentalInAnotherClass"})
private String experimentalInAnotherClass = "";
}
private class BesuCommand {
@CommandLine.Option(names = {"--notExperimentalInBesuCommandClass"})
private String notExperimentalInBesuCommandClass = "";
}
}

@ -1,41 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import picocli.CommandLine;
public class ExperimentalCliOptionMustBeCorrectlyDisplayedPositiveCases {
// BUG: Diagnostic contains: Experimental options must be hidden and not present in the
// BesuCommand class.
@CommandLine.Option(
hidden = false,
names = {"--Xexperimental"})
private String experimental = "";
// BUG: Diagnostic contains: Experimental options must be hidden and not present in the
// BesuCommand class.
@CommandLine.Option(names = {"--Xexperimental2"})
private String experimental2 = "";
private class BesuCommand {
// BUG: Diagnostic contains: Experimental options must be hidden and not present in the
// BesuCommand class.
@CommandLine.Option(names = {"--XexperimentalInBesuCommandClass"})
private String experimentalInBesuCommandClass = "";
}
}

@ -1,40 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import java.util.Observable;
import java.util.Observer;
public interface MethodInputParametersMustBeFinalInterfaceNegativeCases {
void parameterCannotBeFinal(int value);
default void concreteMethod(final long value) {}
static void anotherConcreteMethod(final double value) {}
static Observer annonymousClass() {
return new Observer() {
@Override
public void update(final Observable o, final Object arg) {}
};
}
void methodAfterAnnonymousClass(int value);
enum Status {}
void methodAfterEnum(int value);
}

@ -1,24 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
public interface MethodInputParametersMustBeFinalInterfacePositiveCases {
// BUG: Diagnostic contains: Method input parameters must be final.
default void concreteMethod(int value) {}
// BUG: Diagnostic contains: Method input parameters must be final.
static void concreteStaticMethodsAreIncluded(int value) {}
}

@ -1,63 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import javax.annotation.processing.Generated;
public class MethodInputParametersMustBeFinalNegativeCases {
public void noInputParameters() {}
public void onlyPrimativeInputParameters(final long value) {}
public void onlyObjectInputParameters(final Object value) {}
public void mixedInputParameters(final Object value, final int anotherValue) {}
public interface allInterfacesAreValid {
void parameterCannotBeFinal(int value);
}
}
@Generated(
value = "test",
comments = "Every method is buggy, but ignored because the class has been tagged generated")
class MethodInputParametersMustBeFinalPositiveCasesBugGenerated1 {
public void primativeInputMethod(int value) {}
public void objectInputMethod(Object value) {}
public void mixedInputMethod(Object value, int anotherValue) {}
@Generated(
value = "test",
comments = "Every method is buggy, but ignored because the class has been tagged generated")
public abstract class abstractClassDefinition {
public void concreteMethodsAreIncluded(int value) {}
}
public void varArgsInputMethod(String... value) {}
}
@Generated(
value = "test",
comments = "Every method is buggy, but ignored because the class has been tagged generated")
class MethodInputParametersMustBeFinalPositiveCasesBugGenerated2 {
public void mixedInputMethodFirstFinal(final Object value, int anotherValue) {}
public void mixedInputMethodSecondFinal(Object value, final int anotherValue) {}
}

@ -1,41 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
public class MethodInputParametersMustBeFinalPositiveCases {
// BUG: Diagnostic contains: Method input parameters must be final.
public void primativeInputMethod(int value) {}
// BUG: Diagnostic contains: Method input parameters must be final.
public void objectInputMethod(Object value) {}
// BUG: Diagnostic contains: Method input parameters must be final.
public void mixedInputMethod(Object value, int anotherValue) {}
// BUG: Diagnostic contains: Method input parameters must be final.
public void mixedInputMethodFirstFinal(final Object value, int anotherValue) {}
// BUG: Diagnostic contains: Method input parameters must be final.
public void mixedInputMethodSecondFinal(Object value, final int anotherValue) {}
// BUG: Diagnostic contains: Method input parameters must be final.
public void varArgsInputMethod(String... value) {}
public abstract class abstractClassDefinition {
// BUG: Diagnostic contains: Method input parameters must be final.
public void concreteMethodsAreIncluded(int value) {}
}
}

@ -1,32 +0,0 @@
/*
* Copyright Hyperledger Besu contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import javax.annotation.Nonnull;
public class PreferCommonAnnotationsNegativeCases {
@Nonnull
public String getFoo() {
return "Foo";
}
// Fully Qualified Name is the "escape hatch"
@org.jetbrains.annotations.NotNull
public String getBar() {
return "Bar";
}
}

@ -1,27 +0,0 @@
/*
* Copyright Hyperledger Besu contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
// BUG: Diagnostic contains: Do not use org.jetbrains.annotations.NotNull use
import org.jetbrains.annotations.NotNull;
public class PreferCommonAnnotationsPositiveCases {
@NotNull
public String getFoo() {
return "Foo";
}
}

@ -1,25 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PrivateStaticFinalLoggersNegativeCases {
private static final Logger LOG =
LoggerFactory.getLogger(PrivateStaticFinalLoggersNegativeCases.class);
}

@ -1,25 +0,0 @@
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.errorpronechecks;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PrivateStaticFinalLoggersPositiveCases {
// BUG: Diagnostic contains: Logger classes should be private, static, and final.
private final Logger LOG = LoggerFactory.getLogger(PrivateStaticFinalLoggersPositiveCases.class);
}

@ -235,8 +235,7 @@ public class GraphQLHttpService {
private boolean hostIsInAllowlist(final String hostHeader) {
if (config.getHostsAllowlist().stream()
.anyMatch(
allowlistEntry -> allowlistEntry.toLowerCase().equals(hostHeader.toLowerCase()))) {
.anyMatch(allowlistEntry -> allowlistEntry.equalsIgnoreCase(hostHeader))) {
return true;
} else {
LOG.trace("Host not in allowlist: '{}'", hostHeader);

@ -330,7 +330,7 @@ public class Scalars {
if (input instanceof Number number) {
return number;
} else if (input instanceof String string) {
final String value = string.toLowerCase();
final String value = string.toLowerCase(Locale.ROOT);
if (value.startsWith("0x")) {
return Bytes.fromHexStringLenient(value).toLong();
} else {
@ -352,7 +352,7 @@ public class Scalars {
if (input instanceof IntValue intValue) {
return intValue.getValue().longValue();
} else if (input instanceof StringValue stringValue) {
final String value = stringValue.getValue().toLowerCase();
final String value = stringValue.getValue().toLowerCase(Locale.ROOT);
if (value.startsWith("0x")) {
return Bytes.fromHexStringLenient(value).toLong();
} else {

@ -524,8 +524,7 @@ public class JsonRpcHttpService {
private boolean hostIsInAllowlist(final String hostHeader) {
if (config.getHostsAllowlist().stream()
.anyMatch(
allowlistEntry -> allowlistEntry.toLowerCase().equals(hostHeader.toLowerCase()))) {
.anyMatch(allowlistEntry -> allowlistEntry.equalsIgnoreCase(hostHeader))) {
return true;
} else {
LOG.trace("Host not in allowlist: '{}'", hostHeader);

@ -18,6 +18,7 @@ import org.hyperledger.besu.ethereum.api.query.BlockchainQueries;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import org.hyperledger.besu.ethereum.core.ProcessableBlockHeader;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
@ -38,7 +39,7 @@ public class BlockParameter {
@JsonCreator
public BlockParameter(final String value) {
final String normalizedValue = value.toLowerCase();
final String normalizedValue = value.toLowerCase(Locale.ROOT);
switch (normalizedValue) {
case "earliest":

@ -18,6 +18,7 @@ import org.hyperledger.besu.config.JsonUtil;
import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.ethereum.core.BlockHeader;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalLong;
@ -44,7 +45,7 @@ public class BlockParameterOrBlockHash {
@JsonCreator
public BlockParameterOrBlockHash(final Object value) throws JsonProcessingException {
if (value instanceof String) {
final String normalizedValue = String.valueOf(value).toLowerCase();
final String normalizedValue = String.valueOf(value).toLowerCase(Locale.ROOT);
if (Objects.equals(normalizedValue, "earliest")) {
type = BlockParameterType.EARLIEST;

@ -29,6 +29,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.results.transaction.po
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
@ -82,7 +83,7 @@ public class PendingTransactionsParams {
} else if (!map.isEmpty()) {
final Map.Entry<String, String> foundEntry = map.entrySet().stream().findFirst().get();
final Predicate predicate =
Predicate.fromValue(foundEntry.getKey().toUpperCase())
Predicate.fromValue(foundEntry.getKey().toUpperCase(Locale.ROOT))
.orElseThrow(
() ->
new InvalidJsonRpcParameters(

@ -331,9 +331,7 @@ public class WebSocketService {
.map(
header ->
configuration.getHostsAllowlist().stream()
.anyMatch(
allowlistEntry ->
allowlistEntry.toLowerCase().equals(header.toLowerCase())))
.anyMatch(allowListEntry -> allowListEntry.equalsIgnoreCase(header)))
.orElse(false);
}
}

@ -43,6 +43,7 @@ import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
@ -1742,7 +1743,7 @@ public class JsonRpcHttpServiceTest extends JsonRpcHttpServiceTestBase {
assertThat(Long.decode(result.getString("timestamp"))).isEqualTo(header.getTimestamp());
assertThat(Long.decode(result.getString("number"))).isEqualTo(header.getNumber());
// Nonce is a data field and should represent 8 bytes exactly
final String nonceResult = result.getString("nonce").toLowerCase();
final String nonceResult = result.getString("nonce").toLowerCase(Locale.ROOT);
assertThat(nonceResult.length() == 18 && nonceResult.startsWith("0x")).isTrue();
assertThat(Long.parseUnsignedLong(nonceResult.substring(2), 16)).isEqualTo(header.getNonce());
assertThat(Hash.fromHexString(result.getString("hash"))).isEqualTo(header.getHash());

@ -32,6 +32,7 @@ dependencies {
api 'org.web3j:core'
annotationProcessor 'org.openjdk.jmh:jmh-generator-annprocess'
annotationProcessor 'org.hyperledger.besu:besu-errorprone-checks'
implementation project(':config')
implementation project(':crypto:algorithms')

@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.privacy.PrivateTransactionValidator;
import org.hyperledger.besu.evm.internal.EvmConfiguration;
import java.math.BigInteger;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.OptionalLong;
import java.util.TreeMap;
@ -126,7 +127,7 @@ public class ProtocolScheduleBuilder {
validateForkOrdering();
final TreeMap<Long, BuilderMapEntry> builders = buildMilestoneMap(specFactory);
final NavigableMap<Long, BuilderMapEntry> builders = buildMilestoneMap(specFactory);
// At this stage, all milestones are flagged with correct modifier, but ProtocolSpecs must be
// inserted _AT_ the modifier block entry.
@ -290,7 +291,7 @@ public class ProtocolScheduleBuilder {
return referenceForkBlock;
}
private TreeMap<Long, BuilderMapEntry> buildMilestoneMap(
private NavigableMap<Long, BuilderMapEntry> buildMilestoneMap(
final MainnetProtocolSpecFactory specFactory) {
return createMilestones(specFactory)
.flatMap(Optional::stream)

@ -168,16 +168,14 @@ public class PrivateTransactionReceipt {
if (obj == this) {
return true;
}
if (!(obj instanceof PrivateTransactionReceipt)) {
if (!(obj instanceof PrivateTransactionReceipt other)) {
return false;
}
final PrivateTransactionReceipt other = (PrivateTransactionReceipt) obj;
return logs.equals(other.getLogs())
&& status == other.status
&& output.equals(other.output)
&& revertReason.isPresent()
? revertReason.get().equals(other.revertReason.get())
: true;
return !logs.equals(other.getLogs())
|| status != other.status
|| !output.equals(other.output)
|| revertReason.isEmpty()
|| revertReason.get().equals(other.revertReason.get());
}
@Override

@ -82,39 +82,21 @@ public final class EthHashTest {
}
assertThat(Hex.toHexString(buffer.array()))
.isEqualTo(
new StringBuilder()
.append(
"7ce2991c951f7bf4c4c1bb119887ee07871eb5339d7b97b8588e85c742de90e5bafd5bbe6ce93a134fb6be9ad3e30db99d9528a2ea7846833f52e9ca119b6b54")
.append(
"8979480c46e19972bd0738779c932c1b43e665a2fd3122fc3ddb2691f353ceb0ed3e38b8f51fd55b6940290743563c9f8fa8822e611924657501a12aafab8a8d")
.append(
"88fb5fbae3a99d14792406672e783a06940a42799b1c38bc28715db6d37cb11f9f6b24e386dc52dd8c286bd8c36fa813dffe4448a9f56ebcbeea866b42f68d22")
.append(
"6c32aae4d695a23cab28fd74af53b0c2efcc180ceaaccc0b2e280103d097a03c1d1b0f0f26ce5f32a90238f9bc49f645db001ef9cd3d13d44743f841fad11a37")
.append(
"fa290c62c16042f703578921f30b9951465aae2af4a5dad43a7341d7b4a62750954965a47a1c3af638dc3495c4d62a9bab843168c9fc0114e79cffd1b2827b01")
.append(
"75d30ba054658f214e946cf24c43b40d3383fbb0493408e5c5392434ca21bbcf43200dfb876c713d201813934fa485f48767c5915745cf0986b1dc0f33e57748")
.append(
"bf483ee2aff4248dfe461ec0504a13628401020fc22638584a8f2f5206a13b2f233898c78359b21c8226024d0a7a93df5eb6c282bdbf005a4aab497e096f2847")
.append(
"76c71cee57932a8fb89f6d6b8743b60a4ea374899a94a2e0f218d5c55818cefb1790c8529a76dba31ebb0f4592d709b49587d2317970d39c086f18dd244291d9")
.append(
"eedb16705e53e3350591bd4ff4566a3595ac0f0ce24b5e112a3d033bc51b6fea0a92296dea7f5e20bf6ee6bc347d868fda193c395b9bb147e55e5a9f67cfe741")
.append(
"7eea7d699b155bd13804204df7ea91fa9249e4474dddf35188f77019c67d201e4c10d7079c5ad492a71afff9a23ca7e900ba7d1bdeaf3270514d8eb35eab8a0a")
.append(
"718bb7273aeb37768fa589ed8ab01fbf4027f4ebdbbae128d21e485f061c20183a9bc2e31edbda0727442e9d58eb0fe198440fe199e02e77c0f7b99973f1f74c")
.append(
"c9089a51ab96c94a84d66e6aa48b2d0a4543adb5a789039a2aa7b335ca85c91026c7d3c894da53ae364188c3fd92f78e01d080399884a47385aa792e38150cda")
.append(
"a8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995c")
.append(
"778401b94a2e66e6993ad67ad3ecdc2acb17779f1ea8606827ec92b11c728f8c3b6d3f04a3e6ed05ff81dd76d5dc5695a50377bc135aaf1671cf68b750315493")
.append(
"6c64510164d53312bf3c41740c7a237b05faf4a191bd8a95dafa068dbcf370255c725900ce5c934f36feadcfe55b687c440574c1f06f39d207a8553d39156a24")
.append(
"845f64fd8324bb85312979dead74f764c9677aab89801ad4f927f1c00f12e28f22422bb44200d1969d9ab377dd6b099dc6dbc3222e9321b2c1e84f8e2f07731c")
.toString());
"7ce2991c951f7bf4c4c1bb119887ee07871eb5339d7b97b8588e85c742de90e5bafd5bbe6ce93a134fb6be9ad3e30db99d9528a2ea7846833f52e9ca119b6b54"
+ "8979480c46e19972bd0738779c932c1b43e665a2fd3122fc3ddb2691f353ceb0ed3e38b8f51fd55b6940290743563c9f8fa8822e611924657501a12aafab8a8d"
+ "88fb5fbae3a99d14792406672e783a06940a42799b1c38bc28715db6d37cb11f9f6b24e386dc52dd8c286bd8c36fa813dffe4448a9f56ebcbeea866b42f68d22"
+ "6c32aae4d695a23cab28fd74af53b0c2efcc180ceaaccc0b2e280103d097a03c1d1b0f0f26ce5f32a90238f9bc49f645db001ef9cd3d13d44743f841fad11a37"
+ "fa290c62c16042f703578921f30b9951465aae2af4a5dad43a7341d7b4a62750954965a47a1c3af638dc3495c4d62a9bab843168c9fc0114e79cffd1b2827b01"
+ "75d30ba054658f214e946cf24c43b40d3383fbb0493408e5c5392434ca21bbcf43200dfb876c713d201813934fa485f48767c5915745cf0986b1dc0f33e57748"
+ "bf483ee2aff4248dfe461ec0504a13628401020fc22638584a8f2f5206a13b2f233898c78359b21c8226024d0a7a93df5eb6c282bdbf005a4aab497e096f2847"
+ "76c71cee57932a8fb89f6d6b8743b60a4ea374899a94a2e0f218d5c55818cefb1790c8529a76dba31ebb0f4592d709b49587d2317970d39c086f18dd244291d9"
+ "eedb16705e53e3350591bd4ff4566a3595ac0f0ce24b5e112a3d033bc51b6fea0a92296dea7f5e20bf6ee6bc347d868fda193c395b9bb147e55e5a9f67cfe741"
+ "7eea7d699b155bd13804204df7ea91fa9249e4474dddf35188f77019c67d201e4c10d7079c5ad492a71afff9a23ca7e900ba7d1bdeaf3270514d8eb35eab8a0a"
+ "718bb7273aeb37768fa589ed8ab01fbf4027f4ebdbbae128d21e485f061c20183a9bc2e31edbda0727442e9d58eb0fe198440fe199e02e77c0f7b99973f1f74c"
+ "c9089a51ab96c94a84d66e6aa48b2d0a4543adb5a789039a2aa7b335ca85c91026c7d3c894da53ae364188c3fd92f78e01d080399884a47385aa792e38150cda"
+ "a8620b2ebeca41fbc773bb837b5e724d6eb2de570d99858df0d7d97067fb8103b21757873b735097b35d3bea8fd1c359a9e8a63c1540c76c9784cf8d975e995c"
+ "778401b94a2e66e6993ad67ad3ecdc2acb17779f1ea8606827ec92b11c728f8c3b6d3f04a3e6ed05ff81dd76d5dc5695a50377bc135aaf1671cf68b750315493"
+ "6c64510164d53312bf3c41740c7a237b05faf4a191bd8a95dafa068dbcf370255c725900ce5c934f36feadcfe55b687c440574c1f06f39d207a8553d39156a24"
+ "845f64fd8324bb85312979dead74f764c9677aab89801ad4f927f1c00f12e28f22422bb44200d1969d9ab377dd6b099dc6dbc3222e9321b2c1e84f8e2f07731c");
}
}

@ -24,6 +24,7 @@ import org.hyperledger.besu.ethereum.worldstate.StateTrieAccountValue;
import java.math.BigInteger;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.TreeMap;
@ -133,7 +134,7 @@ public final class AccountRangeMessage extends AbstractSnapMessageData {
@Value.Immutable
public interface AccountRangeData {
TreeMap<Bytes32, Bytes> accounts();
NavigableMap<Bytes32, Bytes> accounts();
ArrayDeque<Bytes> proofs();
}

@ -22,6 +22,7 @@ import org.hyperledger.besu.ethereum.rlp.RLPInput;
import java.math.BigInteger;
import java.util.List;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.TreeMap;
@ -49,13 +50,13 @@ public final class StorageRangeMessage extends AbstractSnapMessageData {
}
public static StorageRangeMessage create(
final ArrayDeque<TreeMap<Bytes32, Bytes>> slots, final List<Bytes> proof) {
final ArrayDeque<NavigableMap<Bytes32, Bytes>> slots, final List<Bytes> proof) {
return create(Optional.empty(), slots, proof);
}
public static StorageRangeMessage create(
final Optional<BigInteger> requestId,
final ArrayDeque<TreeMap<Bytes32, Bytes>> slots,
final ArrayDeque<NavigableMap<Bytes32, Bytes>> slots,
final List<Bytes> proof) {
final BytesValueRLPOutput tmp = new BytesValueRLPOutput();
tmp.startList();
@ -88,7 +89,7 @@ public final class StorageRangeMessage extends AbstractSnapMessageData {
}
public SlotRangeData slotsData(final boolean withRequestId) {
final ArrayDeque<TreeMap<Bytes32, Bytes>> slots = new ArrayDeque<>();
final ArrayDeque<NavigableMap<Bytes32, Bytes>> slots = new ArrayDeque<>();
final ArrayDeque<Bytes> proofs = new ArrayDeque<>();
final RLPInput input = new BytesValueRLPInput(data, false);
input.enterList();
@ -120,7 +121,7 @@ public final class StorageRangeMessage extends AbstractSnapMessageData {
@Value.Immutable
public interface SlotRangeData {
ArrayDeque<TreeMap<Bytes32, Bytes>> slots();
ArrayDeque<NavigableMap<Bytes32, Bytes>> slots();
ArrayDeque<Bytes> proofs();
}

@ -15,6 +15,7 @@
package org.hyperledger.besu.ethereum.eth.sync;
import java.util.EnumSet;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
@ -34,10 +35,10 @@ public enum SyncMode {
public String normalize() {
if (this.toString().startsWith("X_")) {
// removes X_ at the beginning
return StringUtils.capitalize(this.toString().substring(2).toLowerCase());
return StringUtils.capitalize(this.toString().substring(2).toLowerCase(Locale.ROOT));
}
return StringUtils.capitalize(this.toString().toLowerCase());
return StringUtils.capitalize(this.toString().toLowerCase(Locale.ROOT));
}
public static boolean isFullSync(final SyncMode syncMode) {

@ -47,6 +47,7 @@ import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.OptionalLong;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.function.Predicate;
@ -77,7 +78,7 @@ public class SnapWorldDownloadState extends WorldDownloadState<SnapDataRequest>
protected final InMemoryTasksPriorityQueues<SnapDataRequest>
pendingStorageFlatDatabaseHealingRequests = new InMemoryTasksPriorityQueues<>();
private HashSet<Bytes> accountsHealingList = new HashSet<>();
private Set<Bytes> accountsHealingList = new HashSet<>();
private DynamicPivotBlockSelector pivotBlockSelector;
private final SnapSyncStatePersistenceManager snapContext;
@ -304,7 +305,7 @@ public class SnapWorldDownloadState extends WorldDownloadState<SnapDataRequest>
}
}
public synchronized void setAccountsHealingList(final HashSet<Bytes> addAccountToHealingList) {
public synchronized void setAccountsHealingList(final Set<Bytes> addAccountToHealingList) {
this.accountsHealingList = addAccountToHealingList;
}
@ -322,7 +323,7 @@ public class SnapWorldDownloadState extends WorldDownloadState<SnapDataRequest>
}
}
public HashSet<Bytes> getAccountsHealingList() {
public Set<Bytes> getAccountsHealingList() {
return accountsHealingList;
}

@ -36,10 +36,10 @@ import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.services.tasks.InMemoryTasksPriorityQueues;
import java.time.Clock;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Function;
@ -154,7 +154,7 @@ public class SnapWorldStateDownloader implements WorldStateDownloader {
final List<AccountRangeDataRequest> currentAccountRange =
snapContext.getCurrentAccountRange();
final HashSet<Bytes> inconsistentAccounts = snapContext.getAccountsHealingList();
final Set<Bytes> inconsistentAccounts = snapContext.getAccountsHealingList();
if (!currentAccountRange.isEmpty()) { // continue to download worldstate ranges
newDownloadState.setAccountsHealingList(inconsistentAccounts);

@ -28,6 +28,7 @@ import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
@ -72,7 +73,9 @@ public class StackTrie {
}
public void addElement(
final Bytes32 taskIdentifier, final List<Bytes> proofs, final TreeMap<Bytes32, Bytes> keys) {
final Bytes32 taskIdentifier,
final List<Bytes> proofs,
final NavigableMap<Bytes32, Bytes> keys) {
this.elementsCount.addAndGet(keys.size());
this.elements.put(
taskIdentifier, ImmutableTaskElement.builder().proofs(proofs).keys(keys).build());
@ -183,7 +186,7 @@ public class StackTrie {
}
@Value.Default
public TreeMap<Bytes32, Bytes> keys() {
public NavigableMap<Bytes32, Bytes> keys() {
return new TreeMap<>();
}
}

@ -28,6 +28,7 @@ import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@ -127,7 +128,7 @@ public class SnapSyncStatePersistenceManager {
.collect(Collectors.toList());
}
public HashSet<Bytes> getAccountsHealingList() {
public Set<Bytes> getAccountsHealingList() {
return healContext
.streamValuesFromKeysThat(notEqualsTo(SNAP_ACCOUNT_HEALING_LIST_INDEX))
.collect(Collectors.toCollection(HashSet::new));

@ -40,8 +40,8 @@ import org.hyperledger.besu.ethereum.worldstate.WorldStateStorageCoordinator;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
@ -155,7 +155,7 @@ public class AccountRangeDataRequest extends SnapDataRequest {
public void addResponse(
final WorldStateProofProvider worldStateProofProvider,
final TreeMap<Bytes32, Bytes> accounts,
final NavigableMap<Bytes32, Bytes> accounts,
final ArrayDeque<Bytes> proofs) {
if (!accounts.isEmpty() || !proofs.isEmpty()) {
if (!worldStateProofProvider.isValidRangeProof(
@ -226,7 +226,7 @@ public class AccountRangeDataRequest extends SnapDataRequest {
}
@VisibleForTesting
public TreeMap<Bytes32, Bytes> getAccounts() {
public NavigableMap<Bytes32, Bytes> getAccounts() {
return stackTrie.getElement(startKeyHash).keys();
}

@ -31,8 +31,8 @@ import org.hyperledger.besu.ethereum.worldstate.WorldStateKeyValueStorage;
import org.hyperledger.besu.ethereum.worldstate.WorldStateStorageCoordinator;
import org.hyperledger.besu.services.tasks.TasksPriorityProvider;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Stream;
@ -93,7 +93,7 @@ public abstract class SnapDataRequest implements TasksPriorityProvider {
}
public static AccountTrieNodeHealingRequest createAccountTrieNodeDataRequest(
final Hash hash, final Bytes location, final HashSet<Bytes> inconsistentAccounts) {
final Hash hash, final Bytes location, final Set<Bytes> inconsistentAccounts) {
return new AccountTrieNodeHealingRequest(hash, hash, location, inconsistentAccounts);
}
@ -101,7 +101,7 @@ public abstract class SnapDataRequest implements TasksPriorityProvider {
final Hash hash,
final Hash rootHash,
final Bytes location,
final HashSet<Bytes> inconsistentAccounts) {
final Set<Bytes> inconsistentAccounts) {
return new AccountTrieNodeHealingRequest(hash, rootHash, location, inconsistentAccounts);
}

@ -38,8 +38,8 @@ import org.hyperledger.besu.ethereum.worldstate.WorldStateStorageCoordinator;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.TreeMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
@ -129,7 +129,7 @@ public class StorageRangeDataRequest extends SnapDataRequest {
public void addResponse(
final SnapWorldDownloadState downloadState,
final WorldStateProofProvider worldStateProofProvider,
final TreeMap<Bytes32, Bytes> slots,
final NavigableMap<Bytes32, Bytes> slots,
final ArrayDeque<Bytes> proofs) {
if (!slots.isEmpty() || !proofs.isEmpty()) {
if (!worldStateProofProvider.isValidRangeProof(
@ -202,7 +202,7 @@ public class StorageRangeDataRequest extends SnapDataRequest {
return storageRoot;
}
public TreeMap<Bytes32, Bytes> getSlots() {
public NavigableMap<Bytes32, Bytes> getSlots() {
return stackTrie.getElement(startKeyHash).keys();
}

@ -41,6 +41,7 @@ import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Stream;
@ -58,9 +59,9 @@ public class AccountFlatDatabaseHealingRangeRequest extends SnapDataRequest {
private final Bytes32 startKeyHash;
private final Bytes32 endKeyHash;
private TreeMap<Bytes32, Bytes> existingAccounts;
private NavigableMap<Bytes32, Bytes> existingAccounts;
private TreeMap<Bytes32, Bytes> flatDbAccounts;
private NavigableMap<Bytes32, Bytes> flatDbAccounts;
private boolean isProofValid;
public AccountFlatDatabaseHealingRangeRequest(
@ -132,7 +133,7 @@ public class AccountFlatDatabaseHealingRangeRequest extends SnapDataRequest {
public void addLocalData(
final WorldStateProofProvider worldStateProofProvider,
final TreeMap<Bytes32, Bytes> accounts,
final NavigableMap<Bytes32, Bytes> accounts,
final ArrayDeque<Bytes> proofs) {
if (!accounts.isEmpty() && !proofs.isEmpty()) {
// very proof in order to check if the local flat database is valid or not

@ -34,6 +34,7 @@ import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;
@ -43,13 +44,13 @@ import org.apache.tuweni.bytes.Bytes32;
/** Represents a healing request for an account trie node. */
public class AccountTrieNodeHealingRequest extends TrieNodeHealingRequest {
private final HashSet<Bytes> inconsistentAccounts;
private final Set<Bytes> inconsistentAccounts;
public AccountTrieNodeHealingRequest(
final Hash hash,
final Hash originalRootHash,
final Bytes location,
final HashSet<Bytes> inconsistentAccounts) {
final Set<Bytes> inconsistentAccounts) {
super(hash, originalRootHash, location);
this.inconsistentAccounts = inconsistentAccounts;
}
@ -89,7 +90,7 @@ public class AccountTrieNodeHealingRequest extends TrieNodeHealingRequest {
childHash, getRootHash(), location, getSubLocation(location));
}
private HashSet<Bytes> getSubLocation(final Bytes location) {
private Set<Bytes> getSubLocation(final Bytes location) {
final HashSet<Bytes> foundAccountsToHeal = new HashSet<>();
for (Bytes account : inconsistentAccounts) {
if (account.commonPrefixLength(location) == location.size()) {

@ -36,6 +36,7 @@ import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.function.Function;
import java.util.stream.Stream;
@ -56,7 +57,7 @@ public class StorageFlatDatabaseHealingRangeRequest extends SnapDataRequest {
private final Bytes32 storageRoot;
private final Bytes32 startKeyHash;
private final Bytes32 endKeyHash;
private TreeMap<Bytes32, Bytes> slots;
private NavigableMap<Bytes32, Bytes> slots;
private boolean isProofValid;
public StorageFlatDatabaseHealingRangeRequest(
@ -120,7 +121,7 @@ public class StorageFlatDatabaseHealingRangeRequest extends SnapDataRequest {
public void addLocalData(
final WorldStateProofProvider worldStateProofProvider,
final TreeMap<Bytes32, Bytes> slots,
final NavigableMap<Bytes32, Bytes> slots,
final ArrayDeque<Bytes> proofs) {
if (!slots.isEmpty() && !proofs.isEmpty()) {
// very proof in order to check if the local flat database is valid or not

@ -25,7 +25,6 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionPoolMetrics;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiFunction;
import java.util.function.Predicate;
@ -140,7 +139,7 @@ public abstract class AbstractPrioritizedTransactions extends AbstractSequential
@Override
protected void internalConsistencyCheck(
final Map<Address, TreeMap<Long, PendingTransaction>> prevLayerTxsBySender) {
final Map<Address, NavigableMap<Long, PendingTransaction>> prevLayerTxsBySender) {
super.internalConsistencyCheck(prevLayerTxsBySender);
final var controlOrderByFee = new TreeSet<>(this::compareByFee);

@ -27,7 +27,6 @@ import java.util.Map;
import java.util.NavigableMap;
import java.util.OptionalLong;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.BiFunction;
public abstract class AbstractSequentialTransactionsLayer extends AbstractTransactionsLayer {
@ -142,7 +141,7 @@ public abstract class AbstractSequentialTransactionsLayer extends AbstractTransa
@Override
protected void internalConsistencyCheck(
final Map<Address, TreeMap<Long, PendingTransaction>> prevLayerTxsBySender) {
final Map<Address, NavigableMap<Long, PendingTransaction>> prevLayerTxsBySender) {
txsBySender.values().stream()
.filter(senderTxs -> senderTxs.size() > 1)
.map(NavigableMap::entrySet)

@ -569,7 +569,7 @@ public abstract class AbstractTransactionsLayer implements TransactionsLayer {
protected abstract String internalLogStats();
boolean consistencyCheck(
final Map<Address, TreeMap<Long, PendingTransaction>> prevLayerTxsBySender) {
final Map<Address, NavigableMap<Long, PendingTransaction>> prevLayerTxsBySender) {
final BinaryOperator<PendingTransaction> noMergeExpected =
(a, b) -> {
throw new IllegalArgumentException();
@ -606,7 +606,7 @@ public abstract class AbstractTransactionsLayer implements TransactionsLayer {
}
protected abstract void internalConsistencyCheck(
final Map<Address, TreeMap<Long, PendingTransaction>> prevLayerTxsBySender);
final Map<Address, NavigableMap<Long, PendingTransaction>> prevLayerTxsBySender);
public BlobCache getBlobCache() {
return blobCache;

@ -33,7 +33,6 @@ import java.util.Map;
import java.util.NavigableMap;
import java.util.NavigableSet;
import java.util.Optional;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiFunction;
import java.util.function.Predicate;
@ -220,7 +219,7 @@ public class ReadyTransactions extends AbstractSequentialTransactionsLayer {
@Override
protected void internalConsistencyCheck(
final Map<Address, TreeMap<Long, PendingTransaction>> prevLayerTxsBySender) {
final Map<Address, NavigableMap<Long, PendingTransaction>> prevLayerTxsBySender) {
super.internalConsistencyCheck(prevLayerTxsBySender);
final var minNonceBySender =
@ -241,7 +240,6 @@ public class ReadyTransactions extends AbstractSequentialTransactionsLayer {
: "orderByMaxFee does not match pendingTransactions";
}
assert itCurrent.hasNext() == false
: "orderByMaxFee has more elements than pendingTransactions";
assert !itCurrent.hasNext() : "orderByMaxFee has more elements than pendingTransactions";
}
}

@ -39,7 +39,6 @@ import java.util.NavigableSet;
import java.util.Objects;
import java.util.OptionalLong;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.function.BiFunction;
import java.util.function.Predicate;
@ -404,7 +403,7 @@ public class SparseTransactions extends AbstractTransactionsLayer {
@Override
protected void internalConsistencyCheck(
final Map<Address, TreeMap<Long, PendingTransaction>> prevLayerTxsBySender) {
final Map<Address, NavigableMap<Long, PendingTransaction>> prevLayerTxsBySender) {
txsBySender.values().stream()
.filter(senderTxs -> senderTxs.size() > 1)
.map(NavigableMap::entrySet)

@ -25,6 +25,7 @@ import org.hyperledger.besu.ethereum.eth.transactions.TransactionAddedResult;
import org.hyperledger.besu.ethereum.mainnet.feemarket.FeeMarket;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.OptionalLong;
@ -106,7 +107,7 @@ public interface TransactionsLayer {
private final String label;
RemovalReason() {
this.label = name().toLowerCase();
this.label = name().toLowerCase(Locale.ROOT);
}
public String label() {

@ -20,6 +20,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.wire.RawMessage;
import java.util.ArrayList;
import java.util.List;
import java.util.NavigableMap;
import java.util.TreeMap;
import kotlin.collections.ArrayDeque;
@ -33,7 +34,7 @@ public final class StorageRangeMessageTest {
@Test
public void roundTripTest() {
final ArrayDeque<TreeMap<Bytes32, Bytes>> keys = new ArrayDeque<>();
final ArrayDeque<NavigableMap<Bytes32, Bytes>> keys = new ArrayDeque<>();
final TreeMap<Bytes32, Bytes> storage = new TreeMap<>();
storage.put(Hash.wrap(Bytes32.leftPad(Bytes.of(1))), Bytes32.random());
keys.add(storage);

@ -36,6 +36,7 @@ import org.hyperledger.besu.evm.gascalculator.ShanghaiGasCalculator;
import org.hyperledger.besu.evm.precompile.PrecompiledContract;
import java.io.PrintStream;
import java.util.Locale;
import java.util.concurrent.TimeUnit;
import com.google.common.base.Stopwatch;
@ -127,7 +128,7 @@ public abstract class BenchmarkExecutor {
* @return a gas calculator
*/
public static GasCalculator gasCalculatorForFork(final String fork) {
return switch (EvmSpecVersion.valueOf(fork.toUpperCase())) {
return switch (EvmSpecVersion.valueOf(fork.toUpperCase(Locale.ROOT))) {
case HOMESTEAD -> new HomesteadGasCalculator();
case FRONTIER -> new FrontierGasCalculator();
case BYZANTIUM -> new ByzantiumGasCalculator();

@ -14,6 +14,8 @@
*/
package org.hyperledger.besu.ethereum.p2p.discovery;
import java.util.Locale;
/** The status of a {@link DiscoveryPeer}, in relation to the peer discovery state machine. */
public enum PeerDiscoveryStatus {
@ -40,6 +42,6 @@ public enum PeerDiscoveryStatus {
@Override
public String toString() {
return name().toLowerCase();
return name().toLowerCase(Locale.ROOT);
}
}

@ -23,6 +23,7 @@ import org.hyperledger.besu.util.NetworkUtility;
import java.net.InetAddress;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.Locale;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
@ -157,7 +158,7 @@ public class EnodeURLImpl implements EnodeURL {
public static Bytes parseNodeId(final String nodeId) {
int expectedSize = EnodeURLImpl.NODE_ID_SIZE * 2;
if (nodeId.toLowerCase().startsWith("0x")) {
if (nodeId.toLowerCase(Locale.ROOT).startsWith("0x")) {
expectedSize += 2;
}
checkArgument(

@ -84,7 +84,7 @@ public class Capability {
}
@Override
/** Returned string is sanitized since it contains user input */
// Returned string is sanitized since it contains user input
public String toString() {
return Encode.forJava(name) + "/" + version;
}

@ -118,7 +118,7 @@ public class PeerInfo implements Comparable<PeerInfo> {
}
@Override
/** Returned string is sanitized since it contains user input */
// Returned string is sanitized since it contains user input
public String toString() {
final StringBuilder sb = new StringBuilder("PeerInfo{");
sb.append("version=").append(version);

@ -21,7 +21,6 @@ import org.hyperledger.besu.ethereum.p2p.discovery.internal.MockPeerDiscoveryAge
import org.hyperledger.besu.ethereum.p2p.discovery.internal.Packet;
import java.util.Collections;
import java.util.concurrent.atomic.AtomicLong;
import org.junit.jupiter.api.Test;
@ -41,8 +40,8 @@ public class PeerDiscoveryTimestampsTest {
final Packet pong = helper.createPongPacket(agent, Hash.hash(agentPing.getHash()));
helper.sendMessageBetweenAgents(testAgent, agent, pong);
final AtomicLong lastSeen = new AtomicLong();
final AtomicLong firstDiscovered = new AtomicLong();
long lastSeen;
long firstDiscovered;
assertThat(agent.streamDiscoveredPeers()).hasSize(1);
@ -50,16 +49,16 @@ public class PeerDiscoveryTimestampsTest {
assertThat(p.getLastSeen()).isGreaterThan(0);
assertThat(p.getFirstDiscovered()).isGreaterThan(0);
lastSeen.set(p.getLastSeen());
firstDiscovered.set(p.getFirstDiscovered());
lastSeen = p.getLastSeen();
firstDiscovered = p.getFirstDiscovered();
helper.sendMessageBetweenAgents(testAgent, agent, testAgentPing);
assertThat(agent.streamDiscoveredPeers()).hasSize(1);
p = agent.streamDiscoveredPeers().iterator().next();
assertThat(p.getLastSeen()).isGreaterThan(lastSeen.get());
assertThat(p.getFirstDiscovered()).isEqualTo(firstDiscovered.get());
assertThat(p.getLastSeen()).isGreaterThan(lastSeen);
assertThat(p.getFirstDiscovered()).isEqualTo(firstDiscovered);
}
@Test
@ -74,9 +73,9 @@ public class PeerDiscoveryTimestampsTest {
assertThat(agent.streamDiscoveredPeers()).hasSize(1);
final AtomicLong lastContacted = new AtomicLong();
final AtomicLong lastSeen = new AtomicLong();
final AtomicLong firstDiscovered = new AtomicLong();
final long lastContacted;
final long lastSeen;
final long firstDiscovered;
DiscoveryPeer peer = agent.streamDiscoveredPeers().iterator().next();
final long lc = peer.getLastContacted();
@ -87,9 +86,9 @@ public class PeerDiscoveryTimestampsTest {
assertThat(ls).isGreaterThan(0);
assertThat(fd).isGreaterThan(0);
lastContacted.set(lc);
lastSeen.set(ls);
firstDiscovered.set(fd);
lastContacted = lc;
lastSeen = ls;
firstDiscovered = fd;
// Send another packet and ensure that timestamps are updated accordingly.
// Sleep beforehand to make sure timestamps will be different.
@ -102,8 +101,8 @@ public class PeerDiscoveryTimestampsTest {
peer = agent.streamDiscoveredPeers().iterator().next();
assertThat(peer.getLastContacted()).isGreaterThan(lastContacted.get());
assertThat(peer.getLastSeen()).isGreaterThan(lastSeen.get());
assertThat(peer.getFirstDiscovered()).isEqualTo(firstDiscovered.get());
assertThat(peer.getLastContacted()).isGreaterThan(lastContacted);
assertThat(peer.getLastSeen()).isGreaterThan(lastSeen);
assertThat(peer.getFirstDiscovered()).isEqualTo(firstDiscovered);
}
}

@ -19,6 +19,7 @@ import org.hyperledger.besu.ethereum.p2p.rlpx.ConnectCallback;
import org.hyperledger.besu.ethereum.p2p.rlpx.wire.messages.DisconnectMessage;
import org.hyperledger.besu.util.Subscribers;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;
@ -58,7 +59,7 @@ public class MockConnectionInitializer implements ConnectionInitializer {
@Override
public CompletableFuture<InetSocketAddress> start() {
final InetSocketAddress socketAddress =
new InetSocketAddress("127.0.0.1", NEXT_PORT.incrementAndGet());
new InetSocketAddress(InetAddress.getLoopbackAddress(), NEXT_PORT.incrementAndGet());
return CompletableFuture.completedFuture(socketAddress);
}

@ -55,6 +55,7 @@ import org.hyperledger.besu.ethereum.rlp.RLPException;
import org.hyperledger.besu.metrics.noop.NoOpMetricsSystem;
import org.hyperledger.besu.plugin.data.EnodeURL;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
@ -92,7 +93,8 @@ public class DeFramerTest {
private final PeerConnection peerConnection = mock(PeerConnection.class);
private final CompletableFuture<PeerConnection> connectFuture = new CompletableFuture<>();
private final int remotePort = 12345;
private final InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", remotePort);
private final InetSocketAddress remoteAddress =
new InetSocketAddress(InetAddress.getLoopbackAddress(), remotePort);
private final int p2pVersion = 5;
private final String clientId = "abc";

@ -188,6 +188,7 @@ public class ReferenceTestBlockchain implements Blockchain {
}
@Override
@SuppressWarnings("unused")
public Comparator<BlockHeader> getBlockChoiceRule() {
return (a, b) -> {
throw new NonDeterministicOperationException(

@ -22,6 +22,7 @@ import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.NavigableMap;
import java.util.Optional;
import java.util.TreeMap;
import java.util.function.Function;
@ -43,7 +44,7 @@ public class RangeManager {
private RangeManager() {}
public static int getRangeCount(
final Bytes32 min, final Bytes32 max, final TreeMap<Bytes32, Bytes> items) {
final Bytes32 min, final Bytes32 max, final NavigableMap<Bytes32, Bytes> items) {
if (min.equals(MIN_RANGE) && max.equals(MAX_RANGE)) {
return MAX_RANGE
.toUnsignedBigInteger()
@ -120,7 +121,7 @@ public class RangeManager {
public static Optional<Bytes32> findNewBeginElementInRange(
final Bytes32 worldstateRootHash,
final List<Bytes> proofs,
final TreeMap<Bytes32, Bytes> receivedKeys,
final NavigableMap<Bytes32, Bytes> receivedKeys,
final Bytes32 endKeyHash) {
if (receivedKeys.isEmpty() || receivedKeys.lastKey().compareTo(endKeyHash) >= 0) {
return Optional.empty();

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save