Fix javadocs to allow build to pass in JDK 17 (#4834)

- Added missing javadocs so that javadoc doclint passes against JDK 17 (invoke by Besu gradle build).
- Exclude following packages from javadoc lint:
org.hyperledger.besu.privacy.contracts.generated
org.hyperledger.besu.tests.acceptance.*
- Temporarily exclude ethereum and evm submodule for doc lint checks.
- Run the javadoc task using GitHub actions (use Java 17) to report any javadoc errors during the PR builds
- Updating plugin-api build.gradle with new hash as javadoc comments caused it to change

Signed-off-by: Usman Saleem <usman@usmans.info>
pull/4963/head
Usman Saleem 2 years ago committed by GitHub
parent aef335cfcf
commit 9eb32836b7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      .circleci/config.yml
  2. 14
      .github/workflows/checks.yml
  3. 6
      besu/src/main/java/org/hyperledger/besu/Besu.java
  4. 15
      besu/src/main/java/org/hyperledger/besu/BesuInfo.java
  5. 60
      besu/src/main/java/org/hyperledger/besu/Runner.java
  6. 270
      besu/src/main/java/org/hyperledger/besu/RunnerBuilder.java
  7. 12
      besu/src/main/java/org/hyperledger/besu/chainexport/BlockExporter.java
  8. 6
      besu/src/main/java/org/hyperledger/besu/chainexport/RlpBlockExporter.java
  9. 11
      besu/src/main/java/org/hyperledger/besu/chainimport/JsonBlockImporter.java
  10. 20
      besu/src/main/java/org/hyperledger/besu/chainimport/RlpBlockImporter.java
  11. 44
      besu/src/main/java/org/hyperledger/besu/chainimport/internal/BlockData.java
  12. 11
      besu/src/main/java/org/hyperledger/besu/chainimport/internal/ChainData.java
  13. 24
      besu/src/main/java/org/hyperledger/besu/chainimport/internal/TransactionData.java
  14. 132
      besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java
  15. 53
      besu/src/main/java/org/hyperledger/besu/cli/ConfigurationOverviewBuilder.java
  16. 39
      besu/src/main/java/org/hyperledger/besu/cli/DefaultCommandValues.java
  17. 7
      besu/src/main/java/org/hyperledger/besu/cli/NetworkDeprecationMessage.java
  18. 76
      besu/src/main/java/org/hyperledger/besu/cli/config/EthNetworkConfig.java
  19. 42
      besu/src/main/java/org/hyperledger/besu/cli/config/NetworkName.java
  20. 1
      besu/src/main/java/org/hyperledger/besu/cli/converter/FractionConverter.java
  21. 17
      besu/src/main/java/org/hyperledger/besu/cli/converter/MetricCategoryConverter.java
  22. 1
      besu/src/main/java/org/hyperledger/besu/cli/converter/PercentageConverter.java
  23. 6
      besu/src/main/java/org/hyperledger/besu/cli/converter/exception/FractionConversionException.java
  24. 6
      besu/src/main/java/org/hyperledger/besu/cli/converter/exception/PercentageConversionException.java
  25. 6
      besu/src/main/java/org/hyperledger/besu/cli/converter/exception/RpcApisConversionException.java
  26. 2
      besu/src/main/java/org/hyperledger/besu/cli/custom/CorsAllowedOriginsProperty.java
  27. 7
      besu/src/main/java/org/hyperledger/besu/cli/custom/EnodeToURIPropertyConverter.java
  28. 2
      besu/src/main/java/org/hyperledger/besu/cli/custom/JsonRPCAllowlistHostsProperty.java
  29. 9
      besu/src/main/java/org/hyperledger/besu/cli/custom/RpcAuthFileValidator.java
  30. 1
      besu/src/main/java/org/hyperledger/besu/cli/error/BesuExecutionExceptionHandler.java
  31. 6
      besu/src/main/java/org/hyperledger/besu/cli/error/BesuParameterExceptionHandler.java
  32. 1
      besu/src/main/java/org/hyperledger/besu/cli/logging/BesuLoggingConfigurationFactory.java
  33. 7
      besu/src/main/java/org/hyperledger/besu/cli/logging/XmlExtensionConfiguration.java
  34. 43
      besu/src/main/java/org/hyperledger/besu/cli/options/OptionParser.java
  35. 11
      besu/src/main/java/org/hyperledger/besu/cli/options/stable/DataStorageOptions.java
  36. 16
      besu/src/main/java/org/hyperledger/besu/cli/options/stable/EthstatsOptions.java
  37. 18
      besu/src/main/java/org/hyperledger/besu/cli/options/stable/LoggingLevelOption.java
  38. 11
      besu/src/main/java/org/hyperledger/besu/cli/options/stable/NodePrivateKeyFileOption.java
  39. 13
      besu/src/main/java/org/hyperledger/besu/cli/options/stable/P2PTLSConfigOptions.java
  40. 18
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/ChainPruningOptions.java
  41. 22
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/DnsOptions.java
  42. 12
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/EthProtocolOptions.java
  43. 7
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/EvmOptions.java
  44. 27
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/IpcOptions.java
  45. 16
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/LauncherOptions.java
  46. 12
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/MetricsCLIOptions.java
  47. 36
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/MiningOptions.java
  48. 16
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/NatOptions.java
  49. 26
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/NativeLibraryOptions.java
  50. 13
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/NetworkingOptions.java
  51. 22
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/PkiBlockCreationOptions.java
  52. 11
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/PrivacyPluginOptions.java
  53. 16
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/RPCOptions.java
  54. 17
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/SynchronizerOptions.java
  55. 12
      besu/src/main/java/org/hyperledger/besu/cli/options/unstable/TransactionPoolOptions.java
  56. 7
      besu/src/main/java/org/hyperledger/besu/cli/presynctasks/PreSynchronizationTask.java
  57. 11
      besu/src/main/java/org/hyperledger/besu/cli/presynctasks/PreSynchronizationTaskRunner.java
  58. 7
      besu/src/main/java/org/hyperledger/besu/cli/presynctasks/PrivateDatabaseMigrationPreSyncTask.java
  59. 10
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/PasswordSubCommand.java
  60. 20
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/PublicKeySubCommand.java
  61. 2
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/RetestethSubCommand.java
  62. 12
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/ValidateConfigSubCommand.java
  63. 2
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlockExportFormat.java
  64. 3
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlockImportFormat.java
  65. 9
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/blocks/BlocksSubCommand.java
  66. 1
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/BackupState.java
  67. 1
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/GenerateLogBloomCache.java
  68. 8
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/OperatorSubCommand.java
  69. 1
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/operator/RestoreState.java
  70. 8
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/rlp/RLPSubCommand.java
  71. 7
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/rlp/RLPType.java
  72. 5
      besu/src/main/java/org/hyperledger/besu/cli/util/BesuCommandCustomFactory.java
  73. 9
      besu/src/main/java/org/hyperledger/besu/cli/util/CascadingDefaultProvider.java
  74. 13
      besu/src/main/java/org/hyperledger/besu/cli/util/CommandLineUtils.java
  75. 15
      besu/src/main/java/org/hyperledger/besu/cli/util/ConfigOptionSearchAndRunHandler.java
  76. 6
      besu/src/main/java/org/hyperledger/besu/cli/util/EnvironmentVariableDefaultProvider.java
  77. 8
      besu/src/main/java/org/hyperledger/besu/cli/util/TomlConfigFileDefaultProvider.java
  78. 6
      besu/src/main/java/org/hyperledger/besu/cli/util/VersionProvider.java
  79. 117
      besu/src/main/java/org/hyperledger/besu/controller/BesuController.java
  80. 284
      besu/src/main/java/org/hyperledger/besu/controller/BesuControllerBuilder.java
  81. 11
      besu/src/main/java/org/hyperledger/besu/controller/BftBesuControllerBuilder.java
  82. 10
      besu/src/main/java/org/hyperledger/besu/controller/BftQueryPluginServiceFactory.java
  83. 1
      besu/src/main/java/org/hyperledger/besu/controller/CliqueBesuControllerBuilder.java
  84. 7
      besu/src/main/java/org/hyperledger/besu/controller/CliqueQueryPluginServiceFactory.java
  85. 22
      besu/src/main/java/org/hyperledger/besu/controller/ConsensusScheduleBesuControllerBuilder.java
  86. 1
      besu/src/main/java/org/hyperledger/besu/controller/IbftBesuControllerBuilder.java
  87. 2
      besu/src/main/java/org/hyperledger/besu/controller/IbftLegacyBesuControllerBuilder.java
  88. 9
      besu/src/main/java/org/hyperledger/besu/controller/IbftQueryPluginServiceFactory.java
  89. 1
      besu/src/main/java/org/hyperledger/besu/controller/MainnetBesuControllerBuilder.java
  90. 18
      besu/src/main/java/org/hyperledger/besu/controller/MergeBesuControllerBuilder.java
  91. 6
      besu/src/main/java/org/hyperledger/besu/controller/MiningParameterOverrides.java
  92. 1
      besu/src/main/java/org/hyperledger/besu/controller/NoopPluginServiceFactory.java
  93. 6
      besu/src/main/java/org/hyperledger/besu/controller/PluginServiceFactory.java
  94. 1
      besu/src/main/java/org/hyperledger/besu/controller/QbftBesuControllerBuilder.java
  95. 7
      besu/src/main/java/org/hyperledger/besu/controller/TransitionBesuControllerBuilder.java
  96. 7
      besu/src/main/java/org/hyperledger/besu/services/BesuConfigurationImpl.java
  97. 9
      besu/src/main/java/org/hyperledger/besu/services/BesuEventsImpl.java
  98. 35
      besu/src/main/java/org/hyperledger/besu/services/BesuPluginContextImpl.java
  99. 11
      besu/src/main/java/org/hyperledger/besu/services/PermissioningServiceImpl.java
  100. 6
      besu/src/main/java/org/hyperledger/besu/services/PicoCLIOptionsImpl.java
  101. Some files were not shown because too many files have changed in this diff Show More

@ -197,10 +197,6 @@ jobs:
name: IntegrationTests name: IntegrationTests
command: | command: |
./gradlew --no-daemon integrationTest ./gradlew --no-daemon integrationTest
- run:
name: Javadoc
command: |
./gradlew --no-daemon javadoc
- run: - run:
name: CompileJmh name: CompileJmh
command: | command: |

@ -20,3 +20,17 @@ jobs:
cache: gradle cache: gradle
- name: spotless - name: spotless
run: ./gradlew --no-daemon --parallel clean spotlessCheck run: ./gradlew --no-daemon --parallel clean spotlessCheck
javadoc_17:
runs-on: ubuntu-latest
if: ${{ github.actor != 'dependabot[bot]' }}
steps:
- name: Checkout Repo
uses: actions/checkout@v3
- name: Set up Java 17
uses: actions/setup-java@v2
with:
distribution: adopt
java-version: 17
cache: gradle
- name: javadoc (JDK 17)
run: ./gradlew --no-daemon clean javadoc

@ -28,8 +28,14 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import picocli.CommandLine.RunLast; import picocli.CommandLine.RunLast;
/** Besu bootstrap class. */
public final class Besu { public final class Besu {
/**
* The main entrypoint to Besu application
*
* @param args command line arguments.
*/
public static void main(final String... args) { public static void main(final String... args) {
final Logger logger = setupLogging(); final Logger logger = setupLogging();

@ -18,6 +18,10 @@ import org.hyperledger.besu.util.platform.PlatformDetector;
import java.util.Optional; import java.util.Optional;
/**
* Represent Besu information such as version, OS etc. Used with --version option and during Besu
* start.
*/
public final class BesuInfo { public final class BesuInfo {
private static final String CLIENT = "besu"; private static final String CLIENT = "besu";
private static final String VERSION = BesuInfo.class.getPackage().getImplementationVersion(); private static final String VERSION = BesuInfo.class.getPackage().getImplementationVersion();
@ -26,10 +30,21 @@ public final class BesuInfo {
private BesuInfo() {} private BesuInfo() {}
/**
* Generate Besu version
*
* @return Besu version in format such as besu/v22.10.3/linux-aarch_64/openjdk-java-11
*/
public static String version() { public static String version() {
return String.format("%s/v%s/%s/%s", CLIENT, VERSION, OS, VM); return String.format("%s/v%s/%s/%s", CLIENT, VERSION, OS, VM);
} }
/**
* Generate node name including identity.
*
* @param maybeIdentity optional node identity to include in the version string.
* @return Version with optional identity if provided.
*/
public static String nodeName(final Optional<String> maybeIdentity) { public static String nodeName(final Optional<String> maybeIdentity) {
return maybeIdentity return maybeIdentity
.map(identity -> String.format("%s/%s/v%s/%s/%s", CLIENT, identity, VERSION, OS, VM)) .map(identity -> String.format("%s/%s/v%s/%s/%s", CLIENT, identity, VERSION, OS, VM))

@ -51,6 +51,7 @@ import io.vertx.core.Vertx;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Runner controls various Besu services lifecycle. */
public class Runner implements AutoCloseable { public class Runner implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(Runner.class); private static final Logger LOG = LoggerFactory.getLogger(Runner.class);
@ -77,6 +78,26 @@ public class Runner implements AutoCloseable {
private final Optional<AutoTransactionLogBloomCachingService> private final Optional<AutoTransactionLogBloomCachingService>
autoTransactionLogBloomCachingService; autoTransactionLogBloomCachingService;
/**
* Instantiates a new Runner.
*
* @param vertx the vertx
* @param networkRunner the network runner
* @param natService the nat service
* @param jsonRpc the json rpc
* @param engineJsonRpc the engine json rpc
* @param graphQLHttp the graph ql http
* @param webSocketRpc the web socket rpc
* @param ipcJsonRpc the ipc json rpc
* @param stratumServer the stratum server
* @param metrics the metrics
* @param ethStatsService the eth stats service
* @param besuController the besu controller
* @param dataDir the data dir
* @param pidPath the pid path
* @param transactionLogBloomCacher the transaction log bloom cacher
* @param blockchain the blockchain
*/
Runner( Runner(
final Vertx vertx, final Vertx vertx,
final NetworkRunner networkRunner, final NetworkRunner networkRunner,
@ -115,6 +136,7 @@ public class Runner implements AutoCloseable {
new TransactionPoolEvictionService(vertx, besuController.getTransactionPool()); new TransactionPoolEvictionService(vertx, besuController.getTransactionPool());
} }
/** Start external services. */
public void startExternalServices() { public void startExternalServices() {
LOG.info("Starting external services ... "); LOG.info("Starting external services ... ");
metrics.ifPresent(service -> waitForServiceToStart("metrics", service.start())); metrics.ifPresent(service -> waitForServiceToStart("metrics", service.start()));
@ -132,6 +154,7 @@ public class Runner implements AutoCloseable {
ethStatsService.ifPresent(EthStatsService::start); ethStatsService.ifPresent(EthStatsService::start);
} }
/** Start ethereum main loop. */
public void startEthereumMainLoop() { public void startEthereumMainLoop() {
try { try {
LOG.info("Starting Ethereum main loop ... "); LOG.info("Starting Ethereum main loop ... ");
@ -154,6 +177,7 @@ public class Runner implements AutoCloseable {
} }
} }
/** Stop services. */
public void stop() { public void stop() {
transactionPoolEvictionService.stop(); transactionPoolEvictionService.stop();
jsonRpc.ifPresent(service -> waitForServiceToStop("jsonRpc", service.stop())); jsonRpc.ifPresent(service -> waitForServiceToStop("jsonRpc", service.stop()));
@ -184,6 +208,7 @@ public class Runner implements AutoCloseable {
shutdown.countDown(); shutdown.countDown();
} }
/** Await stop. */
public void awaitStop() { public void awaitStop() {
try { try {
shutdown.await(); shutdown.await();
@ -328,22 +353,47 @@ public class Runner implements AutoCloseable {
}); });
} }
/**
* Gets json rpc port.
*
* @return the json rpc port
*/
public Optional<Integer> getJsonRpcPort() { public Optional<Integer> getJsonRpcPort() {
return jsonRpc.map(service -> service.socketAddress().getPort()); return jsonRpc.map(service -> service.socketAddress().getPort());
} }
/**
* Gets engine json rpc port.
*
* @return the engine json rpc port
*/
public Optional<Integer> getEngineJsonRpcPort() { public Optional<Integer> getEngineJsonRpcPort() {
return engineJsonRpc.map(service -> service.socketAddress().getPort()); return engineJsonRpc.map(service -> service.socketAddress().getPort());
} }
/**
* Gets GraphQl http port.
*
* @return the graph ql http port
*/
public Optional<Integer> getGraphQLHttpPort() { public Optional<Integer> getGraphQLHttpPort() {
return graphQLHttp.map(service -> service.socketAddress().getPort()); return graphQLHttp.map(service -> service.socketAddress().getPort());
} }
/**
* Gets web socket port.
*
* @return the web socket port
*/
public Optional<Integer> getWebSocketPort() { public Optional<Integer> getWebSocketPort() {
return webSocketRpc.map(service -> service.socketAddress().getPort()); return webSocketRpc.map(service -> service.socketAddress().getPort());
} }
/**
* Gets metrics port.
*
* @return the metrics port
*/
public Optional<Integer> getMetricsPort() { public Optional<Integer> getMetricsPort() {
if (metrics.isPresent()) { if (metrics.isPresent()) {
return metrics.get().getPort(); return metrics.get().getPort();
@ -352,6 +402,11 @@ public class Runner implements AutoCloseable {
} }
} }
/**
* Gets local enode.
*
* @return the local enode
*/
@VisibleForTesting @VisibleForTesting
Optional<EnodeURL> getLocalEnode() { Optional<EnodeURL> getLocalEnode() {
return networkRunner.getNetwork().getLocalEnode(); return networkRunner.getNetwork().getLocalEnode();
@ -359,6 +414,11 @@ public class Runner implements AutoCloseable {
@FunctionalInterface @FunctionalInterface
private interface SynchronousShutdown { private interface SynchronousShutdown {
/**
* Await for shutdown.
*
* @throws InterruptedException the interrupted exception
*/
void await() throws InterruptedException; void await() throws InterruptedException;
} }

@ -147,6 +147,7 @@ import org.apache.tuweni.units.bigints.UInt256;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The builder for Runner class. */
public class RunnerBuilder { public class RunnerBuilder {
private static final Logger LOG = LoggerFactory.getLogger(RunnerBuilder.class); private static final Logger LOG = LoggerFactory.getLogger(RunnerBuilder.class);
@ -195,26 +196,56 @@ public class RunnerBuilder {
private boolean legacyForkIdEnabled; private boolean legacyForkIdEnabled;
private Optional<Long> rpcMaxLogsRange; private Optional<Long> rpcMaxLogsRange;
/**
* Add Vertx.
*
* @param vertx the vertx instance
* @return runner builder
*/
public RunnerBuilder vertx(final Vertx vertx) { public RunnerBuilder vertx(final Vertx vertx) {
this.vertx = vertx; this.vertx = vertx;
return this; return this;
} }
/**
* Add Besu controller.
*
* @param besuController the besu controller
* @return the runner builder
*/
public RunnerBuilder besuController(final BesuController besuController) { public RunnerBuilder besuController(final BesuController besuController) {
this.besuController = besuController; this.besuController = besuController;
return this; return this;
} }
/**
* P2p enabled.
*
* @param p2pEnabled the p 2 p enabled
* @return the runner builder
*/
public RunnerBuilder p2pEnabled(final boolean p2pEnabled) { public RunnerBuilder p2pEnabled(final boolean p2pEnabled) {
this.p2pEnabled = p2pEnabled; this.p2pEnabled = p2pEnabled;
return this; return this;
} }
/**
* TLSConfiguration p2pTLSConfiguration.
*
* @param p2pTLSConfiguration the TLSConfiguration p2pTLSConfiguration
* @return the runner builder
*/
public RunnerBuilder p2pTLSConfiguration(final TLSConfiguration p2pTLSConfiguration) { public RunnerBuilder p2pTLSConfiguration(final TLSConfiguration p2pTLSConfiguration) {
this.p2pTLSConfiguration = Optional.of(p2pTLSConfiguration); this.p2pTLSConfiguration = Optional.of(p2pTLSConfiguration);
return this; return this;
} }
/**
* Optional TLSConfiguration p2pTLSConfiguration.
*
* @param p2pTLSConfiguration the TLSConfiguration p2pTLSConfiguration
* @return the runner builder
*/
public RunnerBuilder p2pTLSConfiguration(final Optional<TLSConfiguration> p2pTLSConfiguration) { public RunnerBuilder p2pTLSConfiguration(final Optional<TLSConfiguration> p2pTLSConfiguration) {
if (null != p2pTLSConfiguration) { if (null != p2pTLSConfiguration) {
this.p2pTLSConfiguration = p2pTLSConfiguration; this.p2pTLSConfiguration = p2pTLSConfiguration;
@ -222,188 +253,403 @@ public class RunnerBuilder {
return this; return this;
} }
/**
* Enable Discovery.
*
* @param discovery the discovery
* @return the runner builder
*/
public RunnerBuilder discovery(final boolean discovery) { public RunnerBuilder discovery(final boolean discovery) {
this.discovery = discovery; this.discovery = discovery;
return this; return this;
} }
/**
* Add Eth network config.
*
* @param ethNetworkConfig the eth network config
* @return the runner builder
*/
public RunnerBuilder ethNetworkConfig(final EthNetworkConfig ethNetworkConfig) { public RunnerBuilder ethNetworkConfig(final EthNetworkConfig ethNetworkConfig) {
this.ethNetworkConfig = ethNetworkConfig; this.ethNetworkConfig = ethNetworkConfig;
return this; return this;
} }
/**
* Add Networking configuration.
*
* @param networkingConfiguration the networking configuration
* @return the runner builder
*/
public RunnerBuilder networkingConfiguration( public RunnerBuilder networkingConfiguration(
final NetworkingConfiguration networkingConfiguration) { final NetworkingConfiguration networkingConfiguration) {
this.networkingConfiguration = networkingConfiguration; this.networkingConfiguration = networkingConfiguration;
return this; return this;
} }
/**
* Add P2p advertised host.
*
* @param p2pAdvertisedHost the P2P advertised host
* @return the runner builder
*/
public RunnerBuilder p2pAdvertisedHost(final String p2pAdvertisedHost) { public RunnerBuilder p2pAdvertisedHost(final String p2pAdvertisedHost) {
this.p2pAdvertisedHost = p2pAdvertisedHost; this.p2pAdvertisedHost = p2pAdvertisedHost;
return this; return this;
} }
/**
* Add P2P Listener interface ip/host name.
*
* @param ip the ip
* @return the runner builder
*/
public RunnerBuilder p2pListenInterface(final String ip) { public RunnerBuilder p2pListenInterface(final String ip) {
checkArgument(!isNull(ip), "Invalid null value supplied for p2pListenInterface"); checkArgument(!isNull(ip), "Invalid null value supplied for p2pListenInterface");
this.p2pListenInterface = ip; this.p2pListenInterface = ip;
return this; return this;
} }
/**
* Add P2P listen port.
*
* @param p2pListenPort the p 2 p listen port
* @return the runner builder
*/
public RunnerBuilder p2pListenPort(final int p2pListenPort) { public RunnerBuilder p2pListenPort(final int p2pListenPort) {
this.p2pListenPort = p2pListenPort; this.p2pListenPort = p2pListenPort;
return this; return this;
} }
/**
* Add Nat method.
*
* @param natMethod the nat method
* @return the runner builder
*/
public RunnerBuilder natMethod(final NatMethod natMethod) { public RunnerBuilder natMethod(final NatMethod natMethod) {
this.natMethod = natMethod; this.natMethod = natMethod;
return this; return this;
} }
/**
* Add Nat manager service name.
*
* @param natManagerServiceName the nat manager service name
* @return the runner builder
*/
public RunnerBuilder natManagerServiceName(final String natManagerServiceName) { public RunnerBuilder natManagerServiceName(final String natManagerServiceName) {
this.natManagerServiceName = natManagerServiceName; this.natManagerServiceName = natManagerServiceName;
return this; return this;
} }
/**
* Enable Nat method fallback.
*
* @param natMethodFallbackEnabled the nat method fallback enabled
* @return the runner builder
*/
public RunnerBuilder natMethodFallbackEnabled(final boolean natMethodFallbackEnabled) { public RunnerBuilder natMethodFallbackEnabled(final boolean natMethodFallbackEnabled) {
this.natMethodFallbackEnabled = natMethodFallbackEnabled; this.natMethodFallbackEnabled = natMethodFallbackEnabled;
return this; return this;
} }
/**
* Add Max peers.
*
* @param maxPeers the max peers
* @return the runner builder
*/
public RunnerBuilder maxPeers(final int maxPeers) { public RunnerBuilder maxPeers(final int maxPeers) {
this.maxPeers = maxPeers; this.maxPeers = maxPeers;
return this; return this;
} }
/**
* Enable Limit remote wire connections.
*
* @param limitRemoteWireConnectionsEnabled the limit remote wire connections enabled
* @return the runner builder
*/
public RunnerBuilder limitRemoteWireConnectionsEnabled( public RunnerBuilder limitRemoteWireConnectionsEnabled(
final boolean limitRemoteWireConnectionsEnabled) { final boolean limitRemoteWireConnectionsEnabled) {
this.limitRemoteWireConnectionsEnabled = limitRemoteWireConnectionsEnabled; this.limitRemoteWireConnectionsEnabled = limitRemoteWireConnectionsEnabled;
return this; return this;
} }
/**
* Add Fraction remote connections allowed.
*
* @param fractionRemoteConnectionsAllowed the fraction remote connections allowed
* @return the runner builder
*/
public RunnerBuilder fractionRemoteConnectionsAllowed( public RunnerBuilder fractionRemoteConnectionsAllowed(
final float fractionRemoteConnectionsAllowed) { final float fractionRemoteConnectionsAllowed) {
this.fractionRemoteConnectionsAllowed = fractionRemoteConnectionsAllowed; this.fractionRemoteConnectionsAllowed = fractionRemoteConnectionsAllowed;
return this; return this;
} }
/**
* Enable Random peer priority.
*
* @param randomPeerPriority the random peer priority
* @return the runner builder
*/
public RunnerBuilder randomPeerPriority(final boolean randomPeerPriority) { public RunnerBuilder randomPeerPriority(final boolean randomPeerPriority) {
this.randomPeerPriority = randomPeerPriority; this.randomPeerPriority = randomPeerPriority;
return this; return this;
} }
/**
* Add Ethstats url.
*
* @param ethstatsUrl the ethstats url
* @return the runner builder
*/
public RunnerBuilder ethstatsUrl(final String ethstatsUrl) { public RunnerBuilder ethstatsUrl(final String ethstatsUrl) {
this.ethstatsUrl = ethstatsUrl; this.ethstatsUrl = ethstatsUrl;
return this; return this;
} }
/**
* Add Ethstats contact.
*
* @param ethstatsContact the ethstats contact
* @return the runner builder
*/
public RunnerBuilder ethstatsContact(final String ethstatsContact) { public RunnerBuilder ethstatsContact(final String ethstatsContact) {
this.ethstatsContact = ethstatsContact; this.ethstatsContact = ethstatsContact;
return this; return this;
} }
/**
* Add Json RPC configuration.
*
* @param jsonRpcConfiguration the json rpc configuration
* @return the runner builder
*/
public RunnerBuilder jsonRpcConfiguration(final JsonRpcConfiguration jsonRpcConfiguration) { public RunnerBuilder jsonRpcConfiguration(final JsonRpcConfiguration jsonRpcConfiguration) {
this.jsonRpcConfiguration = jsonRpcConfiguration; this.jsonRpcConfiguration = jsonRpcConfiguration;
return this; return this;
} }
/**
* Add Engine json RPC configuration.
*
* @param engineJsonRpcConfiguration the engine json rpc configuration
* @return the runner builder
*/
public RunnerBuilder engineJsonRpcConfiguration( public RunnerBuilder engineJsonRpcConfiguration(
final JsonRpcConfiguration engineJsonRpcConfiguration) { final JsonRpcConfiguration engineJsonRpcConfiguration) {
this.engineJsonRpcConfiguration = Optional.ofNullable(engineJsonRpcConfiguration); this.engineJsonRpcConfiguration = Optional.ofNullable(engineJsonRpcConfiguration);
return this; return this;
} }
/**
* Add GraphQl configuration.
*
* @param graphQLConfiguration the graph ql configuration
* @return the runner builder
*/
public RunnerBuilder graphQLConfiguration(final GraphQLConfiguration graphQLConfiguration) { public RunnerBuilder graphQLConfiguration(final GraphQLConfiguration graphQLConfiguration) {
this.graphQLConfiguration = graphQLConfiguration; this.graphQLConfiguration = graphQLConfiguration;
return this; return this;
} }
/**
* Add Web socket configuration.
*
* @param webSocketConfiguration the web socket configuration
* @return the runner builder
*/
public RunnerBuilder webSocketConfiguration(final WebSocketConfiguration webSocketConfiguration) { public RunnerBuilder webSocketConfiguration(final WebSocketConfiguration webSocketConfiguration) {
this.webSocketConfiguration = webSocketConfiguration; this.webSocketConfiguration = webSocketConfiguration;
return this; return this;
} }
/**
* Add Api configuration.
*
* @param apiConfiguration the api configuration
* @return the runner builder
*/
public RunnerBuilder apiConfiguration(final ApiConfiguration apiConfiguration) { public RunnerBuilder apiConfiguration(final ApiConfiguration apiConfiguration) {
this.apiConfiguration = apiConfiguration; this.apiConfiguration = apiConfiguration;
return this; return this;
} }
/**
* Add Permissioning configuration.
*
* @param permissioningConfiguration the permissioning configuration
* @return the runner builder
*/
public RunnerBuilder permissioningConfiguration( public RunnerBuilder permissioningConfiguration(
final Optional<PermissioningConfiguration> permissioningConfiguration) { final Optional<PermissioningConfiguration> permissioningConfiguration) {
this.permissioningConfiguration = permissioningConfiguration; this.permissioningConfiguration = permissioningConfiguration;
return this; return this;
} }
/**
* Add pid path.
*
* @param pidPath the pid path
* @return the runner builder
*/
public RunnerBuilder pidPath(final Path pidPath) { public RunnerBuilder pidPath(final Path pidPath) {
this.pidPath = Optional.ofNullable(pidPath); this.pidPath = Optional.ofNullable(pidPath);
return this; return this;
} }
/**
* Add Data dir.
*
* @param dataDir the data dir
* @return the runner builder
*/
public RunnerBuilder dataDir(final Path dataDir) { public RunnerBuilder dataDir(final Path dataDir) {
this.dataDir = dataDir; this.dataDir = dataDir;
return this; return this;
} }
/**
* Add list of Banned node id.
*
* @param bannedNodeIds the banned node ids
* @return the runner builder
*/
public RunnerBuilder bannedNodeIds(final Collection<Bytes> bannedNodeIds) { public RunnerBuilder bannedNodeIds(final Collection<Bytes> bannedNodeIds) {
this.bannedNodeIds.addAll(bannedNodeIds); this.bannedNodeIds.addAll(bannedNodeIds);
return this; return this;
} }
/**
* Add Metrics configuration.
*
* @param metricsConfiguration the metrics configuration
* @return the runner builder
*/
public RunnerBuilder metricsConfiguration(final MetricsConfiguration metricsConfiguration) { public RunnerBuilder metricsConfiguration(final MetricsConfiguration metricsConfiguration) {
this.metricsConfiguration = metricsConfiguration; this.metricsConfiguration = metricsConfiguration;
return this; return this;
} }
/**
* Add Metrics system.
*
* @param metricsSystem the metrics system
* @return the runner builder
*/
public RunnerBuilder metricsSystem(final ObservableMetricsSystem metricsSystem) { public RunnerBuilder metricsSystem(final ObservableMetricsSystem metricsSystem) {
this.metricsSystem = metricsSystem; this.metricsSystem = metricsSystem;
return this; return this;
} }
/**
* Add Permissioning service.
*
* @param permissioningService the permissioning service
* @return the runner builder
*/
public RunnerBuilder permissioningService(final PermissioningServiceImpl permissioningService) { public RunnerBuilder permissioningService(final PermissioningServiceImpl permissioningService) {
this.permissioningService = permissioningService; this.permissioningService = permissioningService;
return this; return this;
} }
/**
* Add Static nodes collection.
*
* @param staticNodes the static nodes
* @return the runner builder
*/
public RunnerBuilder staticNodes(final Collection<EnodeURL> staticNodes) { public RunnerBuilder staticNodes(final Collection<EnodeURL> staticNodes) {
this.staticNodes = staticNodes; this.staticNodes = staticNodes;
return this; return this;
} }
/**
* Add Node identity string.
*
* @param identityString the identity string
* @return the runner builder
*/
public RunnerBuilder identityString(final Optional<String> identityString) { public RunnerBuilder identityString(final Optional<String> identityString) {
this.identityString = identityString; this.identityString = identityString;
return this; return this;
} }
/**
* Add Besu plugin context.
*
* @param besuPluginContext the besu plugin context
* @return the runner builder
*/
public RunnerBuilder besuPluginContext(final BesuPluginContextImpl besuPluginContext) { public RunnerBuilder besuPluginContext(final BesuPluginContextImpl besuPluginContext) {
this.besuPluginContext = besuPluginContext; this.besuPluginContext = besuPluginContext;
return this; return this;
} }
/**
* Enable Auto log bloom caching.
*
* @param autoLogBloomCaching the auto log bloom caching
* @return the runner builder
*/
public RunnerBuilder autoLogBloomCaching(final boolean autoLogBloomCaching) { public RunnerBuilder autoLogBloomCaching(final boolean autoLogBloomCaching) {
this.autoLogBloomCaching = autoLogBloomCaching; this.autoLogBloomCaching = autoLogBloomCaching;
return this; return this;
} }
/**
* Add Storage provider.
*
* @param storageProvider the storage provider
* @return the runner builder
*/
public RunnerBuilder storageProvider(final StorageProvider storageProvider) { public RunnerBuilder storageProvider(final StorageProvider storageProvider) {
this.storageProvider = storageProvider; this.storageProvider = storageProvider;
return this; return this;
} }
/**
* Add Rpc endpoint service.
*
* @param rpcEndpointService the rpc endpoint service
* @return the runner builder
*/
public RunnerBuilder rpcEndpointService(final RpcEndpointServiceImpl rpcEndpointService) { public RunnerBuilder rpcEndpointService(final RpcEndpointServiceImpl rpcEndpointService) {
this.rpcEndpointServiceImpl = rpcEndpointService; this.rpcEndpointServiceImpl = rpcEndpointService;
return this; return this;
} }
/**
* Add Json Rpc Ipc configuration.
*
* @param jsonRpcIpcConfiguration the json rpc ipc configuration
* @return the runner builder
*/
public RunnerBuilder jsonRpcIpcConfiguration( public RunnerBuilder jsonRpcIpcConfiguration(
final JsonRpcIpcConfiguration jsonRpcIpcConfiguration) { final JsonRpcIpcConfiguration jsonRpcIpcConfiguration) {
this.jsonRpcIpcConfiguration = jsonRpcIpcConfiguration; this.jsonRpcIpcConfiguration = jsonRpcIpcConfiguration;
return this; return this;
} }
/**
* Add Rpc max logs range.
*
* @param rpcMaxLogsRange the rpc max logs range
* @return the runner builder
*/
public RunnerBuilder rpcMaxLogsRange(final Long rpcMaxLogsRange) { public RunnerBuilder rpcMaxLogsRange(final Long rpcMaxLogsRange) {
this.rpcMaxLogsRange = rpcMaxLogsRange > 0 ? Optional.of(rpcMaxLogsRange) : Optional.empty(); this.rpcMaxLogsRange = rpcMaxLogsRange > 0 ? Optional.of(rpcMaxLogsRange) : Optional.empty();
return this; return this;
} }
/**
* Build Runner instance.
*
* @return the runner
*/
public Runner build() { public Runner build() {
Preconditions.checkNotNull(besuController); Preconditions.checkNotNull(besuController);
@ -965,6 +1211,13 @@ public class RunnerBuilder {
} }
} }
/**
* Gets fixed nodes. Visible for testing.
*
* @param someFixedNodes the fixed nodes
* @param moreFixedNodes nodes added to fixed nodes
* @return the fixed and more nodes combined
*/
@VisibleForTesting @VisibleForTesting
public static Collection<EnodeURL> getFixedNodes( public static Collection<EnodeURL> getFixedNodes(
final Collection<EnodeURL> someFixedNodes, final Collection<EnodeURL> moreFixedNodes) { final Collection<EnodeURL> someFixedNodes, final Collection<EnodeURL> moreFixedNodes) {
@ -1176,15 +1429,32 @@ public class RunnerBuilder {
return MetricsService.create(vertx, configuration, metricsSystem); return MetricsService.create(vertx, configuration, metricsSystem);
} }
/**
* Gets minimum peers.
*
* @return the minimum peers
*/
public int getMinPeers() { public int getMinPeers() {
return minPeers; return minPeers;
} }
/**
* Add Minimum peers.
*
* @param minPeers the minimum peers
* @return the runner builder
*/
public RunnerBuilder minPeers(final int minPeers) { public RunnerBuilder minPeers(final int minPeers) {
this.minPeers = minPeers; this.minPeers = minPeers;
return this; return this;
} }
/**
* Add Legacy fork id.
*
* @param legacyEth64ForkIdEnabled the legacy eth64 fork id enabled
* @return the runner builder
*/
public RunnerBuilder legacyForkId(final boolean legacyEth64ForkIdEnabled) { public RunnerBuilder legacyForkId(final boolean legacyEth64ForkIdEnabled) {
this.legacyForkIdEnabled = legacyEth64ForkIdEnabled; this.legacyForkIdEnabled = legacyEth64ForkIdEnabled;
return this; return this;

@ -33,6 +33,11 @@ public abstract class BlockExporter {
private static final Logger LOG = LoggerFactory.getLogger(BlockExporter.class); private static final Logger LOG = LoggerFactory.getLogger(BlockExporter.class);
private final Blockchain blockchain; private final Blockchain blockchain;
/**
* Instantiates a new Block exporter.
*
* @param blockchain the blockchain
*/
protected BlockExporter(final Blockchain blockchain) { protected BlockExporter(final Blockchain blockchain) {
this.blockchain = blockchain; this.blockchain = blockchain;
} }
@ -90,6 +95,13 @@ public abstract class BlockExporter {
LOG.info("Export complete at block {}", blockNumber); LOG.info("Export complete at block {}", blockNumber);
} }
/**
* Export block.
*
* @param outputStream The FileOutputStream where the block will be exported
* @param block The block to export
* @throws IOException In case of an error while exporting.
*/
protected abstract void exportBlock(final FileOutputStream outputStream, final Block block) protected abstract void exportBlock(final FileOutputStream outputStream, final Block block)
throws IOException; throws IOException;
} }

@ -23,8 +23,14 @@ import java.io.IOException;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
/** The Rlp block exporter. */
public class RlpBlockExporter extends BlockExporter { public class RlpBlockExporter extends BlockExporter {
/**
* Instantiates a new Rlp block exporter.
*
* @param blockchain the blockchain
*/
public RlpBlockExporter(final Blockchain blockchain) { public RlpBlockExporter(final Blockchain blockchain) {
super(blockchain); super(blockchain);
} }

@ -52,6 +52,11 @@ public class JsonBlockImporter {
private final ObjectMapper mapper; private final ObjectMapper mapper;
private final BesuController controller; private final BesuController controller;
/**
* Instantiates a new Json block importer.
*
* @param controller the controller
*/
public JsonBlockImporter(final BesuController controller) { public JsonBlockImporter(final BesuController controller) {
this.controller = controller; this.controller = controller;
mapper = new ObjectMapper(); mapper = new ObjectMapper();
@ -61,6 +66,12 @@ public class JsonBlockImporter {
mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true); mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
} }
/**
* Import chain.
*
* @param chainJson the chain json
* @throws IOException the io exception
*/
public void importChain(final String chainJson) throws IOException { public void importChain(final String chainJson) throws IOException {
warnIfDatabaseIsNotEmpty(); warnIfDatabaseIsNotEmpty();

@ -80,6 +80,17 @@ public class RlpBlockImporter implements Closeable {
return importBlockchain(blocks, besuController, skipPowValidation, 0L, Long.MAX_VALUE); return importBlockchain(blocks, besuController, skipPowValidation, 0L, Long.MAX_VALUE);
} }
/**
* Import blockchain.
*
* @param blocks the blocks
* @param besuController the besu controller
* @param skipPowValidation the skip pow validation
* @param startBlock the start block
* @param endBlock the end block
* @return the rlp block importer - import result
* @throws IOException the io exception
*/
public RlpBlockImporter.ImportResult importBlockchain( public RlpBlockImporter.ImportResult importBlockchain(
final Path blocks, final Path blocks,
final BesuController besuController, final BesuController besuController,
@ -279,12 +290,21 @@ public class RlpBlockImporter implements Closeable {
} }
} }
/** The Import result. */
public static final class ImportResult { public static final class ImportResult {
/** The difficulty. */
public final Difficulty td; public final Difficulty td;
/** The Count. */
final int count; final int count;
/**
* Instantiates a new Import result.
*
* @param td the td
* @param count the count
*/
ImportResult(final Difficulty td, final int count) { ImportResult(final Difficulty td, final int count) {
this.td = td; this.td = td;
this.count = count; this.count = count;

@ -33,6 +33,9 @@ import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256; import org.apache.tuweni.units.bigints.UInt256;
/**
* Represents BlockData used in ChainData. Meant to be constructed by Json serializer/deserializer.
*/
@JsonIgnoreProperties("comment") @JsonIgnoreProperties("comment")
public class BlockData { public class BlockData {
@ -42,6 +45,15 @@ public class BlockData {
private final Optional<Address> coinbase; private final Optional<Address> coinbase;
private final Optional<Bytes> extraData; private final Optional<Bytes> extraData;
/**
* Constructor for BlockData
*
* @param number Block number in hex format.
* @param parentHash Parent hash in hex format.
* @param coinbase Coinbase Address in hex format.
* @param extraData Extra data in hex format.
* @param transactions list of TransactionData.
*/
@JsonCreator @JsonCreator
public BlockData( public BlockData(
@JsonProperty("number") final Optional<String> number, @JsonProperty("number") final Optional<String> number,
@ -56,27 +68,59 @@ public class BlockData {
this.transactionData = transactions; this.transactionData = transactions;
} }
/**
* Gets number.
*
* @return the number
*/
public Optional<Long> getNumber() { public Optional<Long> getNumber() {
return number; return number;
} }
/**
* Gets parent hash.
*
* @return the parent hash
*/
public Optional<Hash> getParentHash() { public Optional<Hash> getParentHash() {
return parentHash; return parentHash;
} }
/**
* Gets coinbase.
*
* @return the coinbase
*/
public Optional<Address> getCoinbase() { public Optional<Address> getCoinbase() {
return coinbase; return coinbase;
} }
/**
* Gets extra data.
*
* @return the extra data
*/
public Optional<Bytes> getExtraData() { public Optional<Bytes> getExtraData() {
return extraData; return extraData;
} }
/**
* Stream transactions.
*
* @param worldState the world state
* @return the stream of Transaction
*/
public Stream<Transaction> streamTransactions(final WorldState worldState) { public Stream<Transaction> streamTransactions(final WorldState worldState) {
final NonceProvider nonceProvider = getNonceProvider(worldState); final NonceProvider nonceProvider = getNonceProvider(worldState);
return transactionData.stream().map((tx) -> tx.getSignedTransaction(nonceProvider)); return transactionData.stream().map((tx) -> tx.getSignedTransaction(nonceProvider));
} }
/**
* Gets nonce provider.
*
* @param worldState the world state
* @return the nonce provider
*/
public NonceProvider getNonceProvider(final WorldState worldState) { public NonceProvider getNonceProvider(final WorldState worldState) {
final HashMap<Address, Long> currentNonceValues = new HashMap<>(); final HashMap<Address, Long> currentNonceValues = new HashMap<>();
return (Address address) -> return (Address address) ->

@ -20,16 +20,27 @@ import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
/** The Chain data. */
@JsonIgnoreProperties("comment") @JsonIgnoreProperties("comment")
public class ChainData { public class ChainData {
private final List<BlockData> blocks; private final List<BlockData> blocks;
/**
* Instantiates a new Chain data.
*
* @param blocks the blocks
*/
@JsonCreator @JsonCreator
public ChainData(@JsonProperty("blocks") final List<BlockData> blocks) { public ChainData(@JsonProperty("blocks") final List<BlockData> blocks) {
this.blocks = blocks; this.blocks = blocks;
} }
/**
* Gets blocks.
*
* @return the blocks
*/
public List<BlockData> getBlocks() { public List<BlockData> getBlocks() {
return blocks; return blocks;
} }

@ -33,6 +33,7 @@ import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256; import org.apache.tuweni.units.bigints.UInt256;
/** The Transaction data. */
@JsonIgnoreProperties("comment") @JsonIgnoreProperties("comment")
public class TransactionData { public class TransactionData {
@ -46,6 +47,16 @@ public class TransactionData {
private static final Supplier<SignatureAlgorithm> SIGNATURE_ALGORITHM = private static final Supplier<SignatureAlgorithm> SIGNATURE_ALGORITHM =
Suppliers.memoize(SignatureAlgorithmFactory::getInstance); Suppliers.memoize(SignatureAlgorithmFactory::getInstance);
/**
* Instantiates a new Transaction data.
*
* @param gasLimit the gas limit
* @param gasPrice the gas price
* @param data the data
* @param value the value
* @param to the to
* @param secretKey the secret key
*/
@JsonCreator @JsonCreator
public TransactionData( public TransactionData(
@JsonProperty("gasLimit") final String gasLimit, @JsonProperty("gasLimit") final String gasLimit,
@ -62,6 +73,12 @@ public class TransactionData {
this.privateKey = SIGNATURE_ALGORITHM.get().createPrivateKey(Bytes32.fromHexString(secretKey)); this.privateKey = SIGNATURE_ALGORITHM.get().createPrivateKey(Bytes32.fromHexString(secretKey));
} }
/**
* Gets signed transaction.
*
* @param nonceProvider the nonce provider
* @return the signed transaction
*/
public Transaction getSignedTransaction(final NonceProvider nonceProvider) { public Transaction getSignedTransaction(final NonceProvider nonceProvider) {
final KeyPair keyPair = SIGNATURE_ALGORITHM.get().createKeyPair(privateKey); final KeyPair keyPair = SIGNATURE_ALGORITHM.get().createKeyPair(privateKey);
@ -78,8 +95,15 @@ public class TransactionData {
.signAndBuild(keyPair); .signAndBuild(keyPair);
} }
/** The interface Nonce provider. */
@FunctionalInterface @FunctionalInterface
public interface NonceProvider { public interface NonceProvider {
/**
* Get Nonce.
*
* @param address the address
* @return the Nonce
*/
long get(final Address address); long get(final Address address);
} }
} }

@ -252,6 +252,7 @@ import picocli.CommandLine.Mixin;
import picocli.CommandLine.Option; import picocli.CommandLine.Option;
import picocli.CommandLine.ParameterException; import picocli.CommandLine.ParameterException;
/** Represents the main Besu CLI command that runs the Besu Ethereum client full node. */
@SuppressWarnings("FieldCanBeLocal") // because Picocli injected fields report false positives @SuppressWarnings("FieldCanBeLocal") // because Picocli injected fields report false positives
@Command( @Command(
description = "This command runs the Besu Ethereum client full node.", description = "This command runs the Besu Ethereum client full node.",
@ -1319,8 +1320,21 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
private Vertx vertx; private Vertx vertx;
private EnodeDnsConfiguration enodeDnsConfiguration; private EnodeDnsConfiguration enodeDnsConfiguration;
private KeyValueStorageProvider keyValueStorageProvider; private KeyValueStorageProvider keyValueStorageProvider;
/** Sets GoQuorum compatibility mode. */
protected Boolean isGoQuorumCompatibilityMode = false; protected Boolean isGoQuorumCompatibilityMode = false;
/**
* Besu command constructor.
*
* @param logger Logger instance
* @param rlpBlockImporter RlpBlockImporter supplier
* @param jsonBlockImporterFactory instance of {@code Function<BesuController, JsonBlockImporter>}
* @param rlpBlockExporterFactory instance of {@code Function<Blockchain, RlpBlockExporter>}
* @param runnerBuilder instance of RunnerBuilder
* @param controllerBuilderFactory instance of BesuController.Builder
* @param besuPluginContext instance of BesuPluginContextImpl
* @param environment Environment variables map
*/
public BesuCommand( public BesuCommand(
final Logger logger, final Logger logger,
final Supplier<RlpBlockImporter> rlpBlockImporter, final Supplier<RlpBlockImporter> rlpBlockImporter,
@ -1347,6 +1361,24 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
new RpcEndpointServiceImpl()); new RpcEndpointServiceImpl());
} }
/**
* Overloaded Besu command constructor visible for testing.
*
* @param logger Logger instance
* @param rlpBlockImporter RlpBlockImporter supplier
* @param jsonBlockImporterFactory instance of {@code Function<BesuController, JsonBlockImporter>}
* @param rlpBlockExporterFactory instance of {@code Function<Blockchain, RlpBlockExporter>}
* @param runnerBuilder instance of RunnerBuilder
* @param controllerBuilderFactory instance of BesuController.Builder
* @param besuPluginContext instance of BesuPluginContextImpl
* @param environment Environment variables map
* @param storageService instance of StorageServiceImpl
* @param securityModuleService instance of SecurityModuleServiceImpl
* @param permissioningService instance of PermissioningServiceImpl
* @param privacyPluginService instance of PrivacyPluginServiceImpl
* @param pkiBlockCreationConfigProvider instance of PkiBlockCreationConfigurationProvider
* @param rpcEndpointServiceImpl instance of RpcEndpointServiceImpl
*/
@VisibleForTesting @VisibleForTesting
protected BesuCommand( protected BesuCommand(
final Logger logger, final Logger logger,
@ -1381,6 +1413,17 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
this.rpcEndpointServiceImpl = rpcEndpointServiceImpl; this.rpcEndpointServiceImpl = rpcEndpointServiceImpl;
} }
/**
* Parse Besu command line arguments. Visible for testing.
*
* @param resultHandler execution strategy. See PicoCLI. Typical argument is RunLast.
* @param parameterExceptionHandler Exception handler for handling parameters
* @param executionExceptionHandler Exception handler for business logic
* @param in Standard input stream
* @param args arguments to Besu command
* @return success or failure exit code.
*/
@VisibleForTesting
public int parse( public int parse(
final IExecutionStrategy resultHandler, final IExecutionStrategy resultHandler,
final BesuParameterExceptionHandler parameterExceptionHandler, final BesuParameterExceptionHandler parameterExceptionHandler,
@ -1581,6 +1624,13 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
} }
// loadKeyPair() is public because it is accessed by subcommands // loadKeyPair() is public because it is accessed by subcommands
/**
* Load key pair from private key. Visible to be accessed by subcommands.
*
* @param nodePrivateKeyFile File containing private key
* @return KeyPair loaded from private key file
*/
public KeyPair loadKeyPair(final File nodePrivateKeyFile) { public KeyPair loadKeyPair(final File nodePrivateKeyFile) {
return KeyPairUtil.loadKeyPair(resolveNodePrivateKeyFile(nodePrivateKeyFile)); return KeyPairUtil.loadKeyPair(resolveNodePrivateKeyFile(nodePrivateKeyFile));
} }
@ -1722,6 +1772,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
.labels(() -> 1, BesuInfo.version()); .labels(() -> 1, BesuInfo.version());
} }
/**
* Configure logging framework for Besu
*
* @param announce sets to true to print the logging level on standard output
*/
public void configureLogging(final boolean announce) { public void configureLogging(final boolean announce) {
// To change the configuration if color was enabled/disabled // To change the configuration if color was enabled/disabled
Log4j2ConfiguratorUtil.reconfigure(); Log4j2ConfiguratorUtil.reconfigure();
@ -1735,6 +1790,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
} }
} }
/**
* Logging in Color enabled or not.
*
* @return Optional true or false representing logging color is enabled. Empty if not set.
*/
public static Optional<Boolean> getColorEnabled() { public static Optional<Boolean> getColorEnabled() {
return Optional.ofNullable(colorEnabled); return Optional.ofNullable(colorEnabled);
} }
@ -1826,6 +1886,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
} }
} }
/**
* Validates P2P interface IP address/host name. Visible for testing.
*
* @param p2pInterface IP Address/host name
*/
protected void validateP2PInterface(final String p2pInterface) { protected void validateP2PInterface(final String p2pInterface) {
final String failMessage = "The provided --p2p-interface is not available: " + p2pInterface; final String failMessage = "The provided --p2p-interface is not available: " + p2pInterface;
try { try {
@ -1890,7 +1955,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
} }
} }
public void validateRpcOptionsParams() { private void validateRpcOptionsParams() {
final Predicate<String> configuredApis = final Predicate<String> configuredApis =
apiName -> apiName ->
Arrays.stream(RpcApis.values()) Arrays.stream(RpcApis.values())
@ -1936,7 +2001,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
} }
} }
public void validateChainDataPruningParams() { private void validateChainDataPruningParams() {
if (unstableChainPruningOptions.getChainDataPruningEnabled() if (unstableChainPruningOptions.getChainDataPruningEnabled()
&& unstableChainPruningOptions.getChainDataPruningBlocksRetained() && unstableChainPruningOptions.getChainDataPruningBlocksRetained()
< ChainPruningOptions.DEFAULT_CHAIN_DATA_PRUNING_MIN_BLOCKS_RETAINED) { < ChainPruningOptions.DEFAULT_CHAIN_DATA_PRUNING_MIN_BLOCKS_RETAINED) {
@ -2156,6 +2221,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
besuController = buildController(); besuController = buildController();
} }
/**
* Builds BesuController
*
* @return instance of BesuController
*/
public BesuController buildController() { public BesuController buildController() {
try { try {
return getControllerBuilder().build(); return getControllerBuilder().build();
@ -2164,6 +2234,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
} }
} }
/**
* Builds BesuControllerBuilder which can be used to build BesuController
*
* @return instance of BesuControllerBuilder
*/
public BesuControllerBuilder getControllerBuilder() { public BesuControllerBuilder getControllerBuilder() {
final KeyValueStorageProvider storageProvider = keyValueStorageProvider(keyValueStorageName); final KeyValueStorageProvider storageProvider = keyValueStorageProvider(keyValueStorageName);
return controllerBuilderFactory return controllerBuilderFactory
@ -2517,6 +2592,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
.build(); .build();
} }
/**
* Metrics Configuration for Besu
*
* @return instance of MetricsConfiguration.
*/
public MetricsConfiguration metricsConfiguration() { public MetricsConfiguration metricsConfiguration() {
if (metricsOptionGroup.isMetricsEnabled && metricsOptionGroup.isMetricsPushEnabled) { if (metricsOptionGroup.isMetricsEnabled && metricsOptionGroup.isMetricsPushEnabled) {
throw new ParameterException( throw new ParameterException(
@ -2798,7 +2878,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
return privacyParameters; return privacyParameters;
} }
public WorldStateArchive createPrivateWorldStateArchive(final StorageProvider storageProvider) { private WorldStateArchive createPrivateWorldStateArchive(final StorageProvider storageProvider) {
final WorldStateStorage privateWorldStateStorage = final WorldStateStorage privateWorldStateStorage =
storageProvider.createPrivateWorldStateStorage(); storageProvider.createPrivateWorldStateStorage();
final WorldStatePreimageStorage preimageStorage = final WorldStatePreimageStorage preimageStorage =
@ -2956,6 +3036,13 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
return runner; return runner;
} }
/**
* Builds Vertx instance from VertxOptions. Visible for testing.
*
* @param vertxOptions Instance of VertxOptions
* @return Instance of Vertx.
*/
@VisibleForTesting
protected Vertx createVertx(final VertxOptions vertxOptions) { protected Vertx createVertx(final VertxOptions vertxOptions) {
return Vertx.vertx(vertxOptions); return Vertx.vertx(vertxOptions);
} }
@ -3082,7 +3169,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
} }
} }
// dataDir() is public because it is accessed by subcommands /**
* Returns data directory used by Besu. Visible as it is accessed by other subcommands.
*
* @return Path representing data directory.
*/
public Path dataDir() { public Path dataDir() {
return dataPath.toAbsolutePath(); return dataPath.toAbsolutePath();
} }
@ -3132,6 +3223,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
+ DefaultCommandValues.PERMISSIONING_CONFIG_LOCATION; + DefaultCommandValues.PERMISSIONING_CONFIG_LOCATION;
} }
/**
* Metrics System used by Besu
*
* @return Instance of MetricsSystem
*/
public MetricsSystem getMetricsSystem() { public MetricsSystem getMetricsSystem() {
return metricsSystem.get(); return metricsSystem.get();
} }
@ -3160,14 +3256,31 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
/**
* Besu CLI Paramaters exception handler used by VertX. Visible for testing.
*
* @return instance of BesuParameterExceptionHandler
*/
@VisibleForTesting
public BesuParameterExceptionHandler parameterExceptionHandler() { public BesuParameterExceptionHandler parameterExceptionHandler() {
return new BesuParameterExceptionHandler(this::getLogLevel); return new BesuParameterExceptionHandler(this::getLogLevel);
} }
/**
* Returns BesuExecutionExceptionHandler. Visible as it is used in testing.
*
* @return instance of BesuExecutionExceptionHandler used by Vertx.
*/
public BesuExecutionExceptionHandler executionExceptionHandler() { public BesuExecutionExceptionHandler executionExceptionHandler() {
return new BesuExecutionExceptionHandler(); return new BesuExecutionExceptionHandler();
} }
/**
* Represents Enode DNS Configuration. Visible for testing.
*
* @return instance of EnodeDnsConfiguration
*/
@VisibleForTesting
public EnodeDnsConfiguration getEnodeDnsConfiguration() { public EnodeDnsConfiguration getEnodeDnsConfiguration() {
if (enodeDnsConfiguration == null) { if (enodeDnsConfiguration == null) {
enodeDnsConfiguration = unstableDnsOptions.toDomainObject(); enodeDnsConfiguration = unstableDnsOptions.toDomainObject();
@ -3191,6 +3304,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
}); });
} }
/**
* Check if required ports are available
*
* @throws InvalidConfigurationException if ports are not available.
*/
protected void checkIfRequiredPortsAreAvailable() { protected void checkIfRequiredPortsAreAvailable() {
final List<Integer> unavailablePorts = new ArrayList<>(); final List<Integer> unavailablePorts = new ArrayList<>();
getEffectivePorts().stream() getEffectivePorts().stream()
@ -3343,6 +3461,8 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
return genesisConfigOptions.getEcCurve(); return genesisConfigOptions.getEcCurve();
} }
/** Enables Go Quorum Compatibility mode. Visible for testing. */
@VisibleForTesting
protected void enableGoQuorumCompatibilityMode() { protected void enableGoQuorumCompatibilityMode() {
// this static flag is read by the RLP decoder // this static flag is read by the RLP decoder
GoQuorumOptions.setGoQuorumCompatibilityMode(true); GoQuorumOptions.setGoQuorumCompatibilityMode(true);
@ -3415,7 +3535,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
return engineRPCOptionGroup.overrideEngineRpcEnabled || isMergeEnabled(); return engineRPCOptionGroup.overrideEngineRpcEnabled || isMergeEnabled();
} }
public static List<String> getJDKEnabledCipherSuites() { private static List<String> getJDKEnabledCipherSuites() {
try { try {
final SSLContext context = SSLContext.getInstance("TLS"); final SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null); context.init(null, null, null);
@ -3426,7 +3546,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
} }
} }
public static List<String> getJDKEnabledProtocols() { private static List<String> getJDKEnabledProtocols() {
try { try {
final SSLContext context = SSLContext.getInstance("TLS"); final SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null); context.init(null, null, null);

@ -26,6 +26,7 @@ import oshi.PlatformEnum;
import oshi.SystemInfo; import oshi.SystemInfo;
import oshi.hardware.HardwareAbstractionLayer; import oshi.hardware.HardwareAbstractionLayer;
/** The Configuration overview builder. */
public class ConfigurationOverviewBuilder { public class ConfigurationOverviewBuilder {
private String network; private String network;
private String dataStorage; private String dataStorage;
@ -36,46 +37,98 @@ public class ConfigurationOverviewBuilder {
private Collection<String> engineApis; private Collection<String> engineApis;
private boolean isHighSpec = false; private boolean isHighSpec = false;
/**
* Sets network.
*
* @param network the network
* @return the network
*/
public ConfigurationOverviewBuilder setNetwork(final String network) { public ConfigurationOverviewBuilder setNetwork(final String network) {
this.network = network; this.network = network;
return this; return this;
} }
/**
* Sets data storage.
*
* @param dataStorage the data storage
* @return the data storage
*/
public ConfigurationOverviewBuilder setDataStorage(final String dataStorage) { public ConfigurationOverviewBuilder setDataStorage(final String dataStorage) {
this.dataStorage = dataStorage; this.dataStorage = dataStorage;
return this; return this;
} }
/**
* Sets sync mode.
*
* @param syncMode the sync mode
* @return the sync mode
*/
public ConfigurationOverviewBuilder setSyncMode(final String syncMode) { public ConfigurationOverviewBuilder setSyncMode(final String syncMode) {
this.syncMode = syncMode; this.syncMode = syncMode;
return this; return this;
} }
/**
* Sets rpc port.
*
* @param rpcPort the rpc port
* @return the rpc port
*/
public ConfigurationOverviewBuilder setRpcPort(final Integer rpcPort) { public ConfigurationOverviewBuilder setRpcPort(final Integer rpcPort) {
this.rpcPort = rpcPort; this.rpcPort = rpcPort;
return this; return this;
} }
/**
* Sets rpc http apis.
*
* @param rpcHttpApis the rpc http apis
* @return the rpc http apis
*/
public ConfigurationOverviewBuilder setRpcHttpApis(final Collection<String> rpcHttpApis) { public ConfigurationOverviewBuilder setRpcHttpApis(final Collection<String> rpcHttpApis) {
this.rpcHttpApis = rpcHttpApis; this.rpcHttpApis = rpcHttpApis;
return this; return this;
} }
/**
* Sets engine port.
*
* @param enginePort the engine port
* @return the engine port
*/
public ConfigurationOverviewBuilder setEnginePort(final Integer enginePort) { public ConfigurationOverviewBuilder setEnginePort(final Integer enginePort) {
this.enginePort = enginePort; this.enginePort = enginePort;
return this; return this;
} }
/**
* Sets engine apis.
*
* @param engineApis the engine apis
* @return the engine apis
*/
public ConfigurationOverviewBuilder setEngineApis(final Collection<String> engineApis) { public ConfigurationOverviewBuilder setEngineApis(final Collection<String> engineApis) {
this.engineApis = engineApis; this.engineApis = engineApis;
return this; return this;
} }
/**
* Sets high spec enabled.
*
* @return the high spec enabled
*/
public ConfigurationOverviewBuilder setHighSpecEnabled() { public ConfigurationOverviewBuilder setHighSpecEnabled() {
isHighSpec = true; isHighSpec = true;
return this; return this;
} }
/**
* Build configuration overview.
*
* @return the string representing configuration overview
*/
public String build() { public String build() {
final List<String> lines = new ArrayList<>(); final List<String> lines = new ArrayList<>();
lines.add("Besu " + BesuInfo.class.getPackage().getImplementationVersion()); lines.add("Besu " + BesuInfo.class.getPackage().getImplementationVersion());

@ -32,43 +32,82 @@ import java.util.List;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import picocli.CommandLine; import picocli.CommandLine;
/** The interface Default command values. */
public interface DefaultCommandValues { public interface DefaultCommandValues {
/** The constant CONFIG_FILE_OPTION_NAME. */
String CONFIG_FILE_OPTION_NAME = "--config-file"; String CONFIG_FILE_OPTION_NAME = "--config-file";
/** The constant MANDATORY_PATH_FORMAT_HELP. */
String MANDATORY_PATH_FORMAT_HELP = "<PATH>"; String MANDATORY_PATH_FORMAT_HELP = "<PATH>";
/** The constant MANDATORY_FILE_FORMAT_HELP. */
String MANDATORY_FILE_FORMAT_HELP = "<FILE>"; String MANDATORY_FILE_FORMAT_HELP = "<FILE>";
/** The constant MANDATORY_DIRECTORY_FORMAT_HELP. */
String MANDATORY_DIRECTORY_FORMAT_HELP = "<DIRECTORY>"; String MANDATORY_DIRECTORY_FORMAT_HELP = "<DIRECTORY>";
/** The constant BESU_HOME_PROPERTY_NAME. */
String BESU_HOME_PROPERTY_NAME = "besu.home"; String BESU_HOME_PROPERTY_NAME = "besu.home";
/** The constant DEFAULT_DATA_DIR_PATH. */
String DEFAULT_DATA_DIR_PATH = "./build/data"; String DEFAULT_DATA_DIR_PATH = "./build/data";
/** The constant MANDATORY_INTEGER_FORMAT_HELP. */
String MANDATORY_INTEGER_FORMAT_HELP = "<INTEGER>"; String MANDATORY_INTEGER_FORMAT_HELP = "<INTEGER>";
/** The constant MANDATORY_DOUBLE_FORMAT_HELP. */
String MANDATORY_DOUBLE_FORMAT_HELP = "<DOUBLE>"; String MANDATORY_DOUBLE_FORMAT_HELP = "<DOUBLE>";
/** The constant MANDATORY_LONG_FORMAT_HELP. */
String MANDATORY_LONG_FORMAT_HELP = "<LONG>"; String MANDATORY_LONG_FORMAT_HELP = "<LONG>";
/** The constant MANDATORY_MODE_FORMAT_HELP. */
String MANDATORY_MODE_FORMAT_HELP = "<MODE>"; String MANDATORY_MODE_FORMAT_HELP = "<MODE>";
/** The constant MANDATORY_NETWORK_FORMAT_HELP. */
String MANDATORY_NETWORK_FORMAT_HELP = "<NETWORK>"; String MANDATORY_NETWORK_FORMAT_HELP = "<NETWORK>";
/** The constant MANDATORY_NODE_ID_FORMAT_HELP. */
String MANDATORY_NODE_ID_FORMAT_HELP = "<NODEID>"; String MANDATORY_NODE_ID_FORMAT_HELP = "<NODEID>";
/** The constant DEFAULT_MIN_TRANSACTION_GAS_PRICE. */
Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000); Wei DEFAULT_MIN_TRANSACTION_GAS_PRICE = Wei.of(1000);
/** The constant DEFAULT_RPC_TX_FEE_CAP. */
Wei DEFAULT_RPC_TX_FEE_CAP = TransactionPoolConfiguration.DEFAULT_RPC_TX_FEE_CAP; Wei DEFAULT_RPC_TX_FEE_CAP = TransactionPoolConfiguration.DEFAULT_RPC_TX_FEE_CAP;
/** The constant DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO. */
Double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8; Double DEFAULT_MIN_BLOCK_OCCUPANCY_RATIO = 0.8;
/** The constant DEFAULT_EXTRA_DATA. */
Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY; Bytes DEFAULT_EXTRA_DATA = Bytes.EMPTY;
/** The constant PERMISSIONING_CONFIG_LOCATION. */
String PERMISSIONING_CONFIG_LOCATION = "permissions_config.toml"; String PERMISSIONING_CONFIG_LOCATION = "permissions_config.toml";
/** The constant MANDATORY_HOST_FORMAT_HELP. */
String MANDATORY_HOST_FORMAT_HELP = "<HOST>"; String MANDATORY_HOST_FORMAT_HELP = "<HOST>";
/** The constant MANDATORY_PORT_FORMAT_HELP. */
String MANDATORY_PORT_FORMAT_HELP = "<PORT>"; String MANDATORY_PORT_FORMAT_HELP = "<PORT>";
/** The constant DEFAULT_NAT_METHOD. */
NatMethod DEFAULT_NAT_METHOD = NatMethod.AUTO; NatMethod DEFAULT_NAT_METHOD = NatMethod.AUTO;
/** The constant DEFAULT_JWT_ALGORITHM. */
JwtAlgorithm DEFAULT_JWT_ALGORITHM = JwtAlgorithm.RS256; JwtAlgorithm DEFAULT_JWT_ALGORITHM = JwtAlgorithm.RS256;
/** The constant FAST_SYNC_MIN_PEER_COUNT. */
int FAST_SYNC_MIN_PEER_COUNT = 5; int FAST_SYNC_MIN_PEER_COUNT = 5;
/** The constant DEFAULT_MAX_PEERS. */
int DEFAULT_MAX_PEERS = 25; int DEFAULT_MAX_PEERS = 25;
/** The constant DEFAULT_P2P_PEER_LOWER_BOUND. */
int DEFAULT_P2P_PEER_LOWER_BOUND = 25; int DEFAULT_P2P_PEER_LOWER_BOUND = 25;
/** The constant DEFAULT_HTTP_MAX_CONNECTIONS. */
int DEFAULT_HTTP_MAX_CONNECTIONS = 80; int DEFAULT_HTTP_MAX_CONNECTIONS = 80;
/** The constant DEFAULT_WS_MAX_CONNECTIONS. */
int DEFAULT_WS_MAX_CONNECTIONS = 80; int DEFAULT_WS_MAX_CONNECTIONS = 80;
/** The constant DEFAULT_WS_MAX_FRAME_SIZE. */
int DEFAULT_WS_MAX_FRAME_SIZE = 1024 * 1024; int DEFAULT_WS_MAX_FRAME_SIZE = 1024 * 1024;
/** The constant DEFAULT_FRACTION_REMOTE_WIRE_CONNECTIONS_ALLOWED. */
float DEFAULT_FRACTION_REMOTE_WIRE_CONNECTIONS_ALLOWED = float DEFAULT_FRACTION_REMOTE_WIRE_CONNECTIONS_ALLOWED =
RlpxConfiguration.DEFAULT_FRACTION_REMOTE_CONNECTIONS_ALLOWED; RlpxConfiguration.DEFAULT_FRACTION_REMOTE_CONNECTIONS_ALLOWED;
/** The constant DEFAULT_KEY_VALUE_STORAGE_NAME. */
String DEFAULT_KEY_VALUE_STORAGE_NAME = "rocksdb"; String DEFAULT_KEY_VALUE_STORAGE_NAME = "rocksdb";
/** The constant DEFAULT_SECURITY_MODULE. */
String DEFAULT_SECURITY_MODULE = "localfile"; String DEFAULT_SECURITY_MODULE = "localfile";
/** The constant DEFAULT_KEYSTORE_TYPE. */
String DEFAULT_KEYSTORE_TYPE = "JKS"; String DEFAULT_KEYSTORE_TYPE = "JKS";
/** The Default tls protocols. */
List<String> DEFAULT_TLS_PROTOCOLS = List.of("TLSv1.3", "TLSv1.2"); List<String> DEFAULT_TLS_PROTOCOLS = List.of("TLSv1.3", "TLSv1.2");
/**
* Gets default besu data path.
*
* @param command the command
* @return the default besu data path
*/
static Path getDefaultBesuDataPath(final Object command) { static Path getDefaultBesuDataPath(final Object command) {
// this property is retrieved from Gradle tasks or Besu running shell script. // this property is retrieved from Gradle tasks or Besu running shell script.
final String besuHomeProperty = System.getProperty(BESU_HOME_PROPERTY_NAME); final String besuHomeProperty = System.getProperty(BESU_HOME_PROPERTY_NAME);

@ -19,8 +19,15 @@ import org.hyperledger.besu.util.log.FramedLogMessage;
import java.util.List; import java.util.List;
/** The Network deprecation message. */
public class NetworkDeprecationMessage { public class NetworkDeprecationMessage {
/**
* Generate deprecation message for specified testnet network.
*
* @param network the network
* @return the deprecation message for specified network
*/
public static String generate(final NetworkName network) { public static String generate(final NetworkName network) {
if (network.getDeprecationDate().isEmpty()) { if (network.getDeprecationDate().isEmpty()) {
throw new AssertionError("Deprecation date is not set. Cannot print a deprecation message"); throw new AssertionError("Deprecation date is not set. Cannot print a deprecation message");

@ -30,6 +30,7 @@ import java.util.Objects;
import java.util.Optional; import java.util.Optional;
import java.util.stream.Collectors; import java.util.stream.Collectors;
/** The Eth network config. */
public class EthNetworkConfig { public class EthNetworkConfig {
private final String genesisConfig; private final String genesisConfig;
@ -37,6 +38,14 @@ public class EthNetworkConfig {
private final List<EnodeURL> bootNodes; private final List<EnodeURL> bootNodes;
private final String dnsDiscoveryUrl; private final String dnsDiscoveryUrl;
/**
* Instantiates a new Eth network config.
*
* @param genesisConfig the genesis config
* @param networkId the network id
* @param bootNodes the boot nodes
* @param dnsDiscoveryUrl the dns discovery url
*/
public EthNetworkConfig( public EthNetworkConfig(
final String genesisConfig, final String genesisConfig,
final BigInteger networkId, final BigInteger networkId,
@ -50,18 +59,38 @@ public class EthNetworkConfig {
this.dnsDiscoveryUrl = dnsDiscoveryUrl; this.dnsDiscoveryUrl = dnsDiscoveryUrl;
} }
/**
* Gets genesis config.
*
* @return the genesis config
*/
public String getGenesisConfig() { public String getGenesisConfig() {
return genesisConfig; return genesisConfig;
} }
/**
* Gets network id.
*
* @return the network id
*/
public BigInteger getNetworkId() { public BigInteger getNetworkId() {
return networkId; return networkId;
} }
/**
* Gets boot nodes.
*
* @return the boot nodes
*/
public List<EnodeURL> getBootNodes() { public List<EnodeURL> getBootNodes() {
return bootNodes; return bootNodes;
} }
/**
* Gets dns discovery url.
*
* @return the dns discovery url
*/
public String getDnsDiscoveryUrl() { public String getDnsDiscoveryUrl() {
return dnsDiscoveryUrl; return dnsDiscoveryUrl;
} }
@ -100,6 +129,12 @@ public class EthNetworkConfig {
+ '}'; + '}';
} }
/**
* Gets network config.
*
* @param networkName the network name
* @return the network config
*/
public static EthNetworkConfig getNetworkConfig(final NetworkName networkName) { public static EthNetworkConfig getNetworkConfig(final NetworkName networkName) {
final String genesisContent = jsonConfig(networkName.getGenesisFile()); final String genesisContent = jsonConfig(networkName.getGenesisFile());
final GenesisConfigOptions genesisConfigOptions = final GenesisConfigOptions genesisConfigOptions =
@ -128,10 +163,17 @@ public class EthNetworkConfig {
} }
} }
/**
* Json config string.
*
* @param network the network
* @return the string
*/
public static String jsonConfig(final NetworkName network) { public static String jsonConfig(final NetworkName network) {
return jsonConfig(network.getGenesisFile()); return jsonConfig(network.getGenesisFile());
} }
/** The type Builder. */
public static class Builder { public static class Builder {
private String dnsDiscoveryUrl; private String dnsDiscoveryUrl;
@ -139,6 +181,11 @@ public class EthNetworkConfig {
private BigInteger networkId; private BigInteger networkId;
private List<EnodeURL> bootNodes; private List<EnodeURL> bootNodes;
/**
* Instantiates a new Builder.
*
* @param ethNetworkConfig the eth network config
*/
public Builder(final EthNetworkConfig ethNetworkConfig) { public Builder(final EthNetworkConfig ethNetworkConfig) {
this.genesisConfig = ethNetworkConfig.genesisConfig; this.genesisConfig = ethNetworkConfig.genesisConfig;
this.networkId = ethNetworkConfig.networkId; this.networkId = ethNetworkConfig.networkId;
@ -146,26 +193,55 @@ public class EthNetworkConfig {
this.dnsDiscoveryUrl = ethNetworkConfig.dnsDiscoveryUrl; this.dnsDiscoveryUrl = ethNetworkConfig.dnsDiscoveryUrl;
} }
/**
* Sets genesis config.
*
* @param genesisConfig the genesis config
* @return the genesis config
*/
public Builder setGenesisConfig(final String genesisConfig) { public Builder setGenesisConfig(final String genesisConfig) {
this.genesisConfig = genesisConfig; this.genesisConfig = genesisConfig;
return this; return this;
} }
/**
* Sets network id.
*
* @param networkId the network id
* @return the network id
*/
public Builder setNetworkId(final BigInteger networkId) { public Builder setNetworkId(final BigInteger networkId) {
this.networkId = networkId; this.networkId = networkId;
return this; return this;
} }
/**
* Sets boot nodes.
*
* @param bootNodes the boot nodes
* @return the boot nodes
*/
public Builder setBootNodes(final List<EnodeURL> bootNodes) { public Builder setBootNodes(final List<EnodeURL> bootNodes) {
this.bootNodes = bootNodes; this.bootNodes = bootNodes;
return this; return this;
} }
/**
* Sets dns discovery url.
*
* @param dnsDiscoveryUrl the dns discovery url
* @return the dns discovery url
*/
public Builder setDnsDiscoveryUrl(final String dnsDiscoveryUrl) { public Builder setDnsDiscoveryUrl(final String dnsDiscoveryUrl) {
this.dnsDiscoveryUrl = dnsDiscoveryUrl; this.dnsDiscoveryUrl = dnsDiscoveryUrl;
return this; return this;
} }
/**
* Build eth network config.
*
* @return the eth network config
*/
public EthNetworkConfig build() { public EthNetworkConfig build() {
return new EthNetworkConfig(genesisConfig, networkId, bootNodes, dnsDiscoveryUrl); return new EthNetworkConfig(genesisConfig, networkId, bootNodes, dnsDiscoveryUrl);
} }

@ -19,17 +19,29 @@ import java.util.Optional;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
/** The enum Network name. */
public enum NetworkName { public enum NetworkName {
/** Mainnet network name. */
MAINNET("/mainnet.json", BigInteger.valueOf(1)), MAINNET("/mainnet.json", BigInteger.valueOf(1)),
/** Rinkeby network name. */
RINKEBY("/rinkeby.json", BigInteger.valueOf(4)), RINKEBY("/rinkeby.json", BigInteger.valueOf(4)),
/** Sepolia network name. */
SEPOLIA("/sepolia.json", BigInteger.valueOf(11155111)), SEPOLIA("/sepolia.json", BigInteger.valueOf(11155111)),
/** Goerli network name. */
GOERLI("/goerli.json", BigInteger.valueOf(5)), GOERLI("/goerli.json", BigInteger.valueOf(5)),
/** Dev network name. */
DEV("/dev.json", BigInteger.valueOf(2018), false), DEV("/dev.json", BigInteger.valueOf(2018), false),
/** Future EIPs network name. */
FUTURE_EIPS("/future.json", BigInteger.valueOf(2022), false), FUTURE_EIPS("/future.json", BigInteger.valueOf(2022), false),
/** Experimental EIPs network name. */
EXPERIMENTAL_EIPS("/experimental.json", BigInteger.valueOf(2023), false), EXPERIMENTAL_EIPS("/experimental.json", BigInteger.valueOf(2023), false),
/** Classic network name. */
CLASSIC("/classic.json", BigInteger.valueOf(1)), CLASSIC("/classic.json", BigInteger.valueOf(1)),
/** Kotti network name. */
KOTTI("/kotti.json", BigInteger.valueOf(6)), KOTTI("/kotti.json", BigInteger.valueOf(6)),
/** Mordor network name. */
MORDOR("/mordor.json", BigInteger.valueOf(7)), MORDOR("/mordor.json", BigInteger.valueOf(7)),
/** Ecip 1049 dev network name. */
ECIP1049_DEV("/ecip1049_dev.json", BigInteger.valueOf(2021)); ECIP1049_DEV("/ecip1049_dev.json", BigInteger.valueOf(2021));
private final String genesisFile; private final String genesisFile;
@ -62,26 +74,56 @@ public enum NetworkName {
} }
} }
/**
* Gets genesis file.
*
* @return the genesis file
*/
public String getGenesisFile() { public String getGenesisFile() {
return genesisFile; return genesisFile;
} }
/**
* Gets network id.
*
* @return the network id
*/
public BigInteger getNetworkId() { public BigInteger getNetworkId() {
return networkId; return networkId;
} }
/**
* Can fast sync boolean.
*
* @return the boolean
*/
public boolean canFastSync() { public boolean canFastSync() {
return canFastSync; return canFastSync;
} }
/**
* Normalize string.
*
* @return the string
*/
public String normalize() { public String normalize() {
return StringUtils.capitalize(name().toLowerCase()); return StringUtils.capitalize(name().toLowerCase());
} }
/**
* Is deprecated boolean.
*
* @return the boolean
*/
public boolean isDeprecated() { public boolean isDeprecated() {
return deprecationDate != null; return deprecationDate != null;
} }
/**
* Gets deprecation date.
*
* @return the deprecation date
*/
public Optional<String> getDeprecationDate() { public Optional<String> getDeprecationDate() {
return Optional.ofNullable(deprecationDate); return Optional.ofNullable(deprecationDate);
} }

@ -19,6 +19,7 @@ import org.hyperledger.besu.util.number.Fraction;
import picocli.CommandLine; import picocli.CommandLine;
/** The Fraction converter to convert floats in CLI. */
public class FractionConverter implements CommandLine.ITypeConverter<Float> { public class FractionConverter implements CommandLine.ITypeConverter<Float> {
@Override @Override

@ -23,6 +23,7 @@ import java.util.Map;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import picocli.CommandLine; import picocli.CommandLine;
/** The Metric category converter for CLI options. */
public class MetricCategoryConverter implements CommandLine.ITypeConverter<MetricCategory> { public class MetricCategoryConverter implements CommandLine.ITypeConverter<MetricCategory> {
private final Map<String, MetricCategory> metricCategories = new HashMap<>(); private final Map<String, MetricCategory> metricCategories = new HashMap<>();
@ -36,15 +37,31 @@ public class MetricCategoryConverter implements CommandLine.ITypeConverter<Metri
return category; return category;
} }
/**
* Add Metrics categories.
*
* @param <T> the type parameter
* @param categoryEnum the category enum
*/
public <T extends Enum<T> & MetricCategory> void addCategories(final Class<T> categoryEnum) { public <T extends Enum<T> & MetricCategory> void addCategories(final Class<T> categoryEnum) {
EnumSet.allOf(categoryEnum) EnumSet.allOf(categoryEnum)
.forEach(category -> metricCategories.put(category.name(), category)); .forEach(category -> metricCategories.put(category.name(), category));
} }
/**
* Add registry category.
*
* @param metricCategory the metric category
*/
public void addRegistryCategory(final MetricCategory metricCategory) { public void addRegistryCategory(final MetricCategory metricCategory) {
metricCategories.put(metricCategory.getName().toUpperCase(), metricCategory); metricCategories.put(metricCategory.getName().toUpperCase(), metricCategory);
} }
/**
* Gets metric categories.
*
* @return the metric categories
*/
@VisibleForTesting @VisibleForTesting
Map<String, MetricCategory> getMetricCategories() { Map<String, MetricCategory> getMetricCategories() {
return metricCategories; return metricCategories;

@ -19,6 +19,7 @@ import org.hyperledger.besu.util.number.Percentage;
import picocli.CommandLine; import picocli.CommandLine;
/** The Percentage Cli type converter. */
public class PercentageConverter implements CommandLine.ITypeConverter<Integer> { public class PercentageConverter implements CommandLine.ITypeConverter<Integer> {
@Override @Override

@ -16,8 +16,14 @@ package org.hyperledger.besu.cli.converter.exception;
import static java.lang.String.format; import static java.lang.String.format;
/** The custom Fraction conversion exception. */
public final class FractionConversionException extends Exception { public final class FractionConversionException extends Exception {
/**
* Instantiates a new Fraction conversion exception.
*
* @param value the value
*/
public FractionConversionException(final String value) { public FractionConversionException(final String value) {
super(format("Invalid value: %s, should be a decimal between 0.0 and 1.0 inclusive.", value)); super(format("Invalid value: %s, should be a decimal between 0.0 and 1.0 inclusive.", value));
} }

@ -16,8 +16,14 @@ package org.hyperledger.besu.cli.converter.exception;
import static java.lang.String.format; import static java.lang.String.format;
/** The custom Percentage conversion exception. */
public final class PercentageConversionException extends Exception { public final class PercentageConversionException extends Exception {
/**
* Instantiates a new Percentage conversion exception.
*
* @param value the invalid value to add in exception message
*/
public PercentageConversionException(final String value) { public PercentageConversionException(final String value) {
super(format("Invalid value: %s, should be a number between 0 and 100 inclusive.", value)); super(format("Invalid value: %s, should be a number between 0 and 100 inclusive.", value));
} }

@ -16,8 +16,14 @@ package org.hyperledger.besu.cli.converter.exception;
import static java.lang.String.format; import static java.lang.String.format;
/** The custom Rpc Apis conversion exception. */
public final class RpcApisConversionException extends Exception { public final class RpcApisConversionException extends Exception {
/**
* Instantiates a new Rpc apis conversion exception.
*
* @param name the invalid Rpc Api name to report in exception message
*/
public RpcApisConversionException(final String name) { public RpcApisConversionException(final String name) {
super(format("Invalid value: %s", name)); super(format("Invalid value: %s", name));
} }

@ -28,10 +28,12 @@ import javax.annotation.Nonnull;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.base.Strings; import com.google.common.base.Strings;
/** The Cors allowed origins property used in CLI */
public class CorsAllowedOriginsProperty extends AbstractList<String> { public class CorsAllowedOriginsProperty extends AbstractList<String> {
private final List<String> domains = new ArrayList<>(); private final List<String> domains = new ArrayList<>();
/** Instantiates a new Cors allowed origins property. */
public CorsAllowedOriginsProperty() {} public CorsAllowedOriginsProperty() {}
@Override @Override

@ -22,14 +22,21 @@ import java.util.function.Function;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import picocli.CommandLine.ITypeConverter; import picocli.CommandLine.ITypeConverter;
/** The Enode to uri property converter. */
public class EnodeToURIPropertyConverter implements ITypeConverter<URI> { public class EnodeToURIPropertyConverter implements ITypeConverter<URI> {
private final Function<String, URI> converter; private final Function<String, URI> converter;
/** Instantiates a new Enode to uri property converter. */
EnodeToURIPropertyConverter() { EnodeToURIPropertyConverter() {
this.converter = (s) -> EnodeURLImpl.fromString(s).toURI(); this.converter = (s) -> EnodeURLImpl.fromString(s).toURI();
} }
/**
* Instantiates a new Enode to uri property converter.
*
* @param converter the converter
*/
@VisibleForTesting @VisibleForTesting
EnodeToURIPropertyConverter(final Function<String, URI> converter) { EnodeToURIPropertyConverter(final Function<String, URI> converter) {
this.converter = converter; this.converter = converter;

@ -25,10 +25,12 @@ import javax.annotation.Nonnull;
import com.google.common.base.Splitter; import com.google.common.base.Splitter;
import com.google.common.base.Strings; import com.google.common.base.Strings;
/** The Json Rpc allowlist hosts list for CLI option. */
public class JsonRPCAllowlistHostsProperty extends AbstractList<String> { public class JsonRPCAllowlistHostsProperty extends AbstractList<String> {
private final List<String> hostnamesAllowlist = new ArrayList<>(); private final List<String> hostnamesAllowlist = new ArrayList<>();
/** Instantiates a new Json rpc allowlist hosts property. */
public JsonRPCAllowlistHostsProperty() {} public JsonRPCAllowlistHostsProperty() {}
@Override @Override

@ -27,8 +27,17 @@ import org.apache.tuweni.toml.TomlParseResult;
import picocli.CommandLine; import picocli.CommandLine;
import picocli.CommandLine.ParameterException; import picocli.CommandLine.ParameterException;
/** The Rpc authentication file validator. */
public class RpcAuthFileValidator { public class RpcAuthFileValidator {
/**
* Validate auth file.
*
* @param commandLine the command line to use for parameter exceptions
* @param filename the auth file
* @param type the RPC type
* @return the auth filename
*/
public static String validate( public static String validate(
final CommandLine commandLine, final String filename, final String type) { final CommandLine commandLine, final String filename, final String type) {

@ -18,6 +18,7 @@ import picocli.CommandLine;
import picocli.CommandLine.IExecutionExceptionHandler; import picocli.CommandLine.IExecutionExceptionHandler;
import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.CommandSpec;
/** Custom Execution Exception Handler used by PicoCLI framework. */
public class BesuExecutionExceptionHandler implements IExecutionExceptionHandler { public class BesuExecutionExceptionHandler implements IExecutionExceptionHandler {
@Override @Override
public int handleExecutionException( public int handleExecutionException(

@ -21,10 +21,16 @@ import org.apache.logging.log4j.Level;
import picocli.CommandLine; import picocli.CommandLine;
import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.CommandSpec;
/** The custom parameter exception handler for Besu PicoCLI. */
public class BesuParameterExceptionHandler implements CommandLine.IParameterExceptionHandler { public class BesuParameterExceptionHandler implements CommandLine.IParameterExceptionHandler {
private final Supplier<Level> levelSupplier; private final Supplier<Level> levelSupplier;
/**
* Instantiates a new Besu parameter exception handler.
*
* @param levelSupplier the logging level supplier
*/
public BesuParameterExceptionHandler(final Supplier<Level> levelSupplier) { public BesuParameterExceptionHandler(final Supplier<Level> levelSupplier) {
this.levelSupplier = levelSupplier; this.levelSupplier = levelSupplier;
} }

@ -19,6 +19,7 @@ import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationFactory; import org.apache.logging.log4j.core.config.ConfigurationFactory;
import org.apache.logging.log4j.core.config.ConfigurationSource; import org.apache.logging.log4j.core.config.ConfigurationSource;
/** Custom Log4J Configuration Factory for Besu */
public class BesuLoggingConfigurationFactory extends ConfigurationFactory { public class BesuLoggingConfigurationFactory extends ConfigurationFactory {
@Override @Override

@ -29,8 +29,15 @@ import org.apache.logging.log4j.core.layout.PatternLayout;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Xml extension configuration for Logging framework. */
public class XmlExtensionConfiguration extends XmlConfiguration { public class XmlExtensionConfiguration extends XmlConfiguration {
/**
* Instantiates a new Xml extension configuration.
*
* @param loggerContext the logger context
* @param configSource the Configuration Source
*/
public XmlExtensionConfiguration( public XmlExtensionConfiguration(
final LoggerContext loggerContext, final ConfigurationSource configSource) { final LoggerContext loggerContext, final ConfigurationSource configSource) {
super(loggerContext, configSource); super(loggerContext, configSource);

@ -22,34 +22,77 @@ import com.google.common.base.Splitter;
import com.google.common.collect.Range; import com.google.common.collect.Range;
import org.apache.tuweni.units.bigints.UInt256; import org.apache.tuweni.units.bigints.UInt256;
/** The Option parser. */
public class OptionParser { public class OptionParser {
/**
* Parse long range range.
*
* @param arg the arg
* @return the range
*/
public static Range<Long> parseLongRange(final String arg) { public static Range<Long> parseLongRange(final String arg) {
checkArgument(arg.matches("-?\\d+\\.\\.-?\\d+")); checkArgument(arg.matches("-?\\d+\\.\\.-?\\d+"));
final Iterator<String> ends = Splitter.on("..").split(arg).iterator(); final Iterator<String> ends = Splitter.on("..").split(arg).iterator();
return Range.closed(parseLong(ends.next()), parseLong(ends.next())); return Range.closed(parseLong(ends.next()), parseLong(ends.next()));
} }
/**
* Parse long from String.
*
* @param arg long value to parse from String
* @return the long
*/
public static long parseLong(final String arg) { public static long parseLong(final String arg) {
return Long.parseLong(arg, 10); return Long.parseLong(arg, 10);
} }
/**
* Format Long values range.
*
* @param range the range
* @return the string
*/
public static String format(final Range<Long> range) { public static String format(final Range<Long> range) {
return format(range.lowerEndpoint()) + ".." + format(range.upperEndpoint()); return format(range.lowerEndpoint()) + ".." + format(range.upperEndpoint());
} }
/**
* Format int to String.
*
* @param value the value
* @return the string
*/
public static String format(final int value) { public static String format(final int value) {
return Integer.toString(value, 10); return Integer.toString(value, 10);
} }
/**
* Format long to String.
*
* @param value the value
* @return the string
*/
public static String format(final long value) { public static String format(final long value) {
return Long.toString(value, 10); return Long.toString(value, 10);
} }
/**
* Format float to string.
*
* @param value the value
* @return the string
*/
public static String format(final float value) { public static String format(final float value) {
return Float.toString(value); return Float.toString(value);
} }
/**
* Format UInt256 to string.
*
* @param value the value
* @return the string
*/
public static String format(final UInt256 value) { public static String format(final UInt256 value) {
return value.toBigInteger().toString(10); return value.toBigInteger().toString(10);
} }

@ -29,6 +29,7 @@ import java.util.List;
import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.StringUtils;
import picocli.CommandLine.Option; import picocli.CommandLine.Option;
/** The Data storage CLI options. */
public class DataStorageOptions implements CLIOptions<DataStorageConfiguration> { public class DataStorageOptions implements CLIOptions<DataStorageConfiguration> {
private static final String DATA_STORAGE_FORMAT = "--data-storage-format"; private static final String DATA_STORAGE_FORMAT = "--data-storage-format";
@ -63,6 +64,11 @@ public class DataStorageOptions implements CLIOptions<DataStorageConfiguration>
arity = "1") arity = "1")
private final Boolean bonsaiUseSnapshots = DEFAULT_BONSAI_USE_SNAPSHOTS; private final Boolean bonsaiUseSnapshots = DEFAULT_BONSAI_USE_SNAPSHOTS;
/**
* Create data storage options.
*
* @return the data storage options
*/
public static DataStorageOptions create() { public static DataStorageOptions create() {
return new DataStorageOptions(); return new DataStorageOptions();
} }
@ -87,6 +93,11 @@ public class DataStorageOptions implements CLIOptions<DataStorageConfiguration>
bonsaiUseSnapshots.toString()); bonsaiUseSnapshots.toString());
} }
/**
* Normalize data storage format string.
*
* @return the normalized string
*/
public String normalizeDataStorageFormat() { public String normalizeDataStorageFormat() {
return StringUtils.capitalize(dataStorageFormat.toString().toLowerCase()); return StringUtils.capitalize(dataStorageFormat.toString().toLowerCase());
} }

@ -22,6 +22,7 @@ import java.util.List;
import picocli.CommandLine; import picocli.CommandLine;
/** The Ethstats CLI options. */
public class EthstatsOptions implements CLIOptions<NetstatsUrl> { public class EthstatsOptions implements CLIOptions<NetstatsUrl> {
private static final String ETHSTATS = "--ethstats"; private static final String ETHSTATS = "--ethstats";
@ -44,6 +45,11 @@ public class EthstatsOptions implements CLIOptions<NetstatsUrl> {
private EthstatsOptions() {} private EthstatsOptions() {}
/**
* Create ethstats options.
*
* @return the ethstats options
*/
public static EthstatsOptions create() { public static EthstatsOptions create() {
return new EthstatsOptions(); return new EthstatsOptions();
} }
@ -53,10 +59,20 @@ public class EthstatsOptions implements CLIOptions<NetstatsUrl> {
return NetstatsUrl.fromParams(ethstatsUrl, ethstatsContact); return NetstatsUrl.fromParams(ethstatsUrl, ethstatsContact);
} }
/**
* Gets ethstats url.
*
* @return the ethstats url
*/
public String getEthstatsUrl() { public String getEthstatsUrl() {
return ethstatsUrl; return ethstatsUrl;
} }
/**
* Gets ethstats contact.
*
* @return the ethstats contact
*/
public String getEthstatsContact() { public String getEthstatsContact() {
return ethstatsContact; return ethstatsContact;
} }

@ -21,17 +21,30 @@ import picocli.CommandLine;
import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Spec; import picocli.CommandLine.Spec;
/** The Logging level CLI option. */
public class LoggingLevelOption { public class LoggingLevelOption {
/**
* Create logging level option.
*
* @return the logging level option
*/
public static LoggingLevelOption create() { public static LoggingLevelOption create() {
return new LoggingLevelOption(); return new LoggingLevelOption();
} }
private static final Set<String> ACCEPTED_VALUES = private static final Set<String> ACCEPTED_VALUES =
Set.of("OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", "ALL"); Set.of("OFF", "ERROR", "WARN", "INFO", "DEBUG", "TRACE", "ALL");
/** The Picocli CommandSpec. Visible for testing. Injected by Picocli framework at runtime. */
@Spec CommandSpec spec; @Spec CommandSpec spec;
private Level logLevel; private Level logLevel;
/**
* Sets log level.
*
* @param logLevel the log level
*/
@CommandLine.Option( @CommandLine.Option(
names = {"--logging", "-l"}, names = {"--logging", "-l"},
paramLabel = "<LOG VERBOSITY LEVEL>", paramLabel = "<LOG VERBOSITY LEVEL>",
@ -48,6 +61,11 @@ public class LoggingLevelOption {
} }
} }
/**
* Gets log level.
*
* @return the log level
*/
public Level getLogLevel() { public Level getLogLevel() {
return logLevel; return logLevel;
} }

@ -20,8 +20,14 @@ import java.io.File;
import picocli.CommandLine; import picocli.CommandLine;
/** The Node private key file Cli option. */
public class NodePrivateKeyFileOption { public class NodePrivateKeyFileOption {
/**
* Create node private key file option.
*
* @return the node private key file option
*/
public static NodePrivateKeyFileOption create() { public static NodePrivateKeyFileOption create() {
return new NodePrivateKeyFileOption(); return new NodePrivateKeyFileOption();
} }
@ -33,6 +39,11 @@ public class NodePrivateKeyFileOption {
"The node's private key file (default: a file named \"key\" in the Besu data directory)") "The node's private key file (default: a file named \"key\" in the Besu data directory)")
private final File nodePrivateKeyFile = null; private final File nodePrivateKeyFile = null;
/**
* Gets node private key file.
*
* @return the node private key file
*/
public File getNodePrivateKeyFile() { public File getNodePrivateKeyFile() {
return nodePrivateKeyFile; return nodePrivateKeyFile;
} }

@ -30,6 +30,7 @@ import picocli.CommandLine;
import picocli.CommandLine.Option; import picocli.CommandLine.Option;
import picocli.CommandLine.ParameterException; import picocli.CommandLine.ParameterException;
/** The P2P TLS Config Cli Options. */
public class P2PTLSConfigOptions { public class P2PTLSConfigOptions {
@Option( @Option(
names = {"--Xp2p-tls-enabled"}, names = {"--Xp2p-tls-enabled"},
@ -95,6 +96,12 @@ public class P2PTLSConfigOptions {
description = "Certificate revocation list for the P2P service.") description = "Certificate revocation list for the P2P service.")
private final Path p2pCrlFile = null; private final Path p2pCrlFile = null;
/**
* Generate P2p tls configuration.
*
* @param commandLine the command line object to report exceptions
* @return the optional TLSConfiguration
*/
public Optional<TLSConfiguration> p2pTLSConfiguration(final CommandLine commandLine) { public Optional<TLSConfiguration> p2pTLSConfiguration(final CommandLine commandLine) {
if (!p2pTLSEnabled) { if (!p2pTLSEnabled) {
return Optional.empty(); return Optional.empty();
@ -128,6 +135,12 @@ public class P2PTLSConfigOptions {
.build()); .build());
} }
/**
* Check P2P Tls options dependencies.
*
* @param logger the logger
* @param commandLine the command line
*/
public void checkP2PTLSOptionsDependencies(final Logger logger, final CommandLine commandLine) { public void checkP2PTLSOptionsDependencies(final Logger logger, final CommandLine commandLine) {
CommandLineUtils.checkOptionDependencies( CommandLineUtils.checkOptionDependencies(
logger, logger,

@ -24,12 +24,15 @@ import java.util.List;
import picocli.CommandLine; import picocli.CommandLine;
/** The Chain pruning CLI options. */
public class ChainPruningOptions implements CLIOptions<ChainPrunerConfiguration> { public class ChainPruningOptions implements CLIOptions<ChainPrunerConfiguration> {
private static final String CHAIN_PRUNING_ENABLED_FLAG = "--Xchain-pruning-enabled"; private static final String CHAIN_PRUNING_ENABLED_FLAG = "--Xchain-pruning-enabled";
private static final String CHAIN_PRUNING_BLOCKS_RETAINED_FLAG = private static final String CHAIN_PRUNING_BLOCKS_RETAINED_FLAG =
"--Xchain-pruning-blocks-retained"; "--Xchain-pruning-blocks-retained";
private static final String CHAIN_PRUNING_FREQUENCY_FLAG = "--Xchain-pruning-frequency"; private static final String CHAIN_PRUNING_FREQUENCY_FLAG = "--Xchain-pruning-frequency";
/** The constant DEFAULT_CHAIN_DATA_PRUNING_MIN_BLOCKS_RETAINED. */
public static final long DEFAULT_CHAIN_DATA_PRUNING_MIN_BLOCKS_RETAINED = 7200; public static final long DEFAULT_CHAIN_DATA_PRUNING_MIN_BLOCKS_RETAINED = 7200;
/** The constant DEFAULT_CHAIN_DATA_PRUNING_FREQUENCY. */
public static final int DEFAULT_CHAIN_DATA_PRUNING_FREQUENCY = 256; public static final int DEFAULT_CHAIN_DATA_PRUNING_FREQUENCY = 256;
@CommandLine.Option( @CommandLine.Option(
@ -57,14 +60,29 @@ public class ChainPruningOptions implements CLIOptions<ChainPrunerConfiguration>
private final PositiveNumber chainDataPruningBlocksFrequency = private final PositiveNumber chainDataPruningBlocksFrequency =
PositiveNumber.fromInt(DEFAULT_CHAIN_DATA_PRUNING_FREQUENCY); PositiveNumber.fromInt(DEFAULT_CHAIN_DATA_PRUNING_FREQUENCY);
/**
* Create chain pruning options.
*
* @return the chain pruning options
*/
public static ChainPruningOptions create() { public static ChainPruningOptions create() {
return new ChainPruningOptions(); return new ChainPruningOptions();
} }
/**
* Gets chain data pruning enabled.
*
* @return the chain data pruning enabled
*/
public Boolean getChainDataPruningEnabled() { public Boolean getChainDataPruningEnabled() {
return chainDataPruningEnabled; return chainDataPruningEnabled;
} }
/**
* Gets chain data pruning blocks retained.
*
* @return the chain data pruning blocks retained
*/
public Long getChainDataPruningBlocksRetained() { public Long getChainDataPruningBlocksRetained() {
return chainDataPruningBlocksRetained; return chainDataPruningBlocksRetained;
} }

@ -23,6 +23,7 @@ import java.util.List;
import picocli.CommandLine; import picocli.CommandLine;
/** The Dns CLI options. */
public class DnsOptions implements CLIOptions<EnodeDnsConfiguration> { public class DnsOptions implements CLIOptions<EnodeDnsConfiguration> {
private final String DNS_ENABLED = "--Xdns-enabled"; private final String DNS_ENABLED = "--Xdns-enabled";
@ -42,10 +43,21 @@ public class DnsOptions implements CLIOptions<EnodeDnsConfiguration> {
arity = "1") arity = "1")
private Boolean dnsUpdateEnabled = Boolean.FALSE; private Boolean dnsUpdateEnabled = Boolean.FALSE;
/**
* Create dns options.
*
* @return the dns options
*/
public static DnsOptions create() { public static DnsOptions create() {
return new DnsOptions(); return new DnsOptions();
} }
/**
* From config dns options.
*
* @param enodeDnsConfiguration the enode dns configuration
* @return the dns options
*/
public static DnsOptions fromConfig(final EnodeDnsConfiguration enodeDnsConfiguration) { public static DnsOptions fromConfig(final EnodeDnsConfiguration enodeDnsConfiguration) {
final DnsOptions cliOptions = new DnsOptions(); final DnsOptions cliOptions = new DnsOptions();
cliOptions.dnsEnabled = enodeDnsConfiguration.dnsEnabled(); cliOptions.dnsEnabled = enodeDnsConfiguration.dnsEnabled();
@ -53,10 +65,20 @@ public class DnsOptions implements CLIOptions<EnodeDnsConfiguration> {
return cliOptions; return cliOptions;
} }
/**
* Gets dns enabled.
*
* @return the dns enabled
*/
public Boolean getDnsEnabled() { public Boolean getDnsEnabled() {
return dnsEnabled; return dnsEnabled;
} }
/**
* Gets dns update enabled.
*
* @return the dns update enabled
*/
public Boolean getDnsUpdateEnabled() { public Boolean getDnsUpdateEnabled() {
return dnsUpdateEnabled; return dnsUpdateEnabled;
} }

@ -24,6 +24,7 @@ import java.util.List;
import picocli.CommandLine; import picocli.CommandLine;
/** The Eth protocol CLI options. */
public class EthProtocolOptions implements CLIOptions<EthProtocolConfiguration> { public class EthProtocolOptions implements CLIOptions<EthProtocolConfiguration> {
private static final String MAX_MESSAGE_SIZE_FLAG = "--Xeth-max-message-size"; private static final String MAX_MESSAGE_SIZE_FLAG = "--Xeth-max-message-size";
private static final String MAX_GET_HEADERS_FLAG = "--Xewp-max-get-headers"; private static final String MAX_GET_HEADERS_FLAG = "--Xewp-max-get-headers";
@ -114,10 +115,21 @@ public class EthProtocolOptions implements CLIOptions<EthProtocolConfiguration>
private EthProtocolOptions() {} private EthProtocolOptions() {}
/**
* Create eth protocol options.
*
* @return the eth protocol options
*/
public static EthProtocolOptions create() { public static EthProtocolOptions create() {
return new EthProtocolOptions(); return new EthProtocolOptions();
} }
/**
* From config eth protocol options.
*
* @param config the config
* @return the eth protocol options
*/
public static EthProtocolOptions fromConfig(final EthProtocolConfiguration config) { public static EthProtocolOptions fromConfig(final EthProtocolConfiguration config) {
final EthProtocolOptions options = create(); final EthProtocolOptions options = create();
options.maxMessageSize = PositiveNumber.fromInt(config.getMaxMessageSize()); options.maxMessageSize = PositiveNumber.fromInt(config.getMaxMessageSize());

@ -23,10 +23,17 @@ import java.util.List;
import picocli.CommandLine; import picocli.CommandLine;
/** The Evm CLI options. */
public class EvmOptions implements CLIOptions<EvmConfiguration> { public class EvmOptions implements CLIOptions<EvmConfiguration> {
/** The constant JUMPDEST_CACHE_WEIGHT. */
public static final String JUMPDEST_CACHE_WEIGHT = "--Xevm-jumpdest-cache-weight-kb"; public static final String JUMPDEST_CACHE_WEIGHT = "--Xevm-jumpdest-cache-weight-kb";
/**
* Create evm options.
*
* @return the evm options
*/
public static EvmOptions create() { public static EvmOptions create() {
return new EvmOptions(); return new EvmOptions();
} }

@ -21,13 +21,25 @@ import java.util.List;
import picocli.CommandLine; import picocli.CommandLine;
/** The Ipc CLI options. */
public class IpcOptions { public class IpcOptions {
private static final String DEFAULT_IPC_FILE = "besu.ipc"; private static final String DEFAULT_IPC_FILE = "besu.ipc";
/**
* Create ipc options.
*
* @return the ipc options
*/
public static IpcOptions create() { public static IpcOptions create() {
return new IpcOptions(); return new IpcOptions();
} }
/**
* Gets default path.
*
* @param dataDir the data dir
* @return the default path
*/
public static Path getDefaultPath(final Path dataDir) { public static Path getDefaultPath(final Path dataDir) {
return dataDir.resolve(DEFAULT_IPC_FILE); return dataDir.resolve(DEFAULT_IPC_FILE);
} }
@ -57,14 +69,29 @@ public class IpcOptions {
"Comma separated list of APIs to enable on JSON-RPC IPC service (default: ${DEFAULT-VALUE})") "Comma separated list of APIs to enable on JSON-RPC IPC service (default: ${DEFAULT-VALUE})")
private final List<String> rpcIpcApis = DEFAULT_RPC_APIS; private final List<String> rpcIpcApis = DEFAULT_RPC_APIS;
/**
* Whether IPC options are enabled.
*
* @return true for enabled, false otherwise.
*/
public Boolean isEnabled() { public Boolean isEnabled() {
return enabled; return enabled;
} }
/**
* Gets ipc path.
*
* @return the ipc path
*/
public Path getIpcPath() { public Path getIpcPath() {
return ipcPath; return ipcPath;
} }
/**
* Gets rpc ipc apis.
*
* @return the rpc ipc apis
*/
public List<String> getRpcIpcApis() { public List<String> getRpcIpcApis() {
return rpcIpcApis; return rpcIpcApis;
} }

@ -17,6 +17,7 @@ package org.hyperledger.besu.cli.options.unstable;
import net.consensys.quorum.mainnet.launcher.options.Options; import net.consensys.quorum.mainnet.launcher.options.Options;
import picocli.CommandLine; import picocli.CommandLine;
/** The Launcher CLI options. */
public class LauncherOptions implements Options { public class LauncherOptions implements Options {
private static final String LAUNCHER_OPTION_NAME = "--Xlauncher"; private static final String LAUNCHER_OPTION_NAME = "--Xlauncher";
@ -40,14 +41,29 @@ public class LauncherOptions implements Options {
arity = "0..1") arity = "0..1")
private Boolean isLauncherModeForced = Boolean.FALSE; private Boolean isLauncherModeForced = Boolean.FALSE;
/**
* Create launcher options.
*
* @return the launcher options
*/
public static LauncherOptions create() { public static LauncherOptions create() {
return new LauncherOptions(); return new LauncherOptions();
} }
/**
* Is launcher mode enabled.
*
* @return true if enabled, false otherwise.
*/
public boolean isLauncherMode() { public boolean isLauncherMode() {
return isLauncherMode; return isLauncherMode;
} }
/**
* Is launcher mode forced enabled.
*
* @return true if enabled, false otherwise.
*/
public boolean isLauncherModeForced() { public boolean isLauncherModeForced() {
return isLauncherModeForced; return isLauncherModeForced;
} }

@ -22,6 +22,7 @@ import java.util.List;
import picocli.CommandLine; import picocli.CommandLine;
/** The Metrics cli options. */
public class MetricsCLIOptions implements CLIOptions<MetricsConfiguration.Builder> { public class MetricsCLIOptions implements CLIOptions<MetricsConfiguration.Builder> {
private static final String TIMERS_ENABLED_FLAG = "--Xmetrics-timers-enabled"; private static final String TIMERS_ENABLED_FLAG = "--Xmetrics-timers-enabled";
private static final String IDLE_TIMEOUT_FLAG = "--Xmetrics-idle-timeout"; private static final String IDLE_TIMEOUT_FLAG = "--Xmetrics-idle-timeout";
@ -43,10 +44,21 @@ public class MetricsCLIOptions implements CLIOptions<MetricsConfiguration.Builde
private MetricsCLIOptions() {} private MetricsCLIOptions() {}
/**
* Create metrics cli options.
*
* @return the metrics cli options
*/
public static MetricsCLIOptions create() { public static MetricsCLIOptions create() {
return new MetricsCLIOptions(); return new MetricsCLIOptions();
} }
/**
* From configuration metrics cli options.
*
* @param config the config
* @return the metrics cli options
*/
public static MetricsCLIOptions fromConfiguration(final MetricsConfiguration config) { public static MetricsCLIOptions fromConfiguration(final MetricsConfiguration config) {
final MetricsCLIOptions metricsOptions = create(); final MetricsCLIOptions metricsOptions = create();
metricsOptions.timersEnabled = config.isTimersEnabled(); metricsOptions.timersEnabled = config.isTimersEnabled();

@ -22,6 +22,7 @@ import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE
import picocli.CommandLine; import picocli.CommandLine;
/** The Mining CLI options. */
public class MiningOptions { public class MiningOptions {
@CommandLine.Option( @CommandLine.Option(
@ -66,30 +67,65 @@ public class MiningOptions {
"Specifies the maximum time, in milliseconds, a PoS block creation jobs is allowed to run. Must be positive and ≤ 12000 (default: ${DEFAULT-VALUE} milliseconds)") "Specifies the maximum time, in milliseconds, a PoS block creation jobs is allowed to run. Must be positive and ≤ 12000 (default: ${DEFAULT-VALUE} milliseconds)")
private final Long posBlockCreationMaxTime = DEFAULT_POS_BLOCK_CREATION_MAX_TIME; private final Long posBlockCreationMaxTime = DEFAULT_POS_BLOCK_CREATION_MAX_TIME;
/**
* Create mining options.
*
* @return the mining options
*/
public static MiningOptions create() { public static MiningOptions create() {
return new MiningOptions(); return new MiningOptions();
} }
/**
* Gets remote sealers limit.
*
* @return the remote sealers limit
*/
public Integer getRemoteSealersLimit() { public Integer getRemoteSealersLimit() {
return remoteSealersLimit; return remoteSealersLimit;
} }
/**
* Gets remote sealers time to live.
*
* @return the remote sealers time to live
*/
public Long getRemoteSealersTimeToLive() { public Long getRemoteSealersTimeToLive() {
return remoteSealersTimeToLive; return remoteSealersTimeToLive;
} }
/**
* Gets stratum extra nonce.
*
* @return the stratum extra nonce
*/
public String getStratumExtranonce() { public String getStratumExtranonce() {
return stratumExtranonce; return stratumExtranonce;
} }
/**
* Gets pow job time to live.
*
* @return the pow job time to live
*/
public Long getPowJobTimeToLive() { public Long getPowJobTimeToLive() {
return powJobTimeToLive; return powJobTimeToLive;
} }
/**
* Gets max ommers depth.
*
* @return the max ommers depth
*/
public int getMaxOmmersDepth() { public int getMaxOmmersDepth() {
return maxOmmersDepth; return maxOmmersDepth;
} }
/**
* Gets pos block creation max time.
*
* @return the pos block creation max time
*/
public Long getPosBlockCreationMaxTime() { public Long getPosBlockCreationMaxTime() {
return posBlockCreationMaxTime; return posBlockCreationMaxTime;
} }

@ -18,6 +18,7 @@ import static org.hyperledger.besu.nat.kubernetes.KubernetesNatManager.DEFAULT_B
import picocli.CommandLine; import picocli.CommandLine;
/** The Nat Cli options. */
public class NatOptions { public class NatOptions {
@SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings. @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings.
@ -36,14 +37,29 @@ public class NatOptions {
arity = "1") arity = "1")
private final Boolean natMethodFallbackEnabled = true; private final Boolean natMethodFallbackEnabled = true;
/**
* Create nat options.
*
* @return the nat options
*/
public static NatOptions create() { public static NatOptions create() {
return new NatOptions(); return new NatOptions();
} }
/**
* Gets nat manager service name.
*
* @return the nat manager service name
*/
public String getNatManagerServiceName() { public String getNatManagerServiceName() {
return natManagerServiceName; return natManagerServiceName;
} }
/**
* Whether nat method fallback is enabled.
*
* @return true if enabled, false otherwise.
*/
public Boolean getNatMethodFallbackEnabled() { public Boolean getNatMethodFallbackEnabled() {
return natMethodFallbackEnabled; return natMethodFallbackEnabled;
} }

@ -16,6 +16,7 @@ package org.hyperledger.besu.cli.options.unstable;
import picocli.CommandLine; import picocli.CommandLine;
/** The Native library CLI options. */
public class NativeLibraryOptions { public class NativeLibraryOptions {
@CommandLine.Option( @CommandLine.Option(
@ -54,22 +55,47 @@ public class NativeLibraryOptions {
arity = "1") arity = "1")
private final Boolean nativeModExp = Boolean.TRUE; private final Boolean nativeModExp = Boolean.TRUE;
/**
* Create native library options.
*
* @return the native library options
*/
public static NativeLibraryOptions create() { public static NativeLibraryOptions create() {
return new NativeLibraryOptions(); return new NativeLibraryOptions();
} }
/**
* Whether native secp is enabled.
*
* @return true if enabled, false otherwise.
*/
public Boolean getNativeSecp() { public Boolean getNativeSecp() {
return nativeSecp; return nativeSecp;
} }
/**
* Whether native Altbn128 is enabled.
*
* @return true if enabled, false otherwise.
*/
public Boolean getNativeAltbn128() { public Boolean getNativeAltbn128() {
return nativeAltbn128; return nativeAltbn128;
} }
/**
* Whether native blake2bf is enabled.
*
* @return true if enabled, false otherwise.
*/
public Boolean getNativeBlake2bf() { public Boolean getNativeBlake2bf() {
return nativeBlake2bf; return nativeBlake2bf;
} }
/**
* Whether native mod exp is enabled.
*
* @return true if enabled, false otherwise.
*/
public Boolean getNativeModExp() { public Boolean getNativeModExp() {
return nativeModExp; return nativeModExp;
} }

@ -25,6 +25,7 @@ import java.util.Optional;
import picocli.CommandLine; import picocli.CommandLine;
/** The Networking Cli options. */
public class NetworkingOptions implements CLIOptions<NetworkingConfiguration> { public class NetworkingOptions implements CLIOptions<NetworkingConfiguration> {
private final String INITIATE_CONNECTIONS_FREQUENCY_FLAG = private final String INITIATE_CONNECTIONS_FREQUENCY_FLAG =
"--Xp2p-initiate-connections-frequency"; "--Xp2p-initiate-connections-frequency";
@ -33,6 +34,7 @@ public class NetworkingOptions implements CLIOptions<NetworkingConfiguration> {
private final String DNS_DISCOVERY_SERVER_OVERRIDE_FLAG = "--Xp2p-dns-discovery-server"; private final String DNS_DISCOVERY_SERVER_OVERRIDE_FLAG = "--Xp2p-dns-discovery-server";
private final String DISCOVERY_PROTOCOL_V5_ENABLED = "--Xv5-discovery-enabled"; private final String DISCOVERY_PROTOCOL_V5_ENABLED = "--Xv5-discovery-enabled";
private final String P2P_PEER_LOWER_BOUND_FLAG = "--Xp2p-peer-lower-bound"; private final String P2P_PEER_LOWER_BOUND_FLAG = "--Xp2p-peer-lower-bound";
/** The constant FILTER_ON_ENR_FORK_ID. */
public static final String FILTER_ON_ENR_FORK_ID = "--Xfilter-on-enr-fork-id"; public static final String FILTER_ON_ENR_FORK_ID = "--Xfilter-on-enr-fork-id";
@CommandLine.Option( @CommandLine.Option(
@ -85,10 +87,21 @@ public class NetworkingOptions implements CLIOptions<NetworkingConfiguration> {
private NetworkingOptions() {} private NetworkingOptions() {}
/**
* Create networking options.
*
* @return the networking options
*/
public static NetworkingOptions create() { public static NetworkingOptions create() {
return new NetworkingOptions(); return new NetworkingOptions();
} }
/**
* Create networking options from Networking Configuration.
*
* @param networkingConfig the networking config
* @return the networking options
*/
public static NetworkingOptions fromConfig(final NetworkingConfiguration networkingConfig) { public static NetworkingOptions fromConfig(final NetworkingConfiguration networkingConfig) {
final NetworkingOptions cliOptions = new NetworkingOptions(); final NetworkingOptions cliOptions = new NetworkingOptions();
cliOptions.checkMaintainedConnectionsFrequencySec = cliOptions.checkMaintainedConnectionsFrequencySec =

@ -29,14 +29,17 @@ import picocli.CommandLine;
import picocli.CommandLine.Option; import picocli.CommandLine.Option;
import picocli.CommandLine.ParameterException; import picocli.CommandLine.ParameterException;
/** The Pki block creation Cli options. */
public class PkiBlockCreationOptions { public class PkiBlockCreationOptions {
/** The pki block creation enabled. */
@Option( @Option(
names = {"--Xpki-block-creation-enabled"}, names = {"--Xpki-block-creation-enabled"},
hidden = true, hidden = true,
description = "Enable PKI integration (default: ${DEFAULT-VALUE})") description = "Enable PKI integration (default: ${DEFAULT-VALUE})")
Boolean enabled = false; Boolean enabled = false;
/** The Key store type. */
@Option( @Option(
names = {"--Xpki-block-creation-keystore-type"}, names = {"--Xpki-block-creation-keystore-type"},
hidden = true, hidden = true,
@ -45,6 +48,7 @@ public class PkiBlockCreationOptions {
@SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"})
String keyStoreType = PkiKeyStoreConfiguration.DEFAULT_KEYSTORE_TYPE; String keyStoreType = PkiKeyStoreConfiguration.DEFAULT_KEYSTORE_TYPE;
/** The Key store file. */
@Option( @Option(
names = {"--Xpki-block-creation-keystore-file"}, names = {"--Xpki-block-creation-keystore-file"},
hidden = true, hidden = true,
@ -52,6 +56,7 @@ public class PkiBlockCreationOptions {
description = "Keystore containing key/certificate for PKI Block Creation.") description = "Keystore containing key/certificate for PKI Block Creation.")
Path keyStoreFile = null; Path keyStoreFile = null;
/** The Key store password file. */
@Option( @Option(
names = {"--Xpki-block-creation-keystore-password-file"}, names = {"--Xpki-block-creation-keystore-password-file"},
hidden = true, hidden = true,
@ -60,6 +65,7 @@ public class PkiBlockCreationOptions {
"File containing password to unlock keystore for PKI Integration. Required if PKI Block Creation is enabled.") "File containing password to unlock keystore for PKI Integration. Required if PKI Block Creation is enabled.")
Path keyStorePasswordFile = null; Path keyStorePasswordFile = null;
/** The Certificate alias. */
@Option( @Option(
names = {"--Xpki-block-creation-keystore-certificate-alias"}, names = {"--Xpki-block-creation-keystore-certificate-alias"},
hidden = true, hidden = true,
@ -69,6 +75,7 @@ public class PkiBlockCreationOptions {
@SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"})
String certificateAlias = PkiKeyStoreConfiguration.DEFAULT_CERTIFICATE_ALIAS; String certificateAlias = PkiKeyStoreConfiguration.DEFAULT_CERTIFICATE_ALIAS;
/** The Trust store type. */
@Option( @Option(
names = {"--Xpki-block-creation-truststore-type"}, names = {"--Xpki-block-creation-truststore-type"},
hidden = true, hidden = true,
@ -77,6 +84,7 @@ public class PkiBlockCreationOptions {
@SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) @SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"})
String trustStoreType = PkiKeyStoreConfiguration.DEFAULT_KEYSTORE_TYPE; String trustStoreType = PkiKeyStoreConfiguration.DEFAULT_KEYSTORE_TYPE;
/** The Trust store file. */
@Option( @Option(
names = {"--Xpki-block-creation-truststore-file"}, names = {"--Xpki-block-creation-truststore-file"},
hidden = true, hidden = true,
@ -84,6 +92,7 @@ public class PkiBlockCreationOptions {
description = "Truststore containing trusted certificates for PKI Block Creation.") description = "Truststore containing trusted certificates for PKI Block Creation.")
Path trustStoreFile = null; Path trustStoreFile = null;
/** The Trust store password file. */
@Option( @Option(
names = {"--Xpki-block-creation-truststore-password-file"}, names = {"--Xpki-block-creation-truststore-password-file"},
hidden = true, hidden = true,
@ -91,6 +100,7 @@ public class PkiBlockCreationOptions {
description = "File containing password to unlock truststore for PKI Block Creation.") description = "File containing password to unlock truststore for PKI Block Creation.")
Path trustStorePasswordFile = null; Path trustStorePasswordFile = null;
/** The Crl file. */
@Option( @Option(
names = {"--Xpki-block-creation-crl-file"}, names = {"--Xpki-block-creation-crl-file"},
hidden = true, hidden = true,
@ -98,6 +108,12 @@ public class PkiBlockCreationOptions {
description = "File with all CRLs for PKI Block Creation.") description = "File with all CRLs for PKI Block Creation.")
Path crlFile = null; Path crlFile = null;
/**
* As domain config optional.
*
* @param commandLine the command line
* @return the optional
*/
public Optional<PkiKeyStoreConfiguration> asDomainConfig(final CommandLine commandLine) { public Optional<PkiKeyStoreConfiguration> asDomainConfig(final CommandLine commandLine) {
if (!enabled) { if (!enabled) {
return Optional.empty(); return Optional.empty();
@ -127,6 +143,12 @@ public class PkiBlockCreationOptions {
.build()); .build());
} }
/**
* Check pki block creation options dependencies.
*
* @param logger the logger
* @param commandLine the command line
*/
public void checkPkiBlockCreationOptionsDependencies( public void checkPkiBlockCreationOptionsDependencies(
final Logger logger, final CommandLine commandLine) { final Logger logger, final CommandLine commandLine) {
CommandLineUtils.checkOptionDependencies( CommandLineUtils.checkOptionDependencies(

@ -16,8 +16,14 @@ package org.hyperledger.besu.cli.options.unstable;
import static picocli.CommandLine.Option; import static picocli.CommandLine.Option;
/** The Privacy plugin Cli options. */
public class PrivacyPluginOptions { public class PrivacyPluginOptions {
/**
* Create privacy plugin options.
*
* @return the privacy plugin options
*/
public static PrivacyPluginOptions create() { public static PrivacyPluginOptions create() {
return new PrivacyPluginOptions(); return new PrivacyPluginOptions();
} }
@ -29,6 +35,11 @@ public class PrivacyPluginOptions {
hidden = true) hidden = true)
private final Boolean isPrivacyPluginEnabled = false; private final Boolean isPrivacyPluginEnabled = false;
/**
* Is privacy plugin enabled boolean.
*
* @return the boolean
*/
public boolean isPrivacyPluginEnabled() { public boolean isPrivacyPluginEnabled() {
return isPrivacyPluginEnabled; return isPrivacyPluginEnabled;
} }

@ -18,6 +18,7 @@ import org.hyperledger.besu.ethereum.api.handlers.TimeoutOptions;
import picocli.CommandLine; import picocli.CommandLine;
/** The Rpc Cli options. */
public class RPCOptions { public class RPCOptions {
@CommandLine.Option( @CommandLine.Option(
@ -34,14 +35,29 @@ public class RPCOptions {
arity = "1") arity = "1")
private final Long wsTimeoutSec = TimeoutOptions.defaultOptions().getTimeoutSeconds(); private final Long wsTimeoutSec = TimeoutOptions.defaultOptions().getTimeoutSeconds();
/**
* Create rpc options.
*
* @return the rpc options
*/
public static RPCOptions create() { public static RPCOptions create() {
return new RPCOptions(); return new RPCOptions();
} }
/**
* Gets http timeout sec.
*
* @return the http timeout sec
*/
public Long getHttpTimeoutSec() { public Long getHttpTimeoutSec() {
return httpTimeoutSec; return httpTimeoutSec;
} }
/**
* Gets WebSocket timeout sec.
*
* @return the WebSocket timeout sec
*/
public Long getWsTimeoutSec() { public Long getWsTimeoutSec() {
return wsTimeoutSec; return wsTimeoutSec;
} }

@ -27,6 +27,7 @@ import com.google.common.collect.Range;
import org.apache.tuweni.units.bigints.UInt256; import org.apache.tuweni.units.bigints.UInt256;
import picocli.CommandLine; import picocli.CommandLine;
/** The Synchronizer Cli options. */
public class SynchronizerOptions implements CLIOptions<SynchronizerConfiguration.Builder> { public class SynchronizerOptions implements CLIOptions<SynchronizerConfiguration.Builder> {
private static final String BLOCK_PROPAGATION_RANGE_FLAG = private static final String BLOCK_PROPAGATION_RANGE_FLAG =
"--Xsynchronizer-block-propagation-range"; "--Xsynchronizer-block-propagation-range";
@ -74,6 +75,11 @@ public class SynchronizerOptions implements CLIOptions<SynchronizerConfiguration
private static final String CHECKPOINT_POST_MERGE_FLAG = "--Xcheckpoint-post-merge-enabled"; private static final String CHECKPOINT_POST_MERGE_FLAG = "--Xcheckpoint-post-merge-enabled";
/**
* Parse block propagation range.
*
* @param arg the range such as -10..30
*/
@CommandLine.Option( @CommandLine.Option(
names = BLOCK_PROPAGATION_RANGE_FLAG, names = BLOCK_PROPAGATION_RANGE_FLAG,
hidden = true, hidden = true,
@ -283,10 +289,21 @@ public class SynchronizerOptions implements CLIOptions<SynchronizerConfiguration
private SynchronizerOptions() {} private SynchronizerOptions() {}
/**
* Create synchronizer options.
*
* @return the synchronizer options
*/
public static SynchronizerOptions create() { public static SynchronizerOptions create() {
return new SynchronizerOptions(); return new SynchronizerOptions();
} }
/**
* Create synchronizer options from Synchronizer Configuration.
*
* @param config the Synchronizer Configuration
* @return the synchronizer options
*/
public static SynchronizerOptions fromConfig(final SynchronizerConfiguration config) { public static SynchronizerOptions fromConfig(final SynchronizerConfiguration config) {
final SynchronizerOptions options = new SynchronizerOptions(); final SynchronizerOptions options = new SynchronizerOptions();
options.blockPropagationRange = config.getBlockPropagationRange(); options.blockPropagationRange = config.getBlockPropagationRange();

@ -31,6 +31,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import picocli.CommandLine; import picocli.CommandLine;
/** The Transaction pool Cli options. */
public class TransactionPoolOptions public class TransactionPoolOptions
implements CLIOptions<ImmutableTransactionPoolConfiguration.Builder> { implements CLIOptions<ImmutableTransactionPoolConfiguration.Builder> {
private static final Logger LOG = LoggerFactory.getLogger(Besu.class); private static final Logger LOG = LoggerFactory.getLogger(Besu.class);
@ -95,10 +96,21 @@ public class TransactionPoolOptions
private TransactionPoolOptions() {} private TransactionPoolOptions() {}
/**
* Create transaction pool options.
*
* @return the transaction pool options
*/
public static TransactionPoolOptions create() { public static TransactionPoolOptions create() {
return new TransactionPoolOptions(); return new TransactionPoolOptions();
} }
/**
* Create Transaction Pool Options from Transaction Pool Configuration.
*
* @param config the Transaction Pool Configuration
* @return the transaction pool options
*/
public static TransactionPoolOptions fromConfig(final TransactionPoolConfiguration config) { public static TransactionPoolOptions fromConfig(final TransactionPoolConfiguration config) {
final TransactionPoolOptions options = TransactionPoolOptions.create(); final TransactionPoolOptions options = TransactionPoolOptions.create();
options.txMessageKeepAliveSeconds = config.getTxMessageKeepAliveSeconds(); options.txMessageKeepAliveSeconds = config.getTxMessageKeepAliveSeconds();

@ -20,9 +20,14 @@ import org.hyperledger.besu.controller.BesuController;
/** /**
* All PreSynchronizationTask instances execute after the {@link BesuController} instance in {@link * All PreSynchronizationTask instances execute after the {@link BesuController} instance in {@link
* BesuCommand} is ready and before {@link Runner#startEthereumMainLoop()} is called * BesuCommand}* is ready and before {@link Runner#startEthereumMainLoop()} is called
*/ */
public interface PreSynchronizationTask { public interface PreSynchronizationTask {
/**
* Run.
*
* @param besuController the besu controller
*/
void run(final BesuController besuController); void run(final BesuController besuController);
} }

@ -19,14 +19,25 @@ import org.hyperledger.besu.controller.BesuController;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
/** The Pre synchronization task runner. */
public class PreSynchronizationTaskRunner { public class PreSynchronizationTaskRunner {
private final List<PreSynchronizationTask> tasks = new ArrayList<>(); private final List<PreSynchronizationTask> tasks = new ArrayList<>();
/**
* Add task.
*
* @param task the task
*/
public void addTask(final PreSynchronizationTask task) { public void addTask(final PreSynchronizationTask task) {
tasks.add(task); tasks.add(task);
} }
/**
* Run tasks.
*
* @param besuController the besu controller
*/
public void runTasks(final BesuController besuController) { public void runTasks(final BesuController besuController) {
tasks.forEach(t -> t.run(besuController)); tasks.forEach(t -> t.run(besuController));
} }

@ -19,11 +19,18 @@ import org.hyperledger.besu.ethereum.core.PrivacyParameters;
import org.hyperledger.besu.ethereum.privacy.storage.migration.PrivateStorageMigrationService; import org.hyperledger.besu.ethereum.privacy.storage.migration.PrivateStorageMigrationService;
import org.hyperledger.besu.util.PrivateStorageMigrationBuilder; import org.hyperledger.besu.util.PrivateStorageMigrationBuilder;
/** The Private database migration pre sync task. */
public class PrivateDatabaseMigrationPreSyncTask implements PreSynchronizationTask { public class PrivateDatabaseMigrationPreSyncTask implements PreSynchronizationTask {
private final PrivacyParameters privacyParameters; private final PrivacyParameters privacyParameters;
private final boolean migratePrivateDatabaseFlag; private final boolean migratePrivateDatabaseFlag;
/**
* Instantiates a new Private database migration pre sync task.
*
* @param privacyParameters the privacy parameters
* @param migratePrivateDatabaseFlag the migrate private database flag
*/
public PrivateDatabaseMigrationPreSyncTask( public PrivateDatabaseMigrationPreSyncTask(
final PrivacyParameters privacyParameters, final boolean migratePrivateDatabaseFlag) { final PrivacyParameters privacyParameters, final boolean migratePrivateDatabaseFlag) {
this.privacyParameters = privacyParameters; this.privacyParameters = privacyParameters;

@ -30,6 +30,7 @@ import picocli.CommandLine.Option;
import picocli.CommandLine.ParentCommand; import picocli.CommandLine.ParentCommand;
import picocli.CommandLine.Spec; import picocli.CommandLine.Spec;
/** The Password sub command. */
@Command( @Command(
name = COMMAND_NAME, name = COMMAND_NAME,
description = "This command provides password related actions.", description = "This command provides password related actions.",
@ -38,6 +39,7 @@ import picocli.CommandLine.Spec;
subcommands = {HashSubCommand.class}) subcommands = {HashSubCommand.class})
public class PasswordSubCommand implements Runnable { public class PasswordSubCommand implements Runnable {
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "password"; public static final String COMMAND_NAME = "password";
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -48,8 +50,13 @@ public class PasswordSubCommand implements Runnable {
@Spec @Spec
private CommandSpec spec; private CommandSpec spec;
final PrintWriter out; private final PrintWriter out;
/**
* Instantiates a new Password sub command.
*
* @param out The PrintWriter where the usage will be reported.
*/
public PasswordSubCommand(final PrintWriter out) { public PasswordSubCommand(final PrintWriter out) {
this.out = out; this.out = out;
} }
@ -59,6 +66,7 @@ public class PasswordSubCommand implements Runnable {
spec.commandLine().usage(out); spec.commandLine().usage(out);
} }
/** The Hash sub command for password. */
@Command( @Command(
name = "hash", name = "hash",
description = "This command generates the hash of a given password.", description = "This command generates the hash of a given password.",

@ -57,6 +57,7 @@ import picocli.CommandLine.Spec;
public class PublicKeySubCommand implements Runnable { public class PublicKeySubCommand implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(PublicKeySubCommand.class); private static final Logger LOG = LoggerFactory.getLogger(PublicKeySubCommand.class);
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "public-key"; public static final String COMMAND_NAME = "public-key";
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -69,6 +70,11 @@ public class PublicKeySubCommand implements Runnable {
private final PrintWriter out; private final PrintWriter out;
/**
* Instantiates a new Public key sub command.
*
* @param out the out
*/
public PublicKeySubCommand(final PrintWriter out) { public PublicKeySubCommand(final PrintWriter out) {
this.out = out; this.out = out;
} }
@ -140,12 +146,14 @@ public class PublicKeySubCommand implements Runnable {
private static class KeyPairSubcommand { private static class KeyPairSubcommand {
/** The Parent command. */
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ParentCommand @ParentCommand
protected PublicKeySubCommand parentCommand; // Picocli injects reference to parent command protected PublicKeySubCommand parentCommand; // Picocli injects reference to parent command
@Mixin private final NodePrivateKeyFileOption nodePrivateKeyFileOption = null; @Mixin private final NodePrivateKeyFileOption nodePrivateKeyFileOption = null;
/** The Ec curve. */
@Option( @Option(
names = "--ec-curve", names = "--ec-curve",
paramLabel = "<NAME>", paramLabel = "<NAME>",
@ -159,6 +167,12 @@ public class PublicKeySubCommand implements Runnable {
@Spec private final CommandSpec spec = null; @Spec private final CommandSpec spec = null;
/**
* Run.
*
* @param exportFile the export file
* @param outputFunction the output function
*/
protected final void run( protected final void run(
final File exportFile, final Function<KeyPair, String> outputFunction) { final File exportFile, final Function<KeyPair, String> outputFunction) {
checkNotNull(parentCommand); checkNotNull(parentCommand);
@ -192,6 +206,12 @@ public class PublicKeySubCommand implements Runnable {
} }
} }
/**
* Configure ec curve.
*
* @param ecCurve the ec curve
* @param commandLine the command line
*/
protected static void configureEcCurve(final String ecCurve, final CommandLine commandLine) { protected static void configureEcCurve(final String ecCurve, final CommandLine commandLine) {
if (ecCurve != null) { if (ecCurve != null) {
try { try {

@ -36,6 +36,7 @@ import picocli.CommandLine.Command;
import picocli.CommandLine.Mixin; import picocli.CommandLine.Mixin;
import picocli.CommandLine.Option; import picocli.CommandLine.Option;
/** Subcommand to run a Retesteth compatible server for reference tests. */
@Command( @Command(
name = COMMAND_NAME, name = COMMAND_NAME,
description = "Run a Retesteth compatible server for reference tests.", description = "Run a Retesteth compatible server for reference tests.",
@ -46,6 +47,7 @@ public class RetestethSubCommand implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(RetestethSubCommand.class); private static final Logger LOG = LoggerFactory.getLogger(RetestethSubCommand.class);
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "retesteth"; public static final String COMMAND_NAME = "retesteth";
/** /**

@ -30,6 +30,7 @@ import picocli.CommandLine.Command;
import picocli.CommandLine.Option; import picocli.CommandLine.Option;
import picocli.CommandLine.ParentCommand; import picocli.CommandLine.ParentCommand;
/** The Besu configuration Validate sub command. */
@Command( @Command(
name = COMMAND_NAME, name = COMMAND_NAME,
description = "This command provides basic Besu config validation (syntax only).", description = "This command provides basic Besu config validation (syntax only).",
@ -37,6 +38,7 @@ import picocli.CommandLine.ParentCommand;
versionProvider = VersionProvider.class) versionProvider = VersionProvider.class)
public class ValidateConfigSubCommand implements Runnable { public class ValidateConfigSubCommand implements Runnable {
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "validate-config"; public static final String COMMAND_NAME = "validate-config";
@Option( @Option(
@ -49,9 +51,15 @@ public class ValidateConfigSubCommand implements Runnable {
@ParentCommand @ParentCommand
private BesuCommand parentCommand; private BesuCommand parentCommand;
final PrintWriter out; private final PrintWriter out;
final CommandLine commandLine; private final CommandLine commandLine;
/**
* Instantiates a new Validate config sub command.
*
* @param commandLine the command line
* @param out the PrintWriter where validation results will be reported.
*/
public ValidateConfigSubCommand(final CommandLine commandLine, final PrintWriter out) { public ValidateConfigSubCommand(final CommandLine commandLine, final PrintWriter out) {
this.out = out; this.out = out;
this.commandLine = commandLine; this.commandLine = commandLine;

@ -14,6 +14,8 @@
*/ */
package org.hyperledger.besu.cli.subcommands.blocks; package org.hyperledger.besu.cli.subcommands.blocks;
/** The enum Block export format. */
public enum BlockExportFormat { public enum BlockExportFormat {
/** Rlp block export format. */
RLP RLP
} }

@ -14,7 +14,10 @@
*/ */
package org.hyperledger.besu.cli.subcommands.blocks; package org.hyperledger.besu.cli.subcommands.blocks;
/** The enum Block import format. */
public enum BlockImportFormat { public enum BlockImportFormat {
/** RLP block import format. */
RLP, RLP,
/** Json block import format. */
JSON JSON
} }

@ -80,6 +80,7 @@ public class BlocksSubCommand implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(BlocksSubCommand.class); private static final Logger LOG = LoggerFactory.getLogger(BlocksSubCommand.class);
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "blocks"; public static final String COMMAND_NAME = "blocks";
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ -96,6 +97,14 @@ public class BlocksSubCommand implements Runnable {
private final PrintWriter out; private final PrintWriter out;
/**
* Instantiates a new Blocks sub command.
*
* @param rlpBlockImporter the RLP block importer
* @param jsonBlockImporterFactory the Json block importer factory
* @param rlpBlockExporterFactory the RLP block exporter factory
* @param out Instance of PrintWriter where command usage will be written.
*/
public BlocksSubCommand( public BlocksSubCommand(
final Supplier<RlpBlockImporter> rlpBlockImporter, final Supplier<RlpBlockImporter> rlpBlockImporter,
final Function<BesuController, JsonBlockImporter> jsonBlockImporterFactory, final Function<BesuController, JsonBlockImporter> jsonBlockImporterFactory,

@ -39,6 +39,7 @@ import picocli.CommandLine.Command;
import picocli.CommandLine.Option; import picocli.CommandLine.Option;
import picocli.CommandLine.ParentCommand; import picocli.CommandLine.ParentCommand;
/** Subcommand that performs back up of state and accounts at a specified block */
@Command( @Command(
name = "x-backup-state", name = "x-backup-state",
description = "Backs up the state and accounts at a specified block.", description = "Backs up the state and accounts at a specified block.",

@ -34,6 +34,7 @@ import picocli.CommandLine.Command;
import picocli.CommandLine.Option; import picocli.CommandLine.Option;
import picocli.CommandLine.ParentCommand; import picocli.CommandLine.ParentCommand;
/** The generate-log-bloom-cache CLI command. */
@Command( @Command(
name = "generate-log-bloom-cache", name = "generate-log-bloom-cache",
description = "Generate cached values of block log bloom filters.", description = "Generate cached values of block log bloom filters.",

@ -40,10 +40,13 @@ import picocli.CommandLine.Spec;
}) })
public class OperatorSubCommand implements Runnable { public class OperatorSubCommand implements Runnable {
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "operator"; public static final String COMMAND_NAME = "operator";
/** The constant GENERATE_BLOCKCHAIN_CONFIG_SUBCOMMAND_NAME. */
public static final String GENERATE_BLOCKCHAIN_CONFIG_SUBCOMMAND_NAME = public static final String GENERATE_BLOCKCHAIN_CONFIG_SUBCOMMAND_NAME =
"generate-blockchain-config"; "generate-blockchain-config";
/** The Parent command. */
@SuppressWarnings("unused") @SuppressWarnings("unused")
@ParentCommand @ParentCommand
BesuCommand parentCommand; // Picocli injects reference to parent command BesuCommand parentCommand; // Picocli injects reference to parent command
@ -54,6 +57,11 @@ public class OperatorSubCommand implements Runnable {
private final PrintWriter out; private final PrintWriter out;
/**
* Instantiates a new Operator sub command.
*
* @param out the out
*/
public OperatorSubCommand(final PrintWriter out) { public OperatorSubCommand(final PrintWriter out) {
this.out = out; this.out = out;
} }

@ -56,6 +56,7 @@ import picocli.CommandLine.Command;
import picocli.CommandLine.Option; import picocli.CommandLine.Option;
import picocli.CommandLine.ParentCommand; import picocli.CommandLine.ParentCommand;
/** The Restore state subcommand. */
@Command( @Command(
name = "x-restore-state", name = "x-restore-state",
description = "Restores the chain from a previously generated backup-state.", description = "Restores the chain from a previously generated backup-state.",

@ -42,6 +42,7 @@ import picocli.CommandLine.ParameterException;
import picocli.CommandLine.ParentCommand; import picocli.CommandLine.ParentCommand;
import picocli.CommandLine.Spec; import picocli.CommandLine.Spec;
/** The RLP sub command. */
@Command( @Command(
name = RLPSubCommand.COMMAND_NAME, name = RLPSubCommand.COMMAND_NAME,
description = "This command provides RLP data related actions.", description = "This command provides RLP data related actions.",
@ -50,6 +51,7 @@ import picocli.CommandLine.Spec;
subcommands = {EncodeSubCommand.class}) subcommands = {EncodeSubCommand.class})
public class RLPSubCommand implements Runnable { public class RLPSubCommand implements Runnable {
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "rlp"; public static final String COMMAND_NAME = "rlp";
private final PrintWriter out; private final PrintWriter out;
@ -63,6 +65,12 @@ public class RLPSubCommand implements Runnable {
@Spec @Spec
private CommandSpec spec; private CommandSpec spec;
/**
* Instantiates a new Rlp sub command.
*
* @param out the PrintWriter where the output of subcommand will be reported
* @param in the InputStream which will be used to read the input for this subcommand.
*/
public RLPSubCommand(final PrintWriter out, final InputStream in) { public RLPSubCommand(final PrintWriter out, final InputStream in) {
this.out = out; this.out = out;
this.in = in; this.in = in;

@ -16,8 +16,10 @@ package org.hyperledger.besu.cli.subcommands.rlp;
/** Type of the RLP data to encode/decode */ /** Type of the RLP data to encode/decode */
public enum RLPType { public enum RLPType {
/** The Ibft extra data. */
// Enum is used to enable the listing of the possible values in PicoCLI. // Enum is used to enable the listing of the possible values in PicoCLI.
IBFT_EXTRA_DATA(new IbftExtraDataCLIAdapter()), IBFT_EXTRA_DATA(new IbftExtraDataCLIAdapter()),
/** The Qbft extra data. */
QBFT_EXTRA_DATA(new QbftExtraDataCLIAdapter()); QBFT_EXTRA_DATA(new QbftExtraDataCLIAdapter());
private final JSONToRLP adapter; private final JSONToRLP adapter;
@ -27,6 +29,11 @@ public enum RLPType {
this.adapter = adapter; this.adapter = adapter;
} }
/**
* Gets adapter.
*
* @return the adapter
*/
public JSONToRLP getAdapter() { public JSONToRLP getAdapter() {
return adapter; return adapter;
} }

@ -26,6 +26,11 @@ public class BesuCommandCustomFactory implements CommandLine.IFactory {
private final PluginVersionsProvider pluginVersionsProvider; private final PluginVersionsProvider pluginVersionsProvider;
private final CommandLine.IFactory defaultFactory = CommandLine.defaultFactory(); private final CommandLine.IFactory defaultFactory = CommandLine.defaultFactory();
/**
* BesuCommandCustomFactory Constructor
*
* @param pluginVersionsProvider instance of PluginVersionsProvider
*/
public BesuCommandCustomFactory(final PluginVersionsProvider pluginVersionsProvider) { public BesuCommandCustomFactory(final PluginVersionsProvider pluginVersionsProvider) {
this.pluginVersionsProvider = pluginVersionsProvider; this.pluginVersionsProvider = pluginVersionsProvider;
} }

@ -21,10 +21,19 @@ import java.util.List;
import picocli.CommandLine.IDefaultValueProvider; import picocli.CommandLine.IDefaultValueProvider;
import picocli.CommandLine.Model.ArgSpec; import picocli.CommandLine.Model.ArgSpec;
/**
* The custom default value provider for Besu CLI options which uses multiple default value
* providers such as environment variables or TOML file.
*/
public class CascadingDefaultProvider implements IDefaultValueProvider { public class CascadingDefaultProvider implements IDefaultValueProvider {
private final List<IDefaultValueProvider> defaultValueProviders; private final List<IDefaultValueProvider> defaultValueProviders;
/**
* Instantiates a new Cascading default provider.
*
* @param defaultValueProviders List of default value providers
*/
public CascadingDefaultProvider(final IDefaultValueProvider... defaultValueProviders) { public CascadingDefaultProvider(final IDefaultValueProvider... defaultValueProviders) {
this.defaultValueProviders = asList(defaultValueProviders); this.defaultValueProviders = asList(defaultValueProviders);
} }

@ -24,12 +24,17 @@ import com.google.common.base.Strings;
import org.slf4j.Logger; import org.slf4j.Logger;
import picocli.CommandLine; import picocli.CommandLine;
/** The Command line utils. */
public class CommandLineUtils { public class CommandLineUtils {
/** The constant DEPENDENCY_WARNING_MSG. */
public static final String DEPENDENCY_WARNING_MSG = public static final String DEPENDENCY_WARNING_MSG =
"{} has been ignored because {} was not defined on the command line."; "{} has been ignored because {} was not defined on the command line.";
/** The constant MULTI_DEPENDENCY_WARNING_MSG. */
public static final String MULTI_DEPENDENCY_WARNING_MSG = public static final String MULTI_DEPENDENCY_WARNING_MSG =
"{} ignored because none of {} was defined."; "{} ignored because none of {} was defined.";
/** The constant DEPRECATION_WARNING_MSG. */
public static final String DEPRECATION_WARNING_MSG = "{} has been deprecated, use {} instead."; public static final String DEPRECATION_WARNING_MSG = "{} has been deprecated, use {} instead.";
/** The constant DEPRECATED_AND_USELESS_WARNING_MSG. */
public static final String DEPRECATED_AND_USELESS_WARNING_MSG = public static final String DEPRECATED_AND_USELESS_WARNING_MSG =
"{} has been deprecated and is now useless, remove it."; "{} has been deprecated and is now useless, remove it.";
@ -97,6 +102,14 @@ public class CommandLineUtils {
} }
} }
/**
* Fail if option doesnt meet requirement.
*
* @param commandLine the command line
* @param errorMessage the error message
* @param requirement the requirement
* @param dependentOptionsNames the dependent options names
*/
public static void failIfOptionDoesntMeetRequirement( public static void failIfOptionDoesntMeetRequirement(
final CommandLine commandLine, final CommandLine commandLine,
final String errorMessage, final String errorMessage,

@ -29,11 +29,19 @@ import picocli.CommandLine.Model.OptionSpec;
import picocli.CommandLine.ParameterException; import picocli.CommandLine.ParameterException;
import picocli.CommandLine.ParseResult; import picocli.CommandLine.ParseResult;
/** Custom Config option search and run handler. */
public class ConfigOptionSearchAndRunHandler extends CommandLine.RunLast { public class ConfigOptionSearchAndRunHandler extends CommandLine.RunLast {
private final IExecutionStrategy resultHandler; private final IExecutionStrategy resultHandler;
private final IParameterExceptionHandler parameterExceptionHandler; private final IParameterExceptionHandler parameterExceptionHandler;
private final Map<String, String> environment; private final Map<String, String> environment;
/**
* Instantiates a new Config option search and run handler.
*
* @param resultHandler the result handler
* @param parameterExceptionHandler the parameter exception handler
* @param environment the environment variables map
*/
public ConfigOptionSearchAndRunHandler( public ConfigOptionSearchAndRunHandler(
final IExecutionStrategy resultHandler, final IExecutionStrategy resultHandler,
final IParameterExceptionHandler parameterExceptionHandler, final IParameterExceptionHandler parameterExceptionHandler,
@ -98,6 +106,13 @@ public class ConfigOptionSearchAndRunHandler extends CommandLine.RunLast {
return Optional.empty(); return Optional.empty();
} }
/**
* Create default value provider default value provider.
*
* @param commandLine the command line
* @param configFile the config file
* @return the default value provider
*/
@VisibleForTesting @VisibleForTesting
IDefaultValueProvider createDefaultValueProvider( IDefaultValueProvider createDefaultValueProvider(
final CommandLine commandLine, final Optional<File> configFile) { final CommandLine commandLine, final Optional<File> configFile) {

@ -24,12 +24,18 @@ import picocli.CommandLine.IDefaultValueProvider;
import picocli.CommandLine.Model.ArgSpec; import picocli.CommandLine.Model.ArgSpec;
import picocli.CommandLine.Model.OptionSpec; import picocli.CommandLine.Model.OptionSpec;
/** The Environment variable default provider used in PicoCli. */
public class EnvironmentVariableDefaultProvider implements IDefaultValueProvider { public class EnvironmentVariableDefaultProvider implements IDefaultValueProvider {
private static final String ENV_VAR_PREFIX = "BESU_"; private static final String ENV_VAR_PREFIX = "BESU_";
private static final String LEGACY_ENV_VAR_PREFIX = "PANTHEON_"; private static final String LEGACY_ENV_VAR_PREFIX = "PANTHEON_";
private final Map<String, String> environment; private final Map<String, String> environment;
/**
* Instantiates a new Environment variable default provider.
*
* @param environment the environment
*/
public EnvironmentVariableDefaultProvider(final Map<String, String> environment) { public EnvironmentVariableDefaultProvider(final Map<String, String> environment) {
this.environment = environment; this.environment = environment;
} }

@ -36,12 +36,19 @@ import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Model.OptionSpec; import picocli.CommandLine.Model.OptionSpec;
import picocli.CommandLine.ParameterException; import picocli.CommandLine.ParameterException;
/** The Toml config file default value provider used by PicoCli. */
public class TomlConfigFileDefaultProvider implements IDefaultValueProvider { public class TomlConfigFileDefaultProvider implements IDefaultValueProvider {
private final CommandLine commandLine; private final CommandLine commandLine;
private final File configFile; private final File configFile;
private TomlParseResult result; private TomlParseResult result;
/**
* Instantiates a new Toml config file default value provider.
*
* @param commandLine the command line
* @param configFile the config file
*/
public TomlConfigFileDefaultProvider(final CommandLine commandLine, final File configFile) { public TomlConfigFileDefaultProvider(final CommandLine commandLine, final File configFile) {
this.commandLine = commandLine; this.commandLine = commandLine;
this.configFile = configFile; this.configFile = configFile;
@ -144,6 +151,7 @@ public class TomlConfigFileDefaultProvider implements IDefaultValueProvider {
commandLine, String.format("Unable to read TOML configuration file %s", configFile)); commandLine, String.format("Unable to read TOML configuration file %s", configFile));
} }
/** Load configuration from file. */
public void loadConfigurationFromFile() { public void loadConfigurationFromFile() {
if (result == null) { if (result == null) {

@ -21,9 +21,15 @@ import java.util.stream.Stream;
import picocli.CommandLine; import picocli.CommandLine;
/** The Version provider used by PicoCli to report Besu version on Cli. */
public class VersionProvider implements CommandLine.IVersionProvider { public class VersionProvider implements CommandLine.IVersionProvider {
private final PluginVersionsProvider pluginVersionsProvider; private final PluginVersionsProvider pluginVersionsProvider;
/**
* Instantiates a new Version provider.
*
* @param pluginVersionsProvider the plugin versions provider
*/
public VersionProvider(final PluginVersionsProvider pluginVersionsProvider) { public VersionProvider(final PluginVersionsProvider pluginVersionsProvider) {
this.pluginVersionsProvider = pluginVersionsProvider; this.pluginVersionsProvider = pluginVersionsProvider;
} }

@ -48,11 +48,15 @@ import org.apache.tuweni.units.bigints.UInt256;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Besu controller. */
public class BesuController implements java.io.Closeable { public class BesuController implements java.io.Closeable {
private static final Logger LOG = LoggerFactory.getLogger(BesuController.class); private static final Logger LOG = LoggerFactory.getLogger(BesuController.class);
/** The constant DATABASE_PATH. */
public static final String DATABASE_PATH = "database"; public static final String DATABASE_PATH = "database";
/** The constant CACHE_PATH. */
public static final String CACHE_PATH = "caches"; public static final String CACHE_PATH = "caches";
private final ProtocolSchedule protocolSchedule; private final ProtocolSchedule protocolSchedule;
private final ProtocolContext protocolContext; private final ProtocolContext protocolContext;
private final EthProtocolManager ethProtocolManager; private final EthProtocolManager ethProtocolManager;
@ -70,6 +74,25 @@ public class BesuController implements java.io.Closeable {
private final PluginServiceFactory additionalPluginServices; private final PluginServiceFactory additionalPluginServices;
private final SyncState syncState; private final SyncState syncState;
/**
* Instantiates a new Besu controller.
*
* @param protocolSchedule the protocol schedule
* @param protocolContext the protocol context
* @param ethProtocolManager the eth protocol manager
* @param genesisConfigOptions the genesis config options
* @param subProtocolConfiguration the sub protocol configuration
* @param synchronizer the synchronizer
* @param syncState the sync state
* @param transactionPool the transaction pool
* @param miningCoordinator the mining coordinator
* @param privacyParameters the privacy parameters
* @param miningParameters the mining parameters
* @param additionalJsonRpcMethodsFactory the additional json rpc methods factory
* @param nodeKey the node key
* @param closeables the closeables
* @param additionalPluginServices the additional plugin services
*/
BesuController( BesuController(
final ProtocolSchedule protocolSchedule, final ProtocolSchedule protocolSchedule,
final ProtocolContext protocolContext, final ProtocolContext protocolContext,
@ -103,38 +126,83 @@ public class BesuController implements java.io.Closeable {
this.additionalPluginServices = additionalPluginServices; this.additionalPluginServices = additionalPluginServices;
} }
/**
* Gets protocol context.
*
* @return the protocol context
*/
public ProtocolContext getProtocolContext() { public ProtocolContext getProtocolContext() {
return protocolContext; return protocolContext;
} }
/**
* Gets protocol schedule.
*
* @return the protocol schedule
*/
public ProtocolSchedule getProtocolSchedule() { public ProtocolSchedule getProtocolSchedule() {
return protocolSchedule; return protocolSchedule;
} }
/**
* Gets protocol manager.
*
* @return the protocol manager
*/
public EthProtocolManager getProtocolManager() { public EthProtocolManager getProtocolManager() {
return ethProtocolManager; return ethProtocolManager;
} }
/**
* Gets genesis config options.
*
* @return the genesis config options
*/
public GenesisConfigOptions getGenesisConfigOptions() { public GenesisConfigOptions getGenesisConfigOptions() {
return genesisConfigOptions; return genesisConfigOptions;
} }
/**
* Gets synchronizer.
*
* @return the synchronizer
*/
public Synchronizer getSynchronizer() { public Synchronizer getSynchronizer() {
return synchronizer; return synchronizer;
} }
/**
* Gets sub protocol configuration.
*
* @return the sub protocol configuration
*/
public SubProtocolConfiguration getSubProtocolConfiguration() { public SubProtocolConfiguration getSubProtocolConfiguration() {
return subProtocolConfiguration; return subProtocolConfiguration;
} }
/**
* Gets node key.
*
* @return the node key
*/
public NodeKey getNodeKey() { public NodeKey getNodeKey() {
return nodeKey; return nodeKey;
} }
/**
* Gets transaction pool.
*
* @return the transaction pool
*/
public TransactionPool getTransactionPool() { public TransactionPool getTransactionPool() {
return transactionPool; return transactionPool;
} }
/**
* Gets mining coordinator.
*
* @return the mining coordinator
*/
public MiningCoordinator getMiningCoordinator() { public MiningCoordinator getMiningCoordinator() {
return miningCoordinator; return miningCoordinator;
} }
@ -152,29 +220,64 @@ public class BesuController implements java.io.Closeable {
} }
} }
/**
* Gets privacy parameters.
*
* @return the privacy parameters
*/
public PrivacyParameters getPrivacyParameters() { public PrivacyParameters getPrivacyParameters() {
return privacyParameters; return privacyParameters;
} }
/**
* Gets mining parameters.
*
* @return the mining parameters
*/
public MiningParameters getMiningParameters() { public MiningParameters getMiningParameters() {
return miningParameters; return miningParameters;
} }
/**
* Gets additional json rpc methods.
*
* @param enabledRpcApis the enabled rpc apis
* @return the additional json rpc methods
*/
public Map<String, JsonRpcMethod> getAdditionalJsonRpcMethods( public Map<String, JsonRpcMethod> getAdditionalJsonRpcMethods(
final Collection<String> enabledRpcApis) { final Collection<String> enabledRpcApis) {
return additionalJsonRpcMethodsFactory.create(enabledRpcApis); return additionalJsonRpcMethodsFactory.create(enabledRpcApis);
} }
/**
* Gets sync state.
*
* @return the sync state
*/
public SyncState getSyncState() { public SyncState getSyncState() {
return syncState; return syncState;
} }
/**
* Gets additional plugin services.
*
* @return the additional plugin services
*/
public PluginServiceFactory getAdditionalPluginServices() { public PluginServiceFactory getAdditionalPluginServices() {
return additionalPluginServices; return additionalPluginServices;
} }
/** The type Builder. */
public static class Builder { public static class Builder {
/**
* From eth network config besu controller builder.
*
* @param ethNetworkConfig the eth network config
* @param genesisConfigOverrides the genesis config overrides
* @param syncMode The sync mode
* @return the besu controller builder
*/
public BesuControllerBuilder fromEthNetworkConfig( public BesuControllerBuilder fromEthNetworkConfig(
final EthNetworkConfig ethNetworkConfig, final EthNetworkConfig ethNetworkConfig,
final Map<String, String> genesisConfigOverrides, final Map<String, String> genesisConfigOverrides,
@ -186,11 +289,25 @@ public class BesuController implements java.io.Closeable {
.networkId(ethNetworkConfig.getNetworkId()); .networkId(ethNetworkConfig.getNetworkId());
} }
/**
* From genesis config besu controller builder.
*
* @param genesisConfig the genesis config
* @param syncMode The Sync Mode
* @return the besu controller builder
*/
public BesuControllerBuilder fromGenesisConfig( public BesuControllerBuilder fromGenesisConfig(
final GenesisConfigFile genesisConfig, final SyncMode syncMode) { final GenesisConfigFile genesisConfig, final SyncMode syncMode) {
return fromGenesisConfig(genesisConfig, Collections.emptyMap(), syncMode); return fromGenesisConfig(genesisConfig, Collections.emptyMap(), syncMode);
} }
/**
* From genesis config besu controller builder.
*
* @param genesisConfig the genesis config
* @param genesisConfigOverrides the genesis config overrides
* @return the besu controller builder
*/
BesuControllerBuilder fromGenesisConfig( BesuControllerBuilder fromGenesisConfig(
final GenesisConfigFile genesisConfig, final GenesisConfigFile genesisConfig,
final Map<String, String> genesisConfigOverrides, final Map<String, String> genesisConfigOverrides,

@ -107,178 +107,358 @@ import java.util.function.Supplier;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Besu controller builder that builds Besu Controller. */
public abstract class BesuControllerBuilder implements MiningParameterOverrides { public abstract class BesuControllerBuilder implements MiningParameterOverrides {
private static final Logger LOG = LoggerFactory.getLogger(BesuControllerBuilder.class); private static final Logger LOG = LoggerFactory.getLogger(BesuControllerBuilder.class);
private GenesisConfigFile genesisConfig; private GenesisConfigFile genesisConfig;
private Map<String, String> genesisConfigOverrides = Collections.emptyMap(); private Map<String, String> genesisConfigOverrides = Collections.emptyMap();
/** The Config options supplier. */
protected Supplier<GenesisConfigOptions> configOptionsSupplier = protected Supplier<GenesisConfigOptions> configOptionsSupplier =
() -> () ->
Optional.ofNullable(genesisConfig) Optional.ofNullable(genesisConfig)
.map(conf -> conf.getConfigOptions(genesisConfigOverrides)) .map(conf -> conf.getConfigOptions(genesisConfigOverrides))
.orElseGet(genesisConfig::getConfigOptions); .orElseGet(genesisConfig::getConfigOptions);
/** The Sync config. */
protected SynchronizerConfiguration syncConfig; protected SynchronizerConfiguration syncConfig;
/** The Ethereum wire protocol configuration. */
protected EthProtocolConfiguration ethereumWireProtocolConfiguration; protected EthProtocolConfiguration ethereumWireProtocolConfiguration;
/** The Transaction pool configuration. */
protected TransactionPoolConfiguration transactionPoolConfiguration; protected TransactionPoolConfiguration transactionPoolConfiguration;
/** The Network id. */
protected BigInteger networkId; protected BigInteger networkId;
/** The Mining parameters. */
protected MiningParameters miningParameters; protected MiningParameters miningParameters;
/** The Metrics system. */
protected ObservableMetricsSystem metricsSystem; protected ObservableMetricsSystem metricsSystem;
/** The Privacy parameters. */
protected PrivacyParameters privacyParameters; protected PrivacyParameters privacyParameters;
/** The Pki block creation configuration. */
protected Optional<PkiBlockCreationConfiguration> pkiBlockCreationConfiguration = protected Optional<PkiBlockCreationConfiguration> pkiBlockCreationConfiguration =
Optional.empty(); Optional.empty();
/** The Data directory. */
protected Path dataDirectory; protected Path dataDirectory;
/** The Clock. */
protected Clock clock; protected Clock clock;
/** The Node key. */
protected NodeKey nodeKey; protected NodeKey nodeKey;
/** The Is revert reason enabled. */
protected boolean isRevertReasonEnabled; protected boolean isRevertReasonEnabled;
/** The Gas limit calculator. */
GasLimitCalculator gasLimitCalculator; GasLimitCalculator gasLimitCalculator;
/** The Storage provider. */
protected StorageProvider storageProvider; protected StorageProvider storageProvider;
/** The Is pruning enabled. */
protected boolean isPruningEnabled; protected boolean isPruningEnabled;
/** The Pruner configuration. */
protected PrunerConfiguration prunerConfiguration; protected PrunerConfiguration prunerConfiguration;
/** The Required blocks. */
protected Map<Long, Hash> requiredBlocks = Collections.emptyMap(); protected Map<Long, Hash> requiredBlocks = Collections.emptyMap();
/** The Reorg logging threshold. */
protected long reorgLoggingThreshold; protected long reorgLoggingThreshold;
/** The Data storage configuration. */
protected DataStorageConfiguration dataStorageConfiguration = protected DataStorageConfiguration dataStorageConfiguration =
DataStorageConfiguration.DEFAULT_CONFIG; DataStorageConfiguration.DEFAULT_CONFIG;
/** The Message permissioning providers. */
protected List<NodeMessagePermissioningProvider> messagePermissioningProviders = protected List<NodeMessagePermissioningProvider> messagePermissioningProviders =
Collections.emptyList(); Collections.emptyList();
/** The Evm configuration. */
protected EvmConfiguration evmConfiguration; protected EvmConfiguration evmConfiguration;
/** The Max peers. */
protected int maxPeers; protected int maxPeers;
/** The Chain pruner configuration. */
protected ChainPrunerConfiguration chainPrunerConfiguration = ChainPrunerConfiguration.DEFAULT; protected ChainPrunerConfiguration chainPrunerConfiguration = ChainPrunerConfiguration.DEFAULT;
/**
* Storage provider besu controller builder.
*
* @param storageProvider the storage provider
* @return the besu controller builder
*/
public BesuControllerBuilder storageProvider(final StorageProvider storageProvider) { public BesuControllerBuilder storageProvider(final StorageProvider storageProvider) {
this.storageProvider = storageProvider; this.storageProvider = storageProvider;
return this; return this;
} }
/**
* Genesis config file besu controller builder.
*
* @param genesisConfig the genesis config
* @return the besu controller builder
*/
public BesuControllerBuilder genesisConfigFile(final GenesisConfigFile genesisConfig) { public BesuControllerBuilder genesisConfigFile(final GenesisConfigFile genesisConfig) {
this.genesisConfig = genesisConfig; this.genesisConfig = genesisConfig;
return this; return this;
} }
/**
* Synchronizer configuration besu controller builder.
*
* @param synchronizerConfig the synchronizer config
* @return the besu controller builder
*/
public BesuControllerBuilder synchronizerConfiguration( public BesuControllerBuilder synchronizerConfiguration(
final SynchronizerConfiguration synchronizerConfig) { final SynchronizerConfiguration synchronizerConfig) {
this.syncConfig = synchronizerConfig; this.syncConfig = synchronizerConfig;
return this; return this;
} }
/**
* Eth protocol configuration besu controller builder.
*
* @param ethProtocolConfiguration the eth protocol configuration
* @return the besu controller builder
*/
public BesuControllerBuilder ethProtocolConfiguration( public BesuControllerBuilder ethProtocolConfiguration(
final EthProtocolConfiguration ethProtocolConfiguration) { final EthProtocolConfiguration ethProtocolConfiguration) {
this.ethereumWireProtocolConfiguration = ethProtocolConfiguration; this.ethereumWireProtocolConfiguration = ethProtocolConfiguration;
return this; return this;
} }
/**
* Network id besu controller builder.
*
* @param networkId the network id
* @return the besu controller builder
*/
public BesuControllerBuilder networkId(final BigInteger networkId) { public BesuControllerBuilder networkId(final BigInteger networkId) {
this.networkId = networkId; this.networkId = networkId;
return this; return this;
} }
/**
* Mining parameters besu controller builder.
*
* @param miningParameters the mining parameters
* @return the besu controller builder
*/
public BesuControllerBuilder miningParameters(final MiningParameters miningParameters) { public BesuControllerBuilder miningParameters(final MiningParameters miningParameters) {
this.miningParameters = miningParameters; this.miningParameters = miningParameters;
return this; return this;
} }
/**
* Message permissioning providers besu controller builder.
*
* @param messagePermissioningProviders the message permissioning providers
* @return the besu controller builder
*/
public BesuControllerBuilder messagePermissioningProviders( public BesuControllerBuilder messagePermissioningProviders(
final List<NodeMessagePermissioningProvider> messagePermissioningProviders) { final List<NodeMessagePermissioningProvider> messagePermissioningProviders) {
this.messagePermissioningProviders = messagePermissioningProviders; this.messagePermissioningProviders = messagePermissioningProviders;
return this; return this;
} }
/**
* Node key besu controller builder.
*
* @param nodeKey the node key
* @return the besu controller builder
*/
public BesuControllerBuilder nodeKey(final NodeKey nodeKey) { public BesuControllerBuilder nodeKey(final NodeKey nodeKey) {
this.nodeKey = nodeKey; this.nodeKey = nodeKey;
return this; return this;
} }
/**
* Metrics system besu controller builder.
*
* @param metricsSystem the metrics system
* @return the besu controller builder
*/
public BesuControllerBuilder metricsSystem(final ObservableMetricsSystem metricsSystem) { public BesuControllerBuilder metricsSystem(final ObservableMetricsSystem metricsSystem) {
this.metricsSystem = metricsSystem; this.metricsSystem = metricsSystem;
return this; return this;
} }
/**
* Privacy parameters besu controller builder.
*
* @param privacyParameters the privacy parameters
* @return the besu controller builder
*/
public BesuControllerBuilder privacyParameters(final PrivacyParameters privacyParameters) { public BesuControllerBuilder privacyParameters(final PrivacyParameters privacyParameters) {
this.privacyParameters = privacyParameters; this.privacyParameters = privacyParameters;
return this; return this;
} }
/**
* Pki block creation configuration besu controller builder.
*
* @param pkiBlockCreationConfiguration the pki block creation configuration
* @return the besu controller builder
*/
public BesuControllerBuilder pkiBlockCreationConfiguration( public BesuControllerBuilder pkiBlockCreationConfiguration(
final Optional<PkiBlockCreationConfiguration> pkiBlockCreationConfiguration) { final Optional<PkiBlockCreationConfiguration> pkiBlockCreationConfiguration) {
this.pkiBlockCreationConfiguration = pkiBlockCreationConfiguration; this.pkiBlockCreationConfiguration = pkiBlockCreationConfiguration;
return this; return this;
} }
/**
* Data directory besu controller builder.
*
* @param dataDirectory the data directory
* @return the besu controller builder
*/
public BesuControllerBuilder dataDirectory(final Path dataDirectory) { public BesuControllerBuilder dataDirectory(final Path dataDirectory) {
this.dataDirectory = dataDirectory; this.dataDirectory = dataDirectory;
return this; return this;
} }
/**
* Clock besu controller builder.
*
* @param clock the clock
* @return the besu controller builder
*/
public BesuControllerBuilder clock(final Clock clock) { public BesuControllerBuilder clock(final Clock clock) {
this.clock = clock; this.clock = clock;
return this; return this;
} }
/**
* Transaction pool configuration besu controller builder.
*
* @param transactionPoolConfiguration the transaction pool configuration
* @return the besu controller builder
*/
public BesuControllerBuilder transactionPoolConfiguration( public BesuControllerBuilder transactionPoolConfiguration(
final TransactionPoolConfiguration transactionPoolConfiguration) { final TransactionPoolConfiguration transactionPoolConfiguration) {
this.transactionPoolConfiguration = transactionPoolConfiguration; this.transactionPoolConfiguration = transactionPoolConfiguration;
return this; return this;
} }
/**
* Is revert reason enabled besu controller builder.
*
* @param isRevertReasonEnabled the is revert reason enabled
* @return the besu controller builder
*/
public BesuControllerBuilder isRevertReasonEnabled(final boolean isRevertReasonEnabled) { public BesuControllerBuilder isRevertReasonEnabled(final boolean isRevertReasonEnabled) {
this.isRevertReasonEnabled = isRevertReasonEnabled; this.isRevertReasonEnabled = isRevertReasonEnabled;
return this; return this;
} }
/**
* Is pruning enabled besu controller builder.
*
* @param isPruningEnabled the is pruning enabled
* @return the besu controller builder
*/
public BesuControllerBuilder isPruningEnabled(final boolean isPruningEnabled) { public BesuControllerBuilder isPruningEnabled(final boolean isPruningEnabled) {
this.isPruningEnabled = isPruningEnabled; this.isPruningEnabled = isPruningEnabled;
return this; return this;
} }
/**
* Pruning configuration besu controller builder.
*
* @param prunerConfiguration the pruner configuration
* @return the besu controller builder
*/
public BesuControllerBuilder pruningConfiguration(final PrunerConfiguration prunerConfiguration) { public BesuControllerBuilder pruningConfiguration(final PrunerConfiguration prunerConfiguration) {
this.prunerConfiguration = prunerConfiguration; this.prunerConfiguration = prunerConfiguration;
return this; return this;
} }
/**
* Genesis config overrides besu controller builder.
*
* @param genesisConfigOverrides the genesis config overrides
* @return the besu controller builder
*/
public BesuControllerBuilder genesisConfigOverrides( public BesuControllerBuilder genesisConfigOverrides(
final Map<String, String> genesisConfigOverrides) { final Map<String, String> genesisConfigOverrides) {
this.genesisConfigOverrides = genesisConfigOverrides; this.genesisConfigOverrides = genesisConfigOverrides;
return this; return this;
} }
/**
* Gas limit calculator besu controller builder.
*
* @param gasLimitCalculator the gas limit calculator
* @return the besu controller builder
*/
public BesuControllerBuilder gasLimitCalculator(final GasLimitCalculator gasLimitCalculator) { public BesuControllerBuilder gasLimitCalculator(final GasLimitCalculator gasLimitCalculator) {
this.gasLimitCalculator = gasLimitCalculator; this.gasLimitCalculator = gasLimitCalculator;
return this; return this;
} }
/**
* Required blocks besu controller builder.
*
* @param requiredBlocks the required blocks
* @return the besu controller builder
*/
public BesuControllerBuilder requiredBlocks(final Map<Long, Hash> requiredBlocks) { public BesuControllerBuilder requiredBlocks(final Map<Long, Hash> requiredBlocks) {
this.requiredBlocks = requiredBlocks; this.requiredBlocks = requiredBlocks;
return this; return this;
} }
/**
* Reorg logging threshold besu controller builder.
*
* @param reorgLoggingThreshold the reorg logging threshold
* @return the besu controller builder
*/
public BesuControllerBuilder reorgLoggingThreshold(final long reorgLoggingThreshold) { public BesuControllerBuilder reorgLoggingThreshold(final long reorgLoggingThreshold) {
this.reorgLoggingThreshold = reorgLoggingThreshold; this.reorgLoggingThreshold = reorgLoggingThreshold;
return this; return this;
} }
/**
* Data storage configuration besu controller builder.
*
* @param dataStorageConfiguration the data storage configuration
* @return the besu controller builder
*/
public BesuControllerBuilder dataStorageConfiguration( public BesuControllerBuilder dataStorageConfiguration(
final DataStorageConfiguration dataStorageConfiguration) { final DataStorageConfiguration dataStorageConfiguration) {
this.dataStorageConfiguration = dataStorageConfiguration; this.dataStorageConfiguration = dataStorageConfiguration;
return this; return this;
} }
/**
* Evm configuration besu controller builder.
*
* @param evmConfiguration the evm configuration
* @return the besu controller builder
*/
public BesuControllerBuilder evmConfiguration(final EvmConfiguration evmConfiguration) { public BesuControllerBuilder evmConfiguration(final EvmConfiguration evmConfiguration) {
this.evmConfiguration = evmConfiguration; this.evmConfiguration = evmConfiguration;
return this; return this;
} }
/**
* Max peers besu controller builder.
*
* @param maxPeers the max peers
* @return the besu controller builder
*/
public BesuControllerBuilder maxPeers(final int maxPeers) { public BesuControllerBuilder maxPeers(final int maxPeers) {
this.maxPeers = maxPeers; this.maxPeers = maxPeers;
return this; return this;
} }
/**
* Chain pruning configuration besu controller builder.
*
* @param chainPrunerConfiguration the chain pruner configuration
* @return the besu controller builder
*/
public BesuControllerBuilder chainPruningConfiguration( public BesuControllerBuilder chainPruningConfiguration(
final ChainPrunerConfiguration chainPrunerConfiguration) { final ChainPrunerConfiguration chainPrunerConfiguration) {
this.chainPrunerConfiguration = chainPrunerConfiguration; this.chainPrunerConfiguration = chainPrunerConfiguration;
return this; return this;
} }
/**
* Build besu controller.
*
* @return the besu controller
*/
public BesuController build() { public BesuController build() {
checkNotNull(genesisConfig, "Missing genesis config"); checkNotNull(genesisConfig, "Missing genesis config");
checkNotNull(syncConfig, "Missing sync config"); checkNotNull(syncConfig, "Missing sync config");
@ -495,6 +675,19 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
additionalPluginServices); additionalPluginServices);
} }
/**
* Create synchronizer synchronizer.
*
* @param protocolSchedule the protocol schedule
* @param worldStateStorage the world state storage
* @param protocolContext the protocol context
* @param maybePruner the maybe pruner
* @param ethContext the eth context
* @param syncState the sync state
* @param ethProtocolManager the eth protocol manager
* @param pivotBlockSelector the pivot block selector
* @return the synchronizer
*/
protected Synchronizer createSynchronizer( protected Synchronizer createSynchronizer(
final ProtocolSchedule protocolSchedule, final ProtocolSchedule protocolSchedule,
final WorldStateStorage worldStateStorage, final WorldStateStorage worldStateStorage,
@ -564,6 +757,12 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
} }
} }
/**
* Gets full sync termination condition.
*
* @param blockchain the blockchain
* @return the full sync termination condition
*/
protected SyncTerminationCondition getFullSyncTerminationCondition(final Blockchain blockchain) { protected SyncTerminationCondition getFullSyncTerminationCondition(final Blockchain blockchain) {
return configOptionsSupplier return configOptionsSupplier
.get() .get()
@ -572,13 +771,27 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
.orElse(SyncTerminationCondition.never()); .orElse(SyncTerminationCondition.never());
} }
/** Prep for build. */
protected void prepForBuild() {} protected void prepForBuild() {}
/**
* Create additional json rpc method factory json rpc methods.
*
* @param protocolContext the protocol context
* @return the json rpc methods
*/
protected JsonRpcMethods createAdditionalJsonRpcMethodFactory( protected JsonRpcMethods createAdditionalJsonRpcMethodFactory(
final ProtocolContext protocolContext) { final ProtocolContext protocolContext) {
return apis -> Collections.emptyMap(); return apis -> Collections.emptyMap();
} }
/**
* Create sub protocol configuration sub protocol configuration.
*
* @param ethProtocolManager the eth protocol manager
* @param maybeSnapProtocolManager the maybe snap protocol manager
* @return the sub protocol configuration
*/
protected SubProtocolConfiguration createSubProtocolConfiguration( protected SubProtocolConfiguration createSubProtocolConfiguration(
final EthProtocolManager ethProtocolManager, final EthProtocolManager ethProtocolManager,
final Optional<SnapProtocolManager> maybeSnapProtocolManager) { final Optional<SnapProtocolManager> maybeSnapProtocolManager) {
@ -591,6 +804,17 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
return subProtocolConfiguration; return subProtocolConfiguration;
} }
/**
* Create mining coordinator mining coordinator.
*
* @param protocolSchedule the protocol schedule
* @param protocolContext the protocol context
* @param transactionPool the transaction pool
* @param miningParameters the mining parameters
* @param syncState the sync state
* @param ethProtocolManager the eth protocol manager
* @return the mining coordinator
*/
protected abstract MiningCoordinator createMiningCoordinator( protected abstract MiningCoordinator createMiningCoordinator(
ProtocolSchedule protocolSchedule, ProtocolSchedule protocolSchedule,
ProtocolContext protocolContext, ProtocolContext protocolContext,
@ -599,19 +823,57 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
SyncState syncState, SyncState syncState,
EthProtocolManager ethProtocolManager); EthProtocolManager ethProtocolManager);
/**
* Create protocol schedule protocol schedule.
*
* @return the protocol schedule
*/
protected abstract ProtocolSchedule createProtocolSchedule(); protected abstract ProtocolSchedule createProtocolSchedule();
/**
* Validate context.
*
* @param context the context
*/
protected void validateContext(final ProtocolContext context) {} protected void validateContext(final ProtocolContext context) {}
/**
* Create consensus context consensus context.
*
* @param blockchain the blockchain
* @param worldStateArchive the world state archive
* @param protocolSchedule the protocol schedule
* @return the consensus context
*/
protected abstract ConsensusContext createConsensusContext( protected abstract ConsensusContext createConsensusContext(
Blockchain blockchain, Blockchain blockchain,
WorldStateArchive worldStateArchive, WorldStateArchive worldStateArchive,
ProtocolSchedule protocolSchedule); ProtocolSchedule protocolSchedule);
/**
* Gets supported protocol.
*
* @return the supported protocol
*/
protected String getSupportedProtocol() { protected String getSupportedProtocol() {
return EthProtocol.NAME; return EthProtocol.NAME;
} }
/**
* Create eth protocol manager eth protocol manager.
*
* @param protocolContext the protocol context
* @param synchronizerConfiguration the synchronizer configuration
* @param transactionPool the transaction pool
* @param ethereumWireProtocolConfiguration the ethereum wire protocol configuration
* @param ethPeers the eth peers
* @param ethContext the eth context
* @param ethMessages the eth messages
* @param scheduler the scheduler
* @param peerValidators the peer validators
* @param mergePeerFilter the merge peer filter
* @return the eth protocol manager
*/
protected EthProtocolManager createEthProtocolManager( protected EthProtocolManager createEthProtocolManager(
final ProtocolContext protocolContext, final ProtocolContext protocolContext,
final SynchronizerConfiguration synchronizerConfiguration, final SynchronizerConfiguration synchronizerConfiguration,
@ -640,6 +902,15 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
genesisConfig.getForkTimestamps()); genesisConfig.getForkTimestamps());
} }
/**
* Create protocol context protocol context.
*
* @param blockchain the blockchain
* @param worldStateArchive the world state archive
* @param protocolSchedule the protocol schedule
* @param consensusContextFactory the consensus context factory
* @return the protocol context
*/
protected ProtocolContext createProtocolContext( protected ProtocolContext createProtocolContext(
final MutableBlockchain blockchain, final MutableBlockchain blockchain,
final WorldStateArchive worldStateArchive, final WorldStateArchive worldStateArchive,
@ -695,6 +966,12 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
metricsSystem)); metricsSystem));
} }
/**
* Create peer validators list.
*
* @param protocolSchedule the protocol schedule
* @return the list
*/
protected List<PeerValidator> createPeerValidators(final ProtocolSchedule protocolSchedule) { protected List<PeerValidator> createPeerValidators(final ProtocolSchedule protocolSchedule) {
final List<PeerValidator> validators = new ArrayList<>(); final List<PeerValidator> validators = new ArrayList<>();
@ -732,6 +1009,13 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
return validators; return validators;
} }
/**
* Create additional plugin services plugin service factory.
*
* @param blockchain the blockchain
* @param protocolContext the protocol context
* @return the plugin service factory
*/
protected abstract PluginServiceFactory createAdditionalPluginServices( protected abstract PluginServiceFactory createAdditionalPluginServices(
final Blockchain blockchain, final ProtocolContext protocolContext); final Blockchain blockchain, final ProtocolContext protocolContext);
} }

@ -22,10 +22,21 @@ import java.util.function.Supplier;
import com.google.common.base.Suppliers; import com.google.common.base.Suppliers;
/** Base class for BFT based Besu Controller Builders. */
public abstract class BftBesuControllerBuilder extends BesuControllerBuilder { public abstract class BftBesuControllerBuilder extends BesuControllerBuilder {
/**
* Bft extra data codec supplier.
*
* @return the supplier of type BftExtraDataCodec.
*/
protected abstract Supplier<BftExtraDataCodec> bftExtraDataCodec(); protected abstract Supplier<BftExtraDataCodec> bftExtraDataCodec();
/**
* Bft block interface supplier.
*
* @return the supplier of type BftBlockInterface.
*/
protected Supplier<BftBlockInterface> bftBlockInterface() { protected Supplier<BftBlockInterface> bftBlockInterface() {
return Suppliers.memoize(() -> new BftBlockInterface(bftExtraDataCodec().get())); return Suppliers.memoize(() -> new BftBlockInterface(bftExtraDataCodec().get()));
} }

@ -25,6 +25,7 @@ import org.hyperledger.besu.plugin.services.query.BftQueryService;
import org.hyperledger.besu.plugin.services.query.PoaQueryService; import org.hyperledger.besu.plugin.services.query.PoaQueryService;
import org.hyperledger.besu.services.BesuPluginContextImpl; import org.hyperledger.besu.services.BesuPluginContextImpl;
/** Bft query plugin service factory which is a concrete implementation of PluginServiceFactory. */
public class BftQueryPluginServiceFactory implements PluginServiceFactory { public class BftQueryPluginServiceFactory implements PluginServiceFactory {
private final Blockchain blockchain; private final Blockchain blockchain;
@ -33,6 +34,15 @@ public class BftQueryPluginServiceFactory implements PluginServiceFactory {
private final NodeKey nodeKey; private final NodeKey nodeKey;
private final String consensusMechanismName; private final String consensusMechanismName;
/**
* Instantiates a new Bft query plugin service factory.
*
* @param blockchain the blockchain
* @param bftExtraDataCodec the bft extra data codec
* @param validatorProvider the validator provider
* @param nodeKey the node key
* @param consensusMechanismName the consensus mechanism name
*/
public BftQueryPluginServiceFactory( public BftQueryPluginServiceFactory(
final Blockchain blockchain, final Blockchain blockchain,
final BftExtraDataCodec bftExtraDataCodec, final BftExtraDataCodec bftExtraDataCodec,

@ -45,6 +45,7 @@ import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Clique consensus controller builder. */
public class CliqueBesuControllerBuilder extends BesuControllerBuilder { public class CliqueBesuControllerBuilder extends BesuControllerBuilder {
private static final Logger LOG = LoggerFactory.getLogger(CliqueBesuControllerBuilder.class); private static final Logger LOG = LoggerFactory.getLogger(CliqueBesuControllerBuilder.class);

@ -23,11 +23,18 @@ import org.hyperledger.besu.plugin.services.metrics.PoAMetricsService;
import org.hyperledger.besu.plugin.services.query.PoaQueryService; import org.hyperledger.besu.plugin.services.query.PoaQueryService;
import org.hyperledger.besu.services.BesuPluginContextImpl; import org.hyperledger.besu.services.BesuPluginContextImpl;
/** The Clique query plugin service factory. */
public class CliqueQueryPluginServiceFactory implements PluginServiceFactory { public class CliqueQueryPluginServiceFactory implements PluginServiceFactory {
private final Blockchain blockchain; private final Blockchain blockchain;
private final NodeKey nodeKey; private final NodeKey nodeKey;
/**
* Instantiates a new Clique query plugin service factory.
*
* @param blockchain the blockchain
* @param nodeKey the node key
*/
public CliqueQueryPluginServiceFactory(final Blockchain blockchain, final NodeKey nodeKey) { public CliqueQueryPluginServiceFactory(final Blockchain blockchain, final NodeKey nodeKey) {
this.blockchain = blockchain; this.blockchain = blockchain;
this.nodeKey = nodeKey; this.nodeKey = nodeKey;

@ -78,9 +78,9 @@ import java.util.stream.Collectors;
import com.google.common.annotations.VisibleForTesting; import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions; import com.google.common.base.Preconditions;
/* /**
This is a placeholder class for the QBFT migration logic. For now, all it does is to delegate any * This is a placeholder class for the QBFT migration logic. For now, all it does is to delegate any
BesuControllerBuilder to the first controller in the list. * BesuControllerBuilder to the first controller in the list.
*/ */
public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilder { public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilder {
@ -89,6 +89,11 @@ public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilde
NavigableSet<ForkSpec<ProtocolSchedule>>, Optional<BigInteger>, ProtocolSchedule> NavigableSet<ForkSpec<ProtocolSchedule>>, Optional<BigInteger>, ProtocolSchedule>
combinedProtocolScheduleFactory; combinedProtocolScheduleFactory;
/**
* Instantiates a new Consensus schedule Besu controller builder.
*
* @param besuControllerBuilderSchedule the besu controller builder schedule
*/
public ConsensusScheduleBesuControllerBuilder( public ConsensusScheduleBesuControllerBuilder(
final Map<Long, BesuControllerBuilder> besuControllerBuilderSchedule) { final Map<Long, BesuControllerBuilder> besuControllerBuilderSchedule) {
this( this(
@ -97,6 +102,12 @@ public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilde
new CombinedProtocolScheduleFactory().create(protocolScheduleSpecs, chainId)); new CombinedProtocolScheduleFactory().create(protocolScheduleSpecs, chainId));
} }
/**
* Instantiates a new Consensus schedule besu controller builder. Visible for testing.
*
* @param besuControllerBuilderSchedule the besu controller builder schedule
* @param combinedProtocolScheduleFactory the combined protocol schedule factory
*/
@VisibleForTesting @VisibleForTesting
protected ConsensusScheduleBesuControllerBuilder( protected ConsensusScheduleBesuControllerBuilder(
final Map<Long, BesuControllerBuilder> besuControllerBuilderSchedule, final Map<Long, BesuControllerBuilder> besuControllerBuilderSchedule,
@ -415,6 +426,11 @@ public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilde
return super.evmConfiguration(evmConfiguration); return super.evmConfiguration(evmConfiguration);
} }
/**
* Gets besu controller builder schedule. Visible for testing.
*
* @return the Besu controller builder schedule
*/
@VisibleForTesting @VisibleForTesting
Map<Long, BesuControllerBuilder> getBesuControllerBuilderSchedule() { Map<Long, BesuControllerBuilder> getBesuControllerBuilderSchedule() {
return besuControllerBuilderSchedule; return besuControllerBuilderSchedule;

@ -84,6 +84,7 @@ import com.google.common.base.Suppliers;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Ibft besu controller builder. */
public class IbftBesuControllerBuilder extends BftBesuControllerBuilder { public class IbftBesuControllerBuilder extends BftBesuControllerBuilder {
private static final Logger LOG = LoggerFactory.getLogger(IbftBesuControllerBuilder.class); private static final Logger LOG = LoggerFactory.getLogger(IbftBesuControllerBuilder.class);

@ -52,12 +52,14 @@ import java.util.Optional;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Ibft legacy besu controller builder. */
public class IbftLegacyBesuControllerBuilder extends BesuControllerBuilder { public class IbftLegacyBesuControllerBuilder extends BesuControllerBuilder {
private static final Logger LOG = LoggerFactory.getLogger(IbftLegacyBesuControllerBuilder.class); private static final Logger LOG = LoggerFactory.getLogger(IbftLegacyBesuControllerBuilder.class);
private final BlockInterface blockInterface = new IbftLegacyBlockInterface(); private final BlockInterface blockInterface = new IbftLegacyBlockInterface();
// TODO remove this warning once IBFT1 has been deprecated // TODO remove this warning once IBFT1 has been deprecated
/** Default constructor */
public IbftLegacyBesuControllerBuilder() { public IbftLegacyBesuControllerBuilder() {
LOG.warn( LOG.warn(
"IBFT1 is being deprecated and will be removed in a future release. Consider using QBFT instead of IBFT1 or using GoQuorum instead of Besu if you need to use IBFT1"); "IBFT1 is being deprecated and will be removed in a future release. Consider using QBFT instead of IBFT1 or using GoQuorum instead of Besu if you need to use IBFT1");

@ -26,6 +26,7 @@ import org.hyperledger.besu.plugin.services.query.IbftQueryService;
import org.hyperledger.besu.plugin.services.query.PoaQueryService; import org.hyperledger.besu.plugin.services.query.PoaQueryService;
import org.hyperledger.besu.services.BesuPluginContextImpl; import org.hyperledger.besu.services.BesuPluginContextImpl;
/** The IBFT query plugin service factory. */
public class IbftQueryPluginServiceFactory implements PluginServiceFactory { public class IbftQueryPluginServiceFactory implements PluginServiceFactory {
private final Blockchain blockchain; private final Blockchain blockchain;
@ -33,6 +34,14 @@ public class IbftQueryPluginServiceFactory implements PluginServiceFactory {
private final ValidatorProvider validatorProvider; private final ValidatorProvider validatorProvider;
private final NodeKey nodeKey; private final NodeKey nodeKey;
/**
* Instantiates a new Ibft query plugin service factory.
*
* @param blockchain the blockchain
* @param blockInterface the block interface
* @param validatorProvider the validator provider
* @param nodeKey the node key
*/
public IbftQueryPluginServiceFactory( public IbftQueryPluginServiceFactory(
final Blockchain blockchain, final Blockchain blockchain,
final BftBlockInterface blockInterface, final BftBlockInterface blockInterface,

@ -31,6 +31,7 @@ import org.hyperledger.besu.ethereum.mainnet.MainnetProtocolSchedule;
import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule; import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
/** The Mainnet besu controller builder. */
public class MainnetBesuControllerBuilder extends BesuControllerBuilder { public class MainnetBesuControllerBuilder extends BesuControllerBuilder {
private EpochCalculator epochCalculator = new EpochCalculator.DefaultEpochCalculator(); private EpochCalculator epochCalculator = new EpochCalculator.DefaultEpochCalculator();

@ -57,6 +57,7 @@ import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Merge besu controller builder. */
public class MergeBesuControllerBuilder extends BesuControllerBuilder { public class MergeBesuControllerBuilder extends BesuControllerBuilder {
private final AtomicReference<SyncState> syncState = new AtomicReference<>(); private final AtomicReference<SyncState> syncState = new AtomicReference<>();
private static final Logger LOG = LoggerFactory.getLogger(MergeBesuControllerBuilder.class); private static final Logger LOG = LoggerFactory.getLogger(MergeBesuControllerBuilder.class);
@ -135,6 +136,18 @@ public class MergeBesuControllerBuilder extends BesuControllerBuilder {
return ethProtocolManager; return ethProtocolManager;
} }
/**
* Create transition mining coordinator.
*
* @param protocolSchedule the protocol schedule
* @param protocolContext the protocol context
* @param transactionPool the transaction pool
* @param miningParameters the mining parameters
* @param syncState the sync state
* @param backwardSyncContext the backward sync context
* @param metricsSystem the metrics system
* @return the mining coordinator
*/
protected MiningCoordinator createTransitionMiningCoordinator( protected MiningCoordinator createTransitionMiningCoordinator(
final ProtocolSchedule protocolSchedule, final ProtocolSchedule protocolSchedule,
final ProtocolContext protocolContext, final ProtocolContext protocolContext,
@ -243,6 +256,11 @@ public class MergeBesuControllerBuilder extends BesuControllerBuilder {
return controller; return controller;
} }
/**
* Create timestamp protocol schedule.
*
* @return the timestamp schedule
*/
public TimestampSchedule createTimestampProtocolSchedule() { public TimestampSchedule createTimestampProtocolSchedule() {
return MergeProtocolSchedule.createTimestamp( return MergeProtocolSchedule.createTimestamp(
configOptionsSupplier.get(), privacyParameters, isRevertReasonEnabled); configOptionsSupplier.get(), privacyParameters, isRevertReasonEnabled);

@ -21,6 +21,12 @@ import org.hyperledger.besu.ethereum.core.MiningParameters;
* overrides. * overrides.
*/ */
public interface MiningParameterOverrides { public interface MiningParameterOverrides {
/**
* Overrides MiningParameter.
*
* @param fromCli The mining parameters that contains original values.
* @return MiningParameters constructed from provided param with additional overridden parameters.
*/
default MiningParameters getMiningParameterOverrides(final MiningParameters fromCli) { default MiningParameters getMiningParameterOverrides(final MiningParameters fromCli) {
return fromCli; return fromCli;
} }

@ -16,6 +16,7 @@ package org.hyperledger.besu.controller;
import org.hyperledger.besu.services.BesuPluginContextImpl; import org.hyperledger.besu.services.BesuPluginContextImpl;
/** The Noop plugin service factory. */
public class NoopPluginServiceFactory implements PluginServiceFactory { public class NoopPluginServiceFactory implements PluginServiceFactory {
@Override @Override

@ -16,7 +16,13 @@ package org.hyperledger.besu.controller;
import org.hyperledger.besu.services.BesuPluginContextImpl; import org.hyperledger.besu.services.BesuPluginContextImpl;
/** The interface Plugin service factory. */
public interface PluginServiceFactory { public interface PluginServiceFactory {
/**
* Appends concrete plugin service in provided Besu Plugin Context.
*
* @param besuContext An instance of BesuPluginContextImpl.
*/
void appendPluginServices(BesuPluginContextImpl besuContext); void appendPluginServices(BesuPluginContextImpl besuContext);
} }

@ -94,6 +94,7 @@ import com.google.common.base.Suppliers;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Qbft Besu controller builder. */
public class QbftBesuControllerBuilder extends BftBesuControllerBuilder { public class QbftBesuControllerBuilder extends BftBesuControllerBuilder {
private static final Logger LOG = LoggerFactory.getLogger(QbftBesuControllerBuilder.class); private static final Logger LOG = LoggerFactory.getLogger(QbftBesuControllerBuilder.class);

@ -72,6 +72,7 @@ import java.util.function.Consumer;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Transition besu controller builder. */
public class TransitionBesuControllerBuilder extends BesuControllerBuilder { public class TransitionBesuControllerBuilder extends BesuControllerBuilder {
private final BesuControllerBuilder preMergeBesuControllerBuilder; private final BesuControllerBuilder preMergeBesuControllerBuilder;
private final MergeBesuControllerBuilder mergeBesuControllerBuilder; private final MergeBesuControllerBuilder mergeBesuControllerBuilder;
@ -79,6 +80,12 @@ public class TransitionBesuControllerBuilder extends BesuControllerBuilder {
private static final Logger LOG = LoggerFactory.getLogger(TransitionBesuControllerBuilder.class); private static final Logger LOG = LoggerFactory.getLogger(TransitionBesuControllerBuilder.class);
private TransitionProtocolSchedule transitionProtocolSchedule; private TransitionProtocolSchedule transitionProtocolSchedule;
/**
* Instantiates a new Transition besu controller builder.
*
* @param preMergeBesuControllerBuilder the pre merge besu controller builder
* @param mergeBesuControllerBuilder the merge besu controller builder
*/
public TransitionBesuControllerBuilder( public TransitionBesuControllerBuilder(
final BesuControllerBuilder preMergeBesuControllerBuilder, final BesuControllerBuilder preMergeBesuControllerBuilder,
final MergeBesuControllerBuilder mergeBesuControllerBuilder) { final MergeBesuControllerBuilder mergeBesuControllerBuilder) {

@ -18,11 +18,18 @@ import org.hyperledger.besu.plugin.services.BesuConfiguration;
import java.nio.file.Path; import java.nio.file.Path;
/** A concrete implementation of BesuConfiguration which is used in Besu plugin framework. */
public class BesuConfigurationImpl implements BesuConfiguration { public class BesuConfigurationImpl implements BesuConfiguration {
private final Path storagePath; private final Path storagePath;
private final Path dataPath; private final Path dataPath;
/**
* BesuConfigurationImpl Constructor.
*
* @param dataPath The Path representing data folder
* @param storagePath The path representing storage folder
*/
public BesuConfigurationImpl(final Path dataPath, final Path storagePath) { public BesuConfigurationImpl(final Path dataPath, final Path storagePath) {
this.dataPath = dataPath; this.dataPath = dataPath;
this.storagePath = storagePath; this.storagePath = storagePath;

@ -38,12 +38,21 @@ import java.util.function.Supplier;
import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256; import org.apache.tuweni.units.bigints.UInt256;
/** A concrete implementation of BesuEvents used in Besu plugin framework. */
public class BesuEventsImpl implements BesuEvents { public class BesuEventsImpl implements BesuEvents {
private final Blockchain blockchain; private final Blockchain blockchain;
private final BlockBroadcaster blockBroadcaster; private final BlockBroadcaster blockBroadcaster;
private final TransactionPool transactionPool; private final TransactionPool transactionPool;
private final SyncState syncState; private final SyncState syncState;
/**
* Constructor for BesuEventsImpl
*
* @param blockchain An instance of Blockchain
* @param blockBroadcaster An instance of BlockBroadcaster
* @param transactionPool An instance of TransactionPool
* @param syncState An instance of SyncState
*/
public BesuEventsImpl( public BesuEventsImpl(
final Blockchain blockchain, final Blockchain blockchain,
final BlockBroadcaster blockBroadcaster, final BlockBroadcaster blockBroadcaster,

@ -45,19 +45,29 @@ import com.google.common.annotations.VisibleForTesting;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Besu plugin context implementation. */
public class BesuPluginContextImpl implements BesuContext, PluginVersionsProvider { public class BesuPluginContextImpl implements BesuContext, PluginVersionsProvider {
private static final Logger LOG = LoggerFactory.getLogger(BesuPluginContextImpl.class); private static final Logger LOG = LoggerFactory.getLogger(BesuPluginContextImpl.class);
private enum Lifecycle { private enum Lifecycle {
/** Uninitialized lifecycle. */
UNINITIALIZED, UNINITIALIZED,
/** Registering lifecycle. */
REGISTERING, REGISTERING,
/** Registered lifecycle. */
REGISTERED, REGISTERED,
/** Before external services started lifecycle. */
BEFORE_EXTERNAL_SERVICES_STARTED, BEFORE_EXTERNAL_SERVICES_STARTED,
/** Before external services finished lifecycle. */
BEFORE_EXTERNAL_SERVICES_FINISHED, BEFORE_EXTERNAL_SERVICES_FINISHED,
/** Before main loop started lifecycle. */
BEFORE_MAIN_LOOP_STARTED, BEFORE_MAIN_LOOP_STARTED,
/** Before main loop finished lifecycle. */
BEFORE_MAIN_LOOP_FINISHED, BEFORE_MAIN_LOOP_FINISHED,
/** Stopping lifecycle. */
STOPPING, STOPPING,
/** Stopped lifecycle. */
STOPPED STOPPED
} }
@ -66,6 +76,13 @@ public class BesuPluginContextImpl implements BesuContext, PluginVersionsProvide
private final List<BesuPlugin> plugins = new ArrayList<>(); private final List<BesuPlugin> plugins = new ArrayList<>();
private final List<String> pluginVersions = new ArrayList<>(); private final List<String> pluginVersions = new ArrayList<>();
/**
* Add service.
*
* @param <T> the type parameter
* @param serviceType the service type
* @param service the service
*/
public <T extends BesuService> void addService(final Class<T> serviceType, final T service) { public <T extends BesuService> void addService(final Class<T> serviceType, final T service) {
checkArgument(serviceType.isInterface(), "Services must be Java interfaces."); checkArgument(serviceType.isInterface(), "Services must be Java interfaces.");
checkArgument( checkArgument(
@ -80,6 +97,11 @@ public class BesuPluginContextImpl implements BesuContext, PluginVersionsProvide
return Optional.ofNullable((T) serviceRegistry.get(serviceType)); return Optional.ofNullable((T) serviceRegistry.get(serviceType));
} }
/**
* Register plugins.
*
* @param pluginsDir the plugins dir
*/
public void registerPlugins(final Path pluginsDir) { public void registerPlugins(final Path pluginsDir) {
checkState( checkState(
state == Lifecycle.UNINITIALIZED, state == Lifecycle.UNINITIALIZED,
@ -128,6 +150,7 @@ public class BesuPluginContextImpl implements BesuContext, PluginVersionsProvide
pluginVersions.add(pluginVersion); pluginVersions.add(pluginVersion);
} }
/** Before external services. */
public void beforeExternalServices() { public void beforeExternalServices() {
checkState( checkState(
state == Lifecycle.REGISTERED, state == Lifecycle.REGISTERED,
@ -158,6 +181,7 @@ public class BesuPluginContextImpl implements BesuContext, PluginVersionsProvide
state = Lifecycle.BEFORE_EXTERNAL_SERVICES_FINISHED; state = Lifecycle.BEFORE_EXTERNAL_SERVICES_FINISHED;
} }
/** Start plugins. */
public void startPlugins() { public void startPlugins() {
checkState( checkState(
state == Lifecycle.BEFORE_EXTERNAL_SERVICES_FINISHED, state == Lifecycle.BEFORE_EXTERNAL_SERVICES_FINISHED,
@ -187,6 +211,7 @@ public class BesuPluginContextImpl implements BesuContext, PluginVersionsProvide
state = Lifecycle.BEFORE_MAIN_LOOP_FINISHED; state = Lifecycle.BEFORE_MAIN_LOOP_FINISHED;
} }
/** Stop plugins. */
public void stopPlugins() { public void stopPlugins() {
checkState( checkState(
state == Lifecycle.BEFORE_MAIN_LOOP_FINISHED, state == Lifecycle.BEFORE_MAIN_LOOP_FINISHED,
@ -221,6 +246,11 @@ public class BesuPluginContextImpl implements BesuContext, PluginVersionsProvide
} }
} }
/**
* Gets plugins.
*
* @return the plugins
*/
@VisibleForTesting @VisibleForTesting
List<BesuPlugin> getPlugins() { List<BesuPlugin> getPlugins() {
return Collections.unmodifiableList(plugins); return Collections.unmodifiableList(plugins);
@ -249,6 +279,11 @@ public class BesuPluginContextImpl implements BesuContext, PluginVersionsProvide
return Optional.empty(); return Optional.empty();
} }
/**
* Gets named plugins.
*
* @return the named plugins
*/
public Map<String, BesuPlugin> getNamedPlugins() { public Map<String, BesuPlugin> getNamedPlugins() {
return plugins.stream() return plugins.stream()
.filter(plugin -> plugin.getName().isPresent()) .filter(plugin -> plugin.getName().isPresent())

@ -23,6 +23,7 @@ import java.util.List;
import com.google.common.collect.Lists; import com.google.common.collect.Lists;
/** The Permissioning service implementation. */
public class PermissioningServiceImpl implements PermissioningService { public class PermissioningServiceImpl implements PermissioningService {
private final List<NodeConnectionPermissioningProvider> connectionPermissioningProviders = private final List<NodeConnectionPermissioningProvider> connectionPermissioningProviders =
@ -34,6 +35,11 @@ public class PermissioningServiceImpl implements PermissioningService {
connectionPermissioningProviders.add(provider); connectionPermissioningProviders.add(provider);
} }
/**
* Gets connection permissioning providers.
*
* @return the connection permissioning providers
*/
public List<NodeConnectionPermissioningProvider> getConnectionPermissioningProviders() { public List<NodeConnectionPermissioningProvider> getConnectionPermissioningProviders() {
return connectionPermissioningProviders; return connectionPermissioningProviders;
} }
@ -47,6 +53,11 @@ public class PermissioningServiceImpl implements PermissioningService {
messagePermissioningProviders.add(provider); messagePermissioningProviders.add(provider);
} }
/**
* Gets message permissioning providers.
*
* @return the message permissioning providers
*/
public List<NodeMessagePermissioningProvider> getMessagePermissioningProviders() { public List<NodeMessagePermissioningProvider> getMessagePermissioningProviders() {
return messagePermissioningProviders; return messagePermissioningProviders;
} }

@ -22,12 +22,18 @@ import picocli.CommandLine;
import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Model.OptionSpec; import picocli.CommandLine.Model.OptionSpec;
/** The Pico cli options service implementation to specify plugins. */
public class PicoCLIOptionsImpl implements PicoCLIOptions { public class PicoCLIOptionsImpl implements PicoCLIOptions {
private static final Logger LOG = LoggerFactory.getLogger(PicoCLIOptionsImpl.class); private static final Logger LOG = LoggerFactory.getLogger(PicoCLIOptionsImpl.class);
private final CommandLine commandLine; private final CommandLine commandLine;
/**
* Instantiates a new Pico cli options.
*
* @param commandLine the command line
*/
public PicoCLIOptionsImpl(final CommandLine commandLine) { public PicoCLIOptionsImpl(final CommandLine commandLine) {
this.commandLine = commandLine; this.commandLine = commandLine;
} }

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

Loading…
Cancel
Save