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. 16
      .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. 24
      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
command: |
./gradlew --no-daemon integrationTest
- run:
name: Javadoc
command: |
./gradlew --no-daemon javadoc
- run:
name: CompileJmh
command: |

@ -19,4 +19,18 @@ jobs:
java-version: 11
cache: gradle
- 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 picocli.CommandLine.RunLast;
/** Besu bootstrap class. */
public final class Besu {
/**
* The main entrypoint to Besu application
*
* @param args command line arguments.
*/
public static void main(final String... args) {
final Logger logger = setupLogging();

@ -18,6 +18,10 @@ import org.hyperledger.besu.util.platform.PlatformDetector;
import java.util.Optional;
/**
* Represent Besu information such as version, OS etc. Used with --version option and during Besu
* start.
*/
public final class BesuInfo {
private static final String CLIENT = "besu";
private static final String VERSION = BesuInfo.class.getPackage().getImplementationVersion();
@ -26,10 +30,21 @@ public final class 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() {
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) {
return maybeIdentity
.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.LoggerFactory;
/** The Runner controls various Besu services lifecycle. */
public class Runner implements AutoCloseable {
private static final Logger LOG = LoggerFactory.getLogger(Runner.class);
@ -77,6 +78,26 @@ public class Runner implements AutoCloseable {
private final Optional<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(
final Vertx vertx,
final NetworkRunner networkRunner,
@ -115,6 +136,7 @@ public class Runner implements AutoCloseable {
new TransactionPoolEvictionService(vertx, besuController.getTransactionPool());
}
/** Start external services. */
public void startExternalServices() {
LOG.info("Starting external services ... ");
metrics.ifPresent(service -> waitForServiceToStart("metrics", service.start()));
@ -132,6 +154,7 @@ public class Runner implements AutoCloseable {
ethStatsService.ifPresent(EthStatsService::start);
}
/** Start ethereum main loop. */
public void startEthereumMainLoop() {
try {
LOG.info("Starting Ethereum main loop ... ");
@ -154,6 +177,7 @@ public class Runner implements AutoCloseable {
}
}
/** Stop services. */
public void stop() {
transactionPoolEvictionService.stop();
jsonRpc.ifPresent(service -> waitForServiceToStop("jsonRpc", service.stop()));
@ -184,6 +208,7 @@ public class Runner implements AutoCloseable {
shutdown.countDown();
}
/** Await stop. */
public void awaitStop() {
try {
shutdown.await();
@ -328,22 +353,47 @@ public class Runner implements AutoCloseable {
});
}
/**
* Gets json rpc port.
*
* @return the json rpc port
*/
public Optional<Integer> getJsonRpcPort() {
return jsonRpc.map(service -> service.socketAddress().getPort());
}
/**
* Gets engine json rpc port.
*
* @return the engine json rpc port
*/
public Optional<Integer> getEngineJsonRpcPort() {
return engineJsonRpc.map(service -> service.socketAddress().getPort());
}
/**
* Gets GraphQl http port.
*
* @return the graph ql http port
*/
public Optional<Integer> getGraphQLHttpPort() {
return graphQLHttp.map(service -> service.socketAddress().getPort());
}
/**
* Gets web socket port.
*
* @return the web socket port
*/
public Optional<Integer> getWebSocketPort() {
return webSocketRpc.map(service -> service.socketAddress().getPort());
}
/**
* Gets metrics port.
*
* @return the metrics port
*/
public Optional<Integer> getMetricsPort() {
if (metrics.isPresent()) {
return metrics.get().getPort();
@ -352,6 +402,11 @@ public class Runner implements AutoCloseable {
}
}
/**
* Gets local enode.
*
* @return the local enode
*/
@VisibleForTesting
Optional<EnodeURL> getLocalEnode() {
return networkRunner.getNetwork().getLocalEnode();
@ -359,6 +414,11 @@ public class Runner implements AutoCloseable {
@FunctionalInterface
private interface SynchronousShutdown {
/**
* Await for shutdown.
*
* @throws InterruptedException the interrupted exception
*/
void await() throws InterruptedException;
}

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

@ -33,6 +33,11 @@ public abstract class BlockExporter {
private static final Logger LOG = LoggerFactory.getLogger(BlockExporter.class);
private final Blockchain blockchain;
/**
* Instantiates a new Block exporter.
*
* @param blockchain the blockchain
*/
protected BlockExporter(final Blockchain blockchain) {
this.blockchain = blockchain;
}
@ -90,6 +95,13 @@ public abstract class BlockExporter {
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)
throws IOException;
}

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

@ -52,6 +52,11 @@ public class JsonBlockImporter {
private final ObjectMapper mapper;
private final BesuController controller;
/**
* Instantiates a new Json block importer.
*
* @param controller the controller
*/
public JsonBlockImporter(final BesuController controller) {
this.controller = controller;
mapper = new ObjectMapper();
@ -61,6 +66,12 @@ public class JsonBlockImporter {
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 {
warnIfDatabaseIsNotEmpty();

@ -80,6 +80,17 @@ public class RlpBlockImporter implements Closeable {
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(
final Path blocks,
final BesuController besuController,
@ -279,12 +290,21 @@ public class RlpBlockImporter implements Closeable {
}
}
/** The Import result. */
public static final class ImportResult {
/** The difficulty. */
public final Difficulty td;
/** The Count. */
final int count;
/**
* Instantiates a new Import result.
*
* @param td the td
* @param count the count
*/
ImportResult(final Difficulty td, final int count) {
this.td = td;
this.count = count;

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

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

@ -33,6 +33,7 @@ import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256;
/** The Transaction data. */
@JsonIgnoreProperties("comment")
public class TransactionData {
@ -46,6 +47,16 @@ public class TransactionData {
private static final Supplier<SignatureAlgorithm> SIGNATURE_ALGORITHM =
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
public TransactionData(
@JsonProperty("gasLimit") final String gasLimit,
@ -62,6 +73,12 @@ public class TransactionData {
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) {
final KeyPair keyPair = SIGNATURE_ALGORITHM.get().createKeyPair(privateKey);
@ -78,8 +95,15 @@ public class TransactionData {
.signAndBuild(keyPair);
}
/** The interface Nonce provider. */
@FunctionalInterface
public interface NonceProvider {
/**
* Get Nonce.
*
* @param address the address
* @return the Nonce
*/
long get(final Address address);
}
}

@ -252,6 +252,7 @@ import picocli.CommandLine.Mixin;
import picocli.CommandLine.Option;
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
@Command(
description = "This command runs the Besu Ethereum client full node.",
@ -1319,8 +1320,21 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
private Vertx vertx;
private EnodeDnsConfiguration enodeDnsConfiguration;
private KeyValueStorageProvider keyValueStorageProvider;
/** Sets GoQuorum compatibility mode. */
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(
final Logger logger,
final Supplier<RlpBlockImporter> rlpBlockImporter,
@ -1347,6 +1361,24 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
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
protected BesuCommand(
final Logger logger,
@ -1381,6 +1413,17 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
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(
final IExecutionStrategy resultHandler,
final BesuParameterExceptionHandler parameterExceptionHandler,
@ -1581,6 +1624,13 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
}
// 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) {
return KeyPairUtil.loadKeyPair(resolveNodePrivateKeyFile(nodePrivateKeyFile));
}
@ -1722,6 +1772,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
.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) {
// To change the configuration if color was enabled/disabled
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() {
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) {
final String failMessage = "The provided --p2p-interface is not available: " + p2pInterface;
try {
@ -1890,7 +1955,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
}
}
public void validateRpcOptionsParams() {
private void validateRpcOptionsParams() {
final Predicate<String> configuredApis =
apiName ->
Arrays.stream(RpcApis.values())
@ -1936,7 +2001,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
}
}
public void validateChainDataPruningParams() {
private void validateChainDataPruningParams() {
if (unstableChainPruningOptions.getChainDataPruningEnabled()
&& unstableChainPruningOptions.getChainDataPruningBlocksRetained()
< ChainPruningOptions.DEFAULT_CHAIN_DATA_PRUNING_MIN_BLOCKS_RETAINED) {
@ -2156,6 +2221,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
besuController = buildController();
}
/**
* Builds BesuController
*
* @return instance of BesuController
*/
public BesuController buildController() {
try {
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() {
final KeyValueStorageProvider storageProvider = keyValueStorageProvider(keyValueStorageName);
return controllerBuilderFactory
@ -2517,6 +2592,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
.build();
}
/**
* Metrics Configuration for Besu
*
* @return instance of MetricsConfiguration.
*/
public MetricsConfiguration metricsConfiguration() {
if (metricsOptionGroup.isMetricsEnabled && metricsOptionGroup.isMetricsPushEnabled) {
throw new ParameterException(
@ -2798,7 +2878,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
return privacyParameters;
}
public WorldStateArchive createPrivateWorldStateArchive(final StorageProvider storageProvider) {
private WorldStateArchive createPrivateWorldStateArchive(final StorageProvider storageProvider) {
final WorldStateStorage privateWorldStateStorage =
storageProvider.createPrivateWorldStateStorage();
final WorldStatePreimageStorage preimageStorage =
@ -2956,6 +3036,13 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
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) {
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() {
return dataPath.toAbsolutePath();
}
@ -3132,6 +3223,11 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
+ DefaultCommandValues.PERMISSIONING_CONFIG_LOCATION;
}
/**
* Metrics System used by Besu
*
* @return Instance of MetricsSystem
*/
public MetricsSystem getMetricsSystem() {
return metricsSystem.get();
}
@ -3160,14 +3256,31 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
.collect(Collectors.toList());
}
/**
* Besu CLI Paramaters exception handler used by VertX. Visible for testing.
*
* @return instance of BesuParameterExceptionHandler
*/
@VisibleForTesting
public BesuParameterExceptionHandler parameterExceptionHandler() {
return new BesuParameterExceptionHandler(this::getLogLevel);
}
/**
* Returns BesuExecutionExceptionHandler. Visible as it is used in testing.
*
* @return instance of BesuExecutionExceptionHandler used by Vertx.
*/
public BesuExecutionExceptionHandler executionExceptionHandler() {
return new BesuExecutionExceptionHandler();
}
/**
* Represents Enode DNS Configuration. Visible for testing.
*
* @return instance of EnodeDnsConfiguration
*/
@VisibleForTesting
public EnodeDnsConfiguration getEnodeDnsConfiguration() {
if (enodeDnsConfiguration == null) {
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() {
final List<Integer> unavailablePorts = new ArrayList<>();
getEffectivePorts().stream()
@ -3343,6 +3461,8 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
return genesisConfigOptions.getEcCurve();
}
/** Enables Go Quorum Compatibility mode. Visible for testing. */
@VisibleForTesting
protected void enableGoQuorumCompatibilityMode() {
// this static flag is read by the RLP decoder
GoQuorumOptions.setGoQuorumCompatibilityMode(true);
@ -3415,7 +3535,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
return engineRPCOptionGroup.overrideEngineRpcEnabled || isMergeEnabled();
}
public static List<String> getJDKEnabledCipherSuites() {
private static List<String> getJDKEnabledCipherSuites() {
try {
final SSLContext context = SSLContext.getInstance("TLS");
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 {
final SSLContext context = SSLContext.getInstance("TLS");
context.init(null, null, null);

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

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

@ -19,8 +19,15 @@ import org.hyperledger.besu.util.log.FramedLogMessage;
import java.util.List;
/** The Network deprecation message. */
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) {
if (network.getDeprecationDate().isEmpty()) {
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.stream.Collectors;
/** The Eth network config. */
public class EthNetworkConfig {
private final String genesisConfig;
@ -37,6 +38,14 @@ public class EthNetworkConfig {
private final List<EnodeURL> bootNodes;
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(
final String genesisConfig,
final BigInteger networkId,
@ -50,18 +59,38 @@ public class EthNetworkConfig {
this.dnsDiscoveryUrl = dnsDiscoveryUrl;
}
/**
* Gets genesis config.
*
* @return the genesis config
*/
public String getGenesisConfig() {
return genesisConfig;
}
/**
* Gets network id.
*
* @return the network id
*/
public BigInteger getNetworkId() {
return networkId;
}
/**
* Gets boot nodes.
*
* @return the boot nodes
*/
public List<EnodeURL> getBootNodes() {
return bootNodes;
}
/**
* Gets dns discovery url.
*
* @return the dns discovery url
*/
public String getDnsDiscoveryUrl() {
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) {
final String genesisContent = jsonConfig(networkName.getGenesisFile());
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) {
return jsonConfig(network.getGenesisFile());
}
/** The type Builder. */
public static class Builder {
private String dnsDiscoveryUrl;
@ -139,6 +181,11 @@ public class EthNetworkConfig {
private BigInteger networkId;
private List<EnodeURL> bootNodes;
/**
* Instantiates a new Builder.
*
* @param ethNetworkConfig the eth network config
*/
public Builder(final EthNetworkConfig ethNetworkConfig) {
this.genesisConfig = ethNetworkConfig.genesisConfig;
this.networkId = ethNetworkConfig.networkId;
@ -146,26 +193,55 @@ public class EthNetworkConfig {
this.dnsDiscoveryUrl = ethNetworkConfig.dnsDiscoveryUrl;
}
/**
* Sets genesis config.
*
* @param genesisConfig the genesis config
* @return the genesis config
*/
public Builder setGenesisConfig(final String genesisConfig) {
this.genesisConfig = genesisConfig;
return this;
}
/**
* Sets network id.
*
* @param networkId the network id
* @return the network id
*/
public Builder setNetworkId(final BigInteger networkId) {
this.networkId = networkId;
return this;
}
/**
* Sets boot nodes.
*
* @param bootNodes the boot nodes
* @return the boot nodes
*/
public Builder setBootNodes(final List<EnodeURL> bootNodes) {
this.bootNodes = bootNodes;
return this;
}
/**
* Sets dns discovery url.
*
* @param dnsDiscoveryUrl the dns discovery url
* @return the dns discovery url
*/
public Builder setDnsDiscoveryUrl(final String dnsDiscoveryUrl) {
this.dnsDiscoveryUrl = dnsDiscoveryUrl;
return this;
}
/**
* Build eth network config.
*
* @return the eth network config
*/
public EthNetworkConfig build() {
return new EthNetworkConfig(genesisConfig, networkId, bootNodes, dnsDiscoveryUrl);
}

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

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

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

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

@ -16,8 +16,14 @@ package org.hyperledger.besu.cli.converter.exception;
import static java.lang.String.format;
/** The custom Fraction conversion exception. */
public final class FractionConversionException extends Exception {
/**
* Instantiates a new Fraction conversion exception.
*
* @param value the value
*/
public FractionConversionException(final String 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;
/** The custom Percentage conversion 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) {
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;
/** The custom Rpc Apis conversion 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) {
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.Strings;
/** The Cors allowed origins property used in CLI */
public class CorsAllowedOriginsProperty extends AbstractList<String> {
private final List<String> domains = new ArrayList<>();
/** Instantiates a new Cors allowed origins property. */
public CorsAllowedOriginsProperty() {}
@Override

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

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

@ -27,8 +27,17 @@ import org.apache.tuweni.toml.TomlParseResult;
import picocli.CommandLine;
import picocli.CommandLine.ParameterException;
/** The Rpc authentication file validator. */
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(
final CommandLine commandLine, final String filename, final String type) {

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

@ -21,10 +21,16 @@ import org.apache.logging.log4j.Level;
import picocli.CommandLine;
import picocli.CommandLine.Model.CommandSpec;
/** The custom parameter exception handler for Besu PicoCLI. */
public class BesuParameterExceptionHandler implements CommandLine.IParameterExceptionHandler {
private final Supplier<Level> levelSupplier;
/**
* Instantiates a new Besu parameter exception handler.
*
* @param levelSupplier the logging level supplier
*/
public BesuParameterExceptionHandler(final Supplier<Level> 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.ConfigurationSource;
/** Custom Log4J Configuration Factory for Besu */
public class BesuLoggingConfigurationFactory extends ConfigurationFactory {
@Override

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

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

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

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

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

@ -20,8 +20,14 @@ import java.io.File;
import picocli.CommandLine;
/** The Node private key file Cli option. */
public class NodePrivateKeyFileOption {
/**
* Create node private key file option.
*
* @return the node private key file option
*/
public static NodePrivateKeyFileOption create() {
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)")
private final File nodePrivateKeyFile = null;
/**
* Gets node private key file.
*
* @return the node private key file
*/
public File getNodePrivateKeyFile() {
return nodePrivateKeyFile;
}

@ -30,6 +30,7 @@ import picocli.CommandLine;
import picocli.CommandLine.Option;
import picocli.CommandLine.ParameterException;
/** The P2P TLS Config Cli Options. */
public class P2PTLSConfigOptions {
@Option(
names = {"--Xp2p-tls-enabled"},
@ -95,6 +96,12 @@ public class P2PTLSConfigOptions {
description = "Certificate revocation list for the P2P service.")
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) {
if (!p2pTLSEnabled) {
return Optional.empty();
@ -128,6 +135,12 @@ public class P2PTLSConfigOptions {
.build());
}
/**
* Check P2P Tls options dependencies.
*
* @param logger the logger
* @param commandLine the command line
*/
public void checkP2PTLSOptionsDependencies(final Logger logger, final CommandLine commandLine) {
CommandLineUtils.checkOptionDependencies(
logger,

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

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

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

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

@ -21,13 +21,25 @@ import java.util.List;
import picocli.CommandLine;
/** The Ipc CLI options. */
public class IpcOptions {
private static final String DEFAULT_IPC_FILE = "besu.ipc";
/**
* Create ipc options.
*
* @return the ipc options
*/
public static IpcOptions create() {
return new IpcOptions();
}
/**
* Gets default path.
*
* @param dataDir the data dir
* @return the default path
*/
public static Path getDefaultPath(final Path dataDir) {
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})")
private final List<String> rpcIpcApis = DEFAULT_RPC_APIS;
/**
* Whether IPC options are enabled.
*
* @return true for enabled, false otherwise.
*/
public Boolean isEnabled() {
return enabled;
}
/**
* Gets ipc path.
*
* @return the ipc path
*/
public Path getIpcPath() {
return ipcPath;
}
/**
* Gets rpc ipc apis.
*
* @return the rpc ipc apis
*/
public List<String> getRpcIpcApis() {
return rpcIpcApis;
}

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

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

@ -22,6 +22,7 @@ import static org.hyperledger.besu.ethereum.core.MiningParameters.DEFAULT_REMOTE
import picocli.CommandLine;
/** The Mining CLI options. */
public class MiningOptions {
@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)")
private final Long posBlockCreationMaxTime = DEFAULT_POS_BLOCK_CREATION_MAX_TIME;
/**
* Create mining options.
*
* @return the mining options
*/
public static MiningOptions create() {
return new MiningOptions();
}
/**
* Gets remote sealers limit.
*
* @return the remote sealers limit
*/
public Integer getRemoteSealersLimit() {
return remoteSealersLimit;
}
/**
* Gets remote sealers time to live.
*
* @return the remote sealers time to live
*/
public Long getRemoteSealersTimeToLive() {
return remoteSealersTimeToLive;
}
/**
* Gets stratum extra nonce.
*
* @return the stratum extra nonce
*/
public String getStratumExtranonce() {
return stratumExtranonce;
}
/**
* Gets pow job time to live.
*
* @return the pow job time to live
*/
public Long getPowJobTimeToLive() {
return powJobTimeToLive;
}
/**
* Gets max ommers depth.
*
* @return the max ommers depth
*/
public int getMaxOmmersDepth() {
return maxOmmersDepth;
}
/**
* Gets pos block creation max time.
*
* @return the pos block creation max time
*/
public Long getPosBlockCreationMaxTime() {
return posBlockCreationMaxTime;
}

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

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

@ -25,6 +25,7 @@ import java.util.Optional;
import picocli.CommandLine;
/** The Networking Cli options. */
public class NetworkingOptions implements CLIOptions<NetworkingConfiguration> {
private final String INITIATE_CONNECTIONS_FREQUENCY_FLAG =
"--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 DISCOVERY_PROTOCOL_V5_ENABLED = "--Xv5-discovery-enabled";
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";
@CommandLine.Option(
@ -85,10 +87,21 @@ public class NetworkingOptions implements CLIOptions<NetworkingConfiguration> {
private NetworkingOptions() {}
/**
* Create networking options.
*
* @return the networking options
*/
public static NetworkingOptions create() {
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) {
final NetworkingOptions cliOptions = new NetworkingOptions();
cliOptions.checkMaintainedConnectionsFrequencySec =

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

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

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

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

@ -31,6 +31,7 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import picocli.CommandLine;
/** The Transaction pool Cli options. */
public class TransactionPoolOptions
implements CLIOptions<ImmutableTransactionPoolConfiguration.Builder> {
private static final Logger LOG = LoggerFactory.getLogger(Besu.class);
@ -95,10 +96,21 @@ public class TransactionPoolOptions
private TransactionPoolOptions() {}
/**
* Create transaction pool options.
*
* @return the transaction pool options
*/
public static TransactionPoolOptions create() {
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) {
final TransactionPoolOptions options = TransactionPoolOptions.create();
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
* BesuCommand} is ready and before {@link Runner#startEthereumMainLoop()} is called
* BesuCommand}* is ready and before {@link Runner#startEthereumMainLoop()} is called
*/
public interface PreSynchronizationTask {
/**
* Run.
*
* @param besuController the besu controller
*/
void run(final BesuController besuController);
}

@ -19,14 +19,25 @@ import org.hyperledger.besu.controller.BesuController;
import java.util.ArrayList;
import java.util.List;
/** The Pre synchronization task runner. */
public class PreSynchronizationTaskRunner {
private final List<PreSynchronizationTask> tasks = new ArrayList<>();
/**
* Add task.
*
* @param task the task
*/
public void addTask(final PreSynchronizationTask task) {
tasks.add(task);
}
/**
* Run tasks.
*
* @param besuController the besu controller
*/
public void runTasks(final BesuController 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.util.PrivateStorageMigrationBuilder;
/** The Private database migration pre sync task. */
public class PrivateDatabaseMigrationPreSyncTask implements PreSynchronizationTask {
private final PrivacyParameters privacyParameters;
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(
final PrivacyParameters privacyParameters, final boolean migratePrivateDatabaseFlag) {
this.privacyParameters = privacyParameters;

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

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

@ -36,6 +36,7 @@ import picocli.CommandLine.Command;
import picocli.CommandLine.Mixin;
import picocli.CommandLine.Option;
/** Subcommand to run a Retesteth compatible server for reference tests. */
@Command(
name = COMMAND_NAME,
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);
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "retesteth";
/**

@ -30,6 +30,7 @@ import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.ParentCommand;
/** The Besu configuration Validate sub command. */
@Command(
name = COMMAND_NAME,
description = "This command provides basic Besu config validation (syntax only).",
@ -37,6 +38,7 @@ import picocli.CommandLine.ParentCommand;
versionProvider = VersionProvider.class)
public class ValidateConfigSubCommand implements Runnable {
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "validate-config";
@Option(
@ -49,9 +51,15 @@ public class ValidateConfigSubCommand implements Runnable {
@ParentCommand
private BesuCommand parentCommand;
final PrintWriter out;
final CommandLine commandLine;
private final PrintWriter out;
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) {
this.out = out;
this.commandLine = commandLine;

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

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

@ -80,6 +80,7 @@ public class BlocksSubCommand implements Runnable {
private static final Logger LOG = LoggerFactory.getLogger(BlocksSubCommand.class);
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "blocks";
@SuppressWarnings("unused")
@ -96,6 +97,14 @@ public class BlocksSubCommand implements Runnable {
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(
final Supplier<RlpBlockImporter> rlpBlockImporter,
final Function<BesuController, JsonBlockImporter> jsonBlockImporterFactory,

@ -39,6 +39,7 @@ import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.ParentCommand;
/** Subcommand that performs back up of state and accounts at a specified block */
@Command(
name = "x-backup-state",
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.ParentCommand;
/** The generate-log-bloom-cache CLI command. */
@Command(
name = "generate-log-bloom-cache",
description = "Generate cached values of block log bloom filters.",

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

@ -56,6 +56,7 @@ import picocli.CommandLine.Command;
import picocli.CommandLine.Option;
import picocli.CommandLine.ParentCommand;
/** The Restore state subcommand. */
@Command(
name = "x-restore-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.Spec;
/** The RLP sub command. */
@Command(
name = RLPSubCommand.COMMAND_NAME,
description = "This command provides RLP data related actions.",
@ -50,6 +51,7 @@ import picocli.CommandLine.Spec;
subcommands = {EncodeSubCommand.class})
public class RLPSubCommand implements Runnable {
/** The constant COMMAND_NAME. */
public static final String COMMAND_NAME = "rlp";
private final PrintWriter out;
@ -63,6 +65,12 @@ public class RLPSubCommand implements Runnable {
@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) {
this.out = out;
this.in = in;

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

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

@ -21,10 +21,19 @@ import java.util.List;
import picocli.CommandLine.IDefaultValueProvider;
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 {
private final List<IDefaultValueProvider> defaultValueProviders;
/**
* Instantiates a new Cascading default provider.
*
* @param defaultValueProviders List of default value providers
*/
public CascadingDefaultProvider(final IDefaultValueProvider... defaultValueProviders) {
this.defaultValueProviders = asList(defaultValueProviders);
}

@ -24,12 +24,17 @@ import com.google.common.base.Strings;
import org.slf4j.Logger;
import picocli.CommandLine;
/** The Command line utils. */
public class CommandLineUtils {
/** The constant DEPENDENCY_WARNING_MSG. */
public static final String DEPENDENCY_WARNING_MSG =
"{} 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 =
"{} ignored because none of {} was defined.";
/** The constant DEPRECATION_WARNING_MSG. */
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 =
"{} 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(
final CommandLine commandLine,
final String errorMessage,

@ -29,11 +29,19 @@ import picocli.CommandLine.Model.OptionSpec;
import picocli.CommandLine.ParameterException;
import picocli.CommandLine.ParseResult;
/** Custom Config option search and run handler. */
public class ConfigOptionSearchAndRunHandler extends CommandLine.RunLast {
private final IExecutionStrategy resultHandler;
private final IParameterExceptionHandler parameterExceptionHandler;
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(
final IExecutionStrategy resultHandler,
final IParameterExceptionHandler parameterExceptionHandler,
@ -98,6 +106,13 @@ public class ConfigOptionSearchAndRunHandler extends CommandLine.RunLast {
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
IDefaultValueProvider createDefaultValueProvider(
final CommandLine commandLine, final Optional<File> configFile) {

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

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

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

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

@ -107,178 +107,358 @@ import java.util.function.Supplier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** The Besu controller builder that builds Besu Controller. */
public abstract class BesuControllerBuilder implements MiningParameterOverrides {
private static final Logger LOG = LoggerFactory.getLogger(BesuControllerBuilder.class);
private GenesisConfigFile genesisConfig;
private Map<String, String> genesisConfigOverrides = Collections.emptyMap();
/** The Config options supplier. */
protected Supplier<GenesisConfigOptions> configOptionsSupplier =
() ->
Optional.ofNullable(genesisConfig)
.map(conf -> conf.getConfigOptions(genesisConfigOverrides))
.orElseGet(genesisConfig::getConfigOptions);
/** The Sync config. */
protected SynchronizerConfiguration syncConfig;
/** The Ethereum wire protocol configuration. */
protected EthProtocolConfiguration ethereumWireProtocolConfiguration;
/** The Transaction pool configuration. */
protected TransactionPoolConfiguration transactionPoolConfiguration;
/** The Network id. */
protected BigInteger networkId;
/** The Mining parameters. */
protected MiningParameters miningParameters;
/** The Metrics system. */
protected ObservableMetricsSystem metricsSystem;
/** The Privacy parameters. */
protected PrivacyParameters privacyParameters;
/** The Pki block creation configuration. */
protected Optional<PkiBlockCreationConfiguration> pkiBlockCreationConfiguration =
Optional.empty();
/** The Data directory. */
protected Path dataDirectory;
/** The Clock. */
protected Clock clock;
/** The Node key. */
protected NodeKey nodeKey;
/** The Is revert reason enabled. */
protected boolean isRevertReasonEnabled;
/** The Gas limit calculator. */
GasLimitCalculator gasLimitCalculator;
/** The Storage provider. */
protected StorageProvider storageProvider;
/** The Is pruning enabled. */
protected boolean isPruningEnabled;
/** The Pruner configuration. */
protected PrunerConfiguration prunerConfiguration;
/** The Required blocks. */
protected Map<Long, Hash> requiredBlocks = Collections.emptyMap();
/** The Reorg logging threshold. */
protected long reorgLoggingThreshold;
/** The Data storage configuration. */
protected DataStorageConfiguration dataStorageConfiguration =
DataStorageConfiguration.DEFAULT_CONFIG;
/** The Message permissioning providers. */
protected List<NodeMessagePermissioningProvider> messagePermissioningProviders =
Collections.emptyList();
/** The Evm configuration. */
protected EvmConfiguration evmConfiguration;
/** The Max peers. */
protected int maxPeers;
/** The Chain pruner configuration. */
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) {
this.storageProvider = storageProvider;
return this;
}
/**
* Genesis config file besu controller builder.
*
* @param genesisConfig the genesis config
* @return the besu controller builder
*/
public BesuControllerBuilder genesisConfigFile(final GenesisConfigFile genesisConfig) {
this.genesisConfig = genesisConfig;
return this;
}
/**
* Synchronizer configuration besu controller builder.
*
* @param synchronizerConfig the synchronizer config
* @return the besu controller builder
*/
public BesuControllerBuilder synchronizerConfiguration(
final SynchronizerConfiguration synchronizerConfig) {
this.syncConfig = synchronizerConfig;
return this;
}
/**
* Eth protocol configuration besu controller builder.
*
* @param ethProtocolConfiguration the eth protocol configuration
* @return the besu controller builder
*/
public BesuControllerBuilder ethProtocolConfiguration(
final EthProtocolConfiguration ethProtocolConfiguration) {
this.ethereumWireProtocolConfiguration = ethProtocolConfiguration;
return this;
}
/**
* Network id besu controller builder.
*
* @param networkId the network id
* @return the besu controller builder
*/
public BesuControllerBuilder networkId(final BigInteger networkId) {
this.networkId = networkId;
return this;
}
/**
* Mining parameters besu controller builder.
*
* @param miningParameters the mining parameters
* @return the besu controller builder
*/
public BesuControllerBuilder miningParameters(final MiningParameters miningParameters) {
this.miningParameters = miningParameters;
return this;
}
/**
* Message permissioning providers besu controller builder.
*
* @param messagePermissioningProviders the message permissioning providers
* @return the besu controller builder
*/
public BesuControllerBuilder messagePermissioningProviders(
final List<NodeMessagePermissioningProvider> messagePermissioningProviders) {
this.messagePermissioningProviders = messagePermissioningProviders;
return this;
}
/**
* Node key besu controller builder.
*
* @param nodeKey the node key
* @return the besu controller builder
*/
public BesuControllerBuilder nodeKey(final NodeKey nodeKey) {
this.nodeKey = nodeKey;
return this;
}
/**
* Metrics system besu controller builder.
*
* @param metricsSystem the metrics system
* @return the besu controller builder
*/
public BesuControllerBuilder metricsSystem(final ObservableMetricsSystem metricsSystem) {
this.metricsSystem = metricsSystem;
return this;
}
/**
* Privacy parameters besu controller builder.
*
* @param privacyParameters the privacy parameters
* @return the besu controller builder
*/
public BesuControllerBuilder privacyParameters(final PrivacyParameters privacyParameters) {
this.privacyParameters = privacyParameters;
return this;
}
/**
* Pki block creation configuration besu controller builder.
*
* @param pkiBlockCreationConfiguration the pki block creation configuration
* @return the besu controller builder
*/
public BesuControllerBuilder pkiBlockCreationConfiguration(
final Optional<PkiBlockCreationConfiguration> pkiBlockCreationConfiguration) {
this.pkiBlockCreationConfiguration = pkiBlockCreationConfiguration;
return this;
}
/**
* Data directory besu controller builder.
*
* @param dataDirectory the data directory
* @return the besu controller builder
*/
public BesuControllerBuilder dataDirectory(final Path dataDirectory) {
this.dataDirectory = dataDirectory;
return this;
}
/**
* Clock besu controller builder.
*
* @param clock the clock
* @return the besu controller builder
*/
public BesuControllerBuilder clock(final Clock clock) {
this.clock = clock;
return this;
}
/**
* Transaction pool configuration besu controller builder.
*
* @param transactionPoolConfiguration the transaction pool configuration
* @return the besu controller builder
*/
public BesuControllerBuilder transactionPoolConfiguration(
final TransactionPoolConfiguration transactionPoolConfiguration) {
this.transactionPoolConfiguration = transactionPoolConfiguration;
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) {
this.isRevertReasonEnabled = isRevertReasonEnabled;
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) {
this.isPruningEnabled = isPruningEnabled;
return this;
}
/**
* Pruning configuration besu controller builder.
*
* @param prunerConfiguration the pruner configuration
* @return the besu controller builder
*/
public BesuControllerBuilder pruningConfiguration(final PrunerConfiguration prunerConfiguration) {
this.prunerConfiguration = prunerConfiguration;
return this;
}
/**
* Genesis config overrides besu controller builder.
*
* @param genesisConfigOverrides the genesis config overrides
* @return the besu controller builder
*/
public BesuControllerBuilder genesisConfigOverrides(
final Map<String, String> genesisConfigOverrides) {
this.genesisConfigOverrides = genesisConfigOverrides;
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) {
this.gasLimitCalculator = gasLimitCalculator;
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) {
this.requiredBlocks = requiredBlocks;
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) {
this.reorgLoggingThreshold = reorgLoggingThreshold;
return this;
}
/**
* Data storage configuration besu controller builder.
*
* @param dataStorageConfiguration the data storage configuration
* @return the besu controller builder
*/
public BesuControllerBuilder dataStorageConfiguration(
final DataStorageConfiguration dataStorageConfiguration) {
this.dataStorageConfiguration = dataStorageConfiguration;
return this;
}
/**
* Evm configuration besu controller builder.
*
* @param evmConfiguration the evm configuration
* @return the besu controller builder
*/
public BesuControllerBuilder evmConfiguration(final EvmConfiguration evmConfiguration) {
this.evmConfiguration = evmConfiguration;
return this;
}
/**
* Max peers besu controller builder.
*
* @param maxPeers the max peers
* @return the besu controller builder
*/
public BesuControllerBuilder maxPeers(final int maxPeers) {
this.maxPeers = maxPeers;
return this;
}
/**
* Chain pruning configuration besu controller builder.
*
* @param chainPrunerConfiguration the chain pruner configuration
* @return the besu controller builder
*/
public BesuControllerBuilder chainPruningConfiguration(
final ChainPrunerConfiguration chainPrunerConfiguration) {
this.chainPrunerConfiguration = chainPrunerConfiguration;
return this;
}
/**
* Build besu controller.
*
* @return the besu controller
*/
public BesuController build() {
checkNotNull(genesisConfig, "Missing genesis config");
checkNotNull(syncConfig, "Missing sync config");
@ -495,6 +675,19 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
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(
final ProtocolSchedule protocolSchedule,
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) {
return configOptionsSupplier
.get()
@ -572,13 +771,27 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
.orElse(SyncTerminationCondition.never());
}
/** Prep for build. */
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(
final ProtocolContext protocolContext) {
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(
final EthProtocolManager ethProtocolManager,
final Optional<SnapProtocolManager> maybeSnapProtocolManager) {
@ -591,6 +804,17 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
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(
ProtocolSchedule protocolSchedule,
ProtocolContext protocolContext,
@ -599,19 +823,57 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
SyncState syncState,
EthProtocolManager ethProtocolManager);
/**
* Create protocol schedule protocol schedule.
*
* @return the protocol schedule
*/
protected abstract ProtocolSchedule createProtocolSchedule();
/**
* Validate context.
*
* @param context the 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(
Blockchain blockchain,
WorldStateArchive worldStateArchive,
ProtocolSchedule protocolSchedule);
/**
* Gets supported protocol.
*
* @return the supported protocol
*/
protected String getSupportedProtocol() {
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(
final ProtocolContext protocolContext,
final SynchronizerConfiguration synchronizerConfiguration,
@ -640,6 +902,15 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
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(
final MutableBlockchain blockchain,
final WorldStateArchive worldStateArchive,
@ -695,6 +966,12 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
metricsSystem));
}
/**
* Create peer validators list.
*
* @param protocolSchedule the protocol schedule
* @return the list
*/
protected List<PeerValidator> createPeerValidators(final ProtocolSchedule protocolSchedule) {
final List<PeerValidator> validators = new ArrayList<>();
@ -732,6 +1009,13 @@ public abstract class BesuControllerBuilder implements MiningParameterOverrides
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(
final Blockchain blockchain, final ProtocolContext protocolContext);
}

@ -22,10 +22,21 @@ import java.util.function.Supplier;
import com.google.common.base.Suppliers;
/** Base class for BFT based Besu Controller Builders. */
public abstract class BftBesuControllerBuilder extends BesuControllerBuilder {
/**
* Bft extra data codec supplier.
*
* @return the supplier of type BftExtraDataCodec.
*/
protected abstract Supplier<BftExtraDataCodec> bftExtraDataCodec();
/**
* Bft block interface supplier.
*
* @return the supplier of type BftBlockInterface.
*/
protected Supplier<BftBlockInterface> bftBlockInterface() {
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.services.BesuPluginContextImpl;
/** Bft query plugin service factory which is a concrete implementation of PluginServiceFactory. */
public class BftQueryPluginServiceFactory implements PluginServiceFactory {
private final Blockchain blockchain;
@ -33,6 +34,15 @@ public class BftQueryPluginServiceFactory implements PluginServiceFactory {
private final NodeKey nodeKey;
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(
final Blockchain blockchain,
final BftExtraDataCodec bftExtraDataCodec,

@ -45,6 +45,7 @@ import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** The Clique consensus controller builder. */
public class CliqueBesuControllerBuilder extends BesuControllerBuilder {
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.services.BesuPluginContextImpl;
/** The Clique query plugin service factory. */
public class CliqueQueryPluginServiceFactory implements PluginServiceFactory {
private final Blockchain blockchain;
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) {
this.blockchain = blockchain;
this.nodeKey = nodeKey;

@ -78,10 +78,10 @@ import java.util.stream.Collectors;
import com.google.common.annotations.VisibleForTesting;
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
BesuControllerBuilder to the first controller in the list.
*/
/**
* 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.
*/
public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilder {
private final Map<Long, BesuControllerBuilder> besuControllerBuilderSchedule = new HashMap<>();
@ -89,6 +89,11 @@ public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilde
NavigableSet<ForkSpec<ProtocolSchedule>>, Optional<BigInteger>, ProtocolSchedule>
combinedProtocolScheduleFactory;
/**
* Instantiates a new Consensus schedule Besu controller builder.
*
* @param besuControllerBuilderSchedule the besu controller builder schedule
*/
public ConsensusScheduleBesuControllerBuilder(
final Map<Long, BesuControllerBuilder> besuControllerBuilderSchedule) {
this(
@ -97,6 +102,12 @@ public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilde
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
protected ConsensusScheduleBesuControllerBuilder(
final Map<Long, BesuControllerBuilder> besuControllerBuilderSchedule,
@ -415,6 +426,11 @@ public class ConsensusScheduleBesuControllerBuilder extends BesuControllerBuilde
return super.evmConfiguration(evmConfiguration);
}
/**
* Gets besu controller builder schedule. Visible for testing.
*
* @return the Besu controller builder schedule
*/
@VisibleForTesting
Map<Long, BesuControllerBuilder> getBesuControllerBuilderSchedule() {
return besuControllerBuilderSchedule;

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

@ -52,12 +52,14 @@ import java.util.Optional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** The Ibft legacy besu controller builder. */
public class IbftLegacyBesuControllerBuilder extends BesuControllerBuilder {
private static final Logger LOG = LoggerFactory.getLogger(IbftLegacyBesuControllerBuilder.class);
private final BlockInterface blockInterface = new IbftLegacyBlockInterface();
// TODO remove this warning once IBFT1 has been deprecated
/** Default constructor */
public IbftLegacyBesuControllerBuilder() {
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");

@ -26,6 +26,7 @@ import org.hyperledger.besu.plugin.services.query.IbftQueryService;
import org.hyperledger.besu.plugin.services.query.PoaQueryService;
import org.hyperledger.besu.services.BesuPluginContextImpl;
/** The IBFT query plugin service factory. */
public class IbftQueryPluginServiceFactory implements PluginServiceFactory {
private final Blockchain blockchain;
@ -33,6 +34,14 @@ public class IbftQueryPluginServiceFactory implements PluginServiceFactory {
private final ValidatorProvider validatorProvider;
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(
final Blockchain blockchain,
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.worldstate.WorldStateArchive;
/** The Mainnet besu controller builder. */
public class MainnetBesuControllerBuilder extends BesuControllerBuilder {
private EpochCalculator epochCalculator = new EpochCalculator.DefaultEpochCalculator();

@ -57,6 +57,7 @@ import java.util.concurrent.atomic.AtomicReference;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** The Merge besu controller builder. */
public class MergeBesuControllerBuilder extends BesuControllerBuilder {
private final AtomicReference<SyncState> syncState = new AtomicReference<>();
private static final Logger LOG = LoggerFactory.getLogger(MergeBesuControllerBuilder.class);
@ -135,6 +136,18 @@ public class MergeBesuControllerBuilder extends BesuControllerBuilder {
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(
final ProtocolSchedule protocolSchedule,
final ProtocolContext protocolContext,
@ -243,6 +256,11 @@ public class MergeBesuControllerBuilder extends BesuControllerBuilder {
return controller;
}
/**
* Create timestamp protocol schedule.
*
* @return the timestamp schedule
*/
public TimestampSchedule createTimestampProtocolSchedule() {
return MergeProtocolSchedule.createTimestamp(
configOptionsSupplier.get(), privacyParameters, isRevertReasonEnabled);

@ -21,6 +21,12 @@ import org.hyperledger.besu.ethereum.core.MiningParameters;
* overrides.
*/
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) {
return fromCli;
}

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

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

@ -94,6 +94,7 @@ import com.google.common.base.Suppliers;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** The Qbft Besu controller builder. */
public class QbftBesuControllerBuilder extends BftBesuControllerBuilder {
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.LoggerFactory;
/** The Transition besu controller builder. */
public class TransitionBesuControllerBuilder extends BesuControllerBuilder {
private final BesuControllerBuilder preMergeBesuControllerBuilder;
private final MergeBesuControllerBuilder mergeBesuControllerBuilder;
@ -79,6 +80,12 @@ public class TransitionBesuControllerBuilder extends BesuControllerBuilder {
private static final Logger LOG = LoggerFactory.getLogger(TransitionBesuControllerBuilder.class);
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(
final BesuControllerBuilder preMergeBesuControllerBuilder,
final MergeBesuControllerBuilder mergeBesuControllerBuilder) {

@ -18,11 +18,18 @@ import org.hyperledger.besu.plugin.services.BesuConfiguration;
import java.nio.file.Path;
/** A concrete implementation of BesuConfiguration which is used in Besu plugin framework. */
public class BesuConfigurationImpl implements BesuConfiguration {
private final Path storagePath;
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) {
this.dataPath = dataPath;
this.storagePath = storagePath;

@ -38,12 +38,21 @@ import java.util.function.Supplier;
import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256;
/** A concrete implementation of BesuEvents used in Besu plugin framework. */
public class BesuEventsImpl implements BesuEvents {
private final Blockchain blockchain;
private final BlockBroadcaster blockBroadcaster;
private final TransactionPool transactionPool;
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(
final Blockchain blockchain,
final BlockBroadcaster blockBroadcaster,

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

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

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

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

Loading…
Cancel
Save