forked from besu-eth/besu
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBesuCommand.java
More file actions
2755 lines (2464 loc) · 114 KB
/
BesuCommand.java
File metadata and controls
2755 lines (2464 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright ConsenSys AG.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.cli;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.base.Preconditions.checkState;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;
import static org.hyperledger.besu.cli.DefaultCommandValues.getDefaultBesuDataPath;
import static org.hyperledger.besu.cli.util.CommandLineUtils.DEPENDENCY_WARNING_MSG;
import static org.hyperledger.besu.cli.util.CommandLineUtils.isOptionSet;
import static org.hyperledger.besu.config.NetworkDefinition.EPHEMERY;
import static org.hyperledger.besu.config.NetworkDefinition.MAINNET;
import static org.hyperledger.besu.controller.BesuController.DATABASE_PATH;
import static org.hyperledger.besu.ethereum.api.jsonrpc.authentication.EngineAuthService.EPHEMERAL_JWT_FILE;
import org.hyperledger.besu.Runner;
import org.hyperledger.besu.RunnerBuilder;
import org.hyperledger.besu.chainexport.Era1BlockExporter;
import org.hyperledger.besu.chainexport.RlpBlockExporter;
import org.hyperledger.besu.chainimport.Era1BlockImporter;
import org.hyperledger.besu.chainimport.JsonBlockImporter;
import org.hyperledger.besu.chainimport.RlpBlockImporter;
import org.hyperledger.besu.cli.config.EthNetworkConfig;
import org.hyperledger.besu.cli.config.NativeRequirement;
import org.hyperledger.besu.cli.config.NativeRequirement.NativeRequirementResult;
import org.hyperledger.besu.cli.config.ProfilesCompletionCandidates;
import org.hyperledger.besu.cli.custom.JsonRPCAllowlistHostsProperty;
import org.hyperledger.besu.cli.error.BesuExecutionExceptionHandler;
import org.hyperledger.besu.cli.error.BesuParameterExceptionHandler;
import org.hyperledger.besu.cli.options.ApiConfigurationOptions;
import org.hyperledger.besu.cli.options.BalConfigurationOptions;
import org.hyperledger.besu.cli.options.ChainPruningOptions;
import org.hyperledger.besu.cli.options.DebugTracerOptions;
import org.hyperledger.besu.cli.options.DnsOptions;
import org.hyperledger.besu.cli.options.EngineRPCConfiguration;
import org.hyperledger.besu.cli.options.EngineRPCOptions;
import org.hyperledger.besu.cli.options.EthProtocolOptions;
import org.hyperledger.besu.cli.options.EthstatsOptions;
import org.hyperledger.besu.cli.options.EvmOptions;
import org.hyperledger.besu.cli.options.GraphQlOptions;
import org.hyperledger.besu.cli.options.InProcessRpcOptions;
import org.hyperledger.besu.cli.options.IpcOptions;
import org.hyperledger.besu.cli.options.JsonRpcHttpOptions;
import org.hyperledger.besu.cli.options.LoggingLevelOption;
import org.hyperledger.besu.cli.options.MetricsOptions;
import org.hyperledger.besu.cli.options.MiningOptions;
import org.hyperledger.besu.cli.options.NatOptions;
import org.hyperledger.besu.cli.options.NativeLibraryOptions;
import org.hyperledger.besu.cli.options.NetworkingOptions;
import org.hyperledger.besu.cli.options.NodePrivateKeyFileOption;
import org.hyperledger.besu.cli.options.P2PDiscoveryOptions;
import org.hyperledger.besu.cli.options.PermissionsOptions;
import org.hyperledger.besu.cli.options.PluginsConfigurationOptions;
import org.hyperledger.besu.cli.options.RPCOptions;
import org.hyperledger.besu.cli.options.RpcWebsocketOptions;
import org.hyperledger.besu.cli.options.SynchronizerOptions;
import org.hyperledger.besu.cli.options.TransactionPoolOptions;
import org.hyperledger.besu.cli.options.storage.DataStorageOptions;
import org.hyperledger.besu.cli.options.storage.PathBasedExtraStorageOptions;
import org.hyperledger.besu.cli.options.unstable.QBFTOptions;
import org.hyperledger.besu.cli.presynctasks.PreSynchronizationTaskRunner;
import org.hyperledger.besu.cli.subcommands.PasswordSubCommand;
import org.hyperledger.besu.cli.subcommands.PublicKeySubCommand;
import org.hyperledger.besu.cli.subcommands.TxParseSubCommand;
import org.hyperledger.besu.cli.subcommands.ValidateConfigSubCommand;
import org.hyperledger.besu.cli.subcommands.blocks.BlocksSubCommand;
import org.hyperledger.besu.cli.subcommands.operator.OperatorSubCommand;
import org.hyperledger.besu.cli.subcommands.rlp.RLPSubCommand;
import org.hyperledger.besu.cli.subcommands.storage.StorageSubCommand;
import org.hyperledger.besu.cli.util.BesuCommandCustomFactory;
import org.hyperledger.besu.cli.util.BootnodeResolver;
import org.hyperledger.besu.cli.util.BootnodeResolver.BootnodeResolutionException;
import org.hyperledger.besu.cli.util.CommandLineUtils;
import org.hyperledger.besu.cli.util.ConfigDefaultValueProviderStrategy;
import org.hyperledger.besu.cli.util.VersionProvider;
import org.hyperledger.besu.components.BesuComponent;
import org.hyperledger.besu.config.CheckpointConfigOptions;
import org.hyperledger.besu.config.GenesisConfig;
import org.hyperledger.besu.config.GenesisConfigOptions;
import org.hyperledger.besu.config.MergeConfiguration;
import org.hyperledger.besu.config.NetworkDefinition;
import org.hyperledger.besu.consensus.merge.blockcreation.MergeCoordinator;
import org.hyperledger.besu.controller.BesuController;
import org.hyperledger.besu.controller.BesuControllerBuilder;
import org.hyperledger.besu.crypto.Blake2bfMessageDigest;
import org.hyperledger.besu.crypto.KeyPair;
import org.hyperledger.besu.crypto.KeyPairUtil;
import org.hyperledger.besu.crypto.SECP256R1;
import org.hyperledger.besu.crypto.SignatureAlgorithmFactory;
import org.hyperledger.besu.crypto.SignatureAlgorithmType;
import org.hyperledger.besu.cryptoservices.KeyPairSecurityModule;
import org.hyperledger.besu.cryptoservices.NodeKey;
import org.hyperledger.besu.datatypes.Address;
import org.hyperledger.besu.datatypes.Hash;
import org.hyperledger.besu.datatypes.Wei;
import org.hyperledger.besu.ethereum.api.ApiConfiguration;
import org.hyperledger.besu.ethereum.api.graphql.GraphQLConfiguration;
import org.hyperledger.besu.ethereum.api.jsonrpc.InProcessRpcConfiguration;
import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration;
import org.hyperledger.besu.ethereum.api.jsonrpc.RpcApis;
import org.hyperledger.besu.ethereum.api.jsonrpc.authentication.JwtAlgorithm;
import org.hyperledger.besu.ethereum.api.jsonrpc.ipc.JsonRpcIpcConfiguration;
import org.hyperledger.besu.ethereum.api.jsonrpc.websocket.WebSocketConfiguration;
import org.hyperledger.besu.ethereum.api.query.BlockchainQueries;
import org.hyperledger.besu.ethereum.chain.Blockchain;
import org.hyperledger.besu.ethereum.core.MiningConfiguration;
import org.hyperledger.besu.ethereum.core.MiningParametersMetrics;
import org.hyperledger.besu.ethereum.core.VersionMetadata;
import org.hyperledger.besu.ethereum.eth.sync.SyncMode;
import org.hyperledger.besu.ethereum.eth.sync.SynchronizerConfiguration;
import org.hyperledger.besu.ethereum.eth.transactions.ImmutableTransactionPoolConfiguration;
import org.hyperledger.besu.ethereum.eth.transactions.TransactionPoolConfiguration;
import org.hyperledger.besu.ethereum.mainnet.BalConfiguration;
import org.hyperledger.besu.ethereum.p2p.config.DiscoveryConfiguration;
import org.hyperledger.besu.ethereum.p2p.discovery.P2PDiscoveryConfiguration;
import org.hyperledger.besu.ethereum.p2p.peers.EnodeDnsConfiguration;
import org.hyperledger.besu.ethereum.p2p.peers.EnodeURLImpl;
import org.hyperledger.besu.ethereum.p2p.peers.StaticNodesParser;
import org.hyperledger.besu.ethereum.permissioning.LocalPermissioningConfiguration;
import org.hyperledger.besu.ethereum.permissioning.PermissioningConfiguration;
import org.hyperledger.besu.ethereum.storage.StorageProvider;
import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueSegmentIdentifier;
import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProvider;
import org.hyperledger.besu.ethereum.storage.keyvalue.KeyValueStorageProviderBuilder;
import org.hyperledger.besu.ethereum.worldstate.DataStorageConfiguration;
import org.hyperledger.besu.ethereum.worldstate.ImmutableDataStorageConfiguration;
import org.hyperledger.besu.ethereum.worldstate.ImmutablePathBasedExtraStorageConfiguration;
import org.hyperledger.besu.ethereum.worldstate.PathBasedExtraStorageConfiguration;
import org.hyperledger.besu.evm.precompile.AbstractAltBnPrecompiledContract;
import org.hyperledger.besu.evm.precompile.AbstractBLS12PrecompiledContract;
import org.hyperledger.besu.evm.precompile.AbstractPrecompiledContract;
import org.hyperledger.besu.evm.precompile.BigIntegerModularExponentiationPrecompiledContract;
import org.hyperledger.besu.evm.precompile.KZGPointEvalPrecompiledContract;
import org.hyperledger.besu.evm.precompile.P256VerifyPrecompiledContract;
import org.hyperledger.besu.metrics.BesuMetricCategory;
import org.hyperledger.besu.metrics.MetricCategoryRegistryImpl;
import org.hyperledger.besu.metrics.MetricsProtocol;
import org.hyperledger.besu.metrics.ObservableMetricsSystem;
import org.hyperledger.besu.metrics.StandardMetricCategory;
import org.hyperledger.besu.metrics.prometheus.MetricsConfiguration;
import org.hyperledger.besu.metrics.vertx.VertxMetricsAdapterFactory;
import org.hyperledger.besu.nat.NatMethod;
import org.hyperledger.besu.plugin.data.EnodeURL;
import org.hyperledger.besu.plugin.services.BesuConfiguration;
import org.hyperledger.besu.plugin.services.BesuEvents;
import org.hyperledger.besu.plugin.services.BlockSimulationService;
import org.hyperledger.besu.plugin.services.BlockchainService;
import org.hyperledger.besu.plugin.services.MetricsSystem;
import org.hyperledger.besu.plugin.services.PermissioningService;
import org.hyperledger.besu.plugin.services.PicoCLIOptions;
import org.hyperledger.besu.plugin.services.RpcEndpointService;
import org.hyperledger.besu.plugin.services.SecurityModuleService;
import org.hyperledger.besu.plugin.services.StorageService;
import org.hyperledger.besu.plugin.services.TraceService;
import org.hyperledger.besu.plugin.services.TransactionPoolValidatorService;
import org.hyperledger.besu.plugin.services.TransactionSelectionService;
import org.hyperledger.besu.plugin.services.TransactionSimulationService;
import org.hyperledger.besu.plugin.services.TransactionValidatorService;
import org.hyperledger.besu.plugin.services.WorldStateService;
import org.hyperledger.besu.plugin.services.exception.StorageException;
import org.hyperledger.besu.plugin.services.metrics.MetricCategoryRegistry;
import org.hyperledger.besu.plugin.services.mining.MiningService;
import org.hyperledger.besu.plugin.services.p2p.P2PService;
import org.hyperledger.besu.plugin.services.rlp.RlpConverterService;
import org.hyperledger.besu.plugin.services.securitymodule.SecurityModule;
import org.hyperledger.besu.plugin.services.storage.DataStorageFormat;
import org.hyperledger.besu.plugin.services.storage.rocksdb.RocksDBPlugin;
import org.hyperledger.besu.plugin.services.sync.SynchronizationService;
import org.hyperledger.besu.plugin.services.transactionpool.TransactionPoolService;
import org.hyperledger.besu.services.BesuConfigurationImpl;
import org.hyperledger.besu.services.BesuEventsImpl;
import org.hyperledger.besu.services.BesuPluginContextImpl;
import org.hyperledger.besu.services.BlockSimulatorServiceImpl;
import org.hyperledger.besu.services.BlockchainServiceImpl;
import org.hyperledger.besu.services.MiningServiceImpl;
import org.hyperledger.besu.services.P2PServiceImpl;
import org.hyperledger.besu.services.PermissioningServiceImpl;
import org.hyperledger.besu.services.PicoCLIOptionsImpl;
import org.hyperledger.besu.services.RlpConverterServiceImpl;
import org.hyperledger.besu.services.RpcEndpointServiceImpl;
import org.hyperledger.besu.services.SecurityModuleServiceImpl;
import org.hyperledger.besu.services.StorageServiceImpl;
import org.hyperledger.besu.services.SynchronizationServiceImpl;
import org.hyperledger.besu.services.TraceServiceImpl;
import org.hyperledger.besu.services.TransactionPoolServiceImpl;
import org.hyperledger.besu.services.TransactionPoolValidatorServiceImpl;
import org.hyperledger.besu.services.TransactionSelectionServiceImpl;
import org.hyperledger.besu.services.TransactionSimulationServiceImpl;
import org.hyperledger.besu.services.TransactionValidatorServiceImpl;
import org.hyperledger.besu.services.WorldStateServiceImpl;
import org.hyperledger.besu.services.kvstore.InMemoryStoragePlugin;
import org.hyperledger.besu.util.BesuVersionUtils;
import org.hyperledger.besu.util.EphemeryGenesisUpdater;
import org.hyperledger.besu.util.InvalidConfigurationException;
import org.hyperledger.besu.util.LogConfigurator;
import org.hyperledger.besu.util.NetworkUtility;
import org.hyperledger.besu.util.PermissioningConfigurationValidator;
import org.hyperledger.besu.util.number.Fraction;
import org.hyperledger.besu.util.number.Percentage;
import org.hyperledger.besu.util.number.PositiveNumber;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.attribute.GroupPrincipal;
import java.nio.file.attribute.PosixFileAttributes;
import java.nio.file.attribute.PosixFilePermission;
import java.nio.file.attribute.UserPrincipal;
import java.time.Clock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
import java.util.TreeMap;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.fasterxml.jackson.core.StreamReadConstraints;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Splitter;
import com.google.common.base.Strings;
import com.google.common.base.Suppliers;
import com.google.common.collect.ImmutableMap;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.jackson.DatabindCodec;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.impl.Log4jContextFactory;
import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256;
import org.slf4j.Logger;
import oshi.PlatformEnum;
import oshi.SystemInfo;
import picocli.AutoComplete;
import picocli.CommandLine;
import picocli.CommandLine.Command;
import picocli.CommandLine.ExecutionException;
import picocli.CommandLine.IExecutionStrategy;
import picocli.CommandLine.Model.ITypeInfo;
import picocli.CommandLine.Model.OptionSpec;
import picocli.CommandLine.Option;
import picocli.CommandLine.ParameterException;
import picocli.CommandLine.ParseResult;
/** 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.",
abbreviateSynopsis = true,
name = "besu",
mixinStandardHelpOptions = true,
versionProvider = VersionProvider.class,
header = "@|bold,fg(cyan) Usage:|@",
synopsisHeading = "%n",
descriptionHeading = "%n@|bold,fg(cyan) Description:|@%n%n",
optionListHeading = "%n@|bold,fg(cyan) Options:|@%n",
footerHeading = "%nBesu is licensed under the Apache License 2.0%n",
footer = {
"%n%n@|fg(cyan) To get started quickly, just choose a network to sync and a profile to run with suggested defaults:|@",
"%n@|fg(cyan) for Mainnet|@ --network=mainnet --profile=[minimalist_staker|staker]",
"%nMore info and other profiles at https://besu.hyperledger.org%n"
})
public class BesuCommand implements DefaultCommandValues, Runnable {
@SuppressWarnings("PrivateStaticFinalLoggers")
// non-static for testing
private final Logger logger;
private CommandLine commandLine;
private final Supplier<RlpBlockImporter> rlpBlockImporter;
private final Function<BesuController, JsonBlockImporter> jsonBlockImporterFactory;
private final Supplier<Era1BlockImporter> era1BlockImporter;
private final Function<Blockchain, RlpBlockExporter> rlpBlockExporterFactory;
private final BiFunction<Blockchain, NetworkDefinition, Era1BlockExporter>
era1BlockExporterFactory;
// Unstable CLI options
final NetworkingOptions unstableNetworkingOptions = NetworkingOptions.create();
final SynchronizerOptions unstableSynchronizerOptions = SynchronizerOptions.create();
final EthProtocolOptions unstableEthProtocolOptions = EthProtocolOptions.create();
private final DnsOptions unstableDnsOptions = DnsOptions.create();
private final NatOptions unstableNatOptions = NatOptions.create();
private final NativeLibraryOptions unstableNativeLibraryOptions = NativeLibraryOptions.create();
private final RPCOptions unstableRPCOptions = RPCOptions.create();
private final EvmOptions unstableEvmOptions = EvmOptions.create();
private final IpcOptions unstableIpcOptions = IpcOptions.create();
private final ChainPruningOptions unstableChainPruningOptions = ChainPruningOptions.create();
private final QBFTOptions unstableQbftOptions = QBFTOptions.create();
private final DebugTracerOptions unstableDebugTracerOptions = DebugTracerOptions.create();
// stable CLI options
final DataStorageOptions dataStorageOptions = DataStorageOptions.create();
private final EthstatsOptions ethstatsOptions = EthstatsOptions.create();
private final NodePrivateKeyFileOption nodePrivateKeyFileOption =
NodePrivateKeyFileOption.create();
private final LoggingLevelOption loggingLevelOption = LoggingLevelOption.create();
@CommandLine.ArgGroup(validate = false, heading = "@|bold Tx Pool Common Options|@%n")
final TransactionPoolOptions transactionPoolOptions = TransactionPoolOptions.create();
@CommandLine.ArgGroup(validate = false, heading = "@|bold Block Builder Options|@%n")
final MiningOptions miningOptions = MiningOptions.create();
private final RunnerBuilder runnerBuilder;
private final BesuController.Builder controllerBuilder;
private final BesuPluginContextImpl besuPluginContext;
private final StorageServiceImpl storageService;
private final SecurityModuleServiceImpl securityModuleService;
private final PermissioningServiceImpl permissioningService;
private final RpcEndpointServiceImpl rpcEndpointServiceImpl;
private final Map<String, String> environment;
private final MetricCategoryRegistryImpl metricCategoryRegistry =
new MetricCategoryRegistryImpl();
private final PreSynchronizationTaskRunner preSynchronizationTaskRunner =
new PreSynchronizationTaskRunner();
private final Set<Integer> allocatedPorts = new HashSet<>();
private final Supplier<GenesisConfig> genesisConfigSupplier =
Suppliers.memoize(this::readGenesisConfig);
private final Supplier<GenesisConfigOptions> genesisConfigOptionsSupplier =
Suppliers.memoize(this::readGenesisConfigOptions);
private final Supplier<MiningConfiguration> miningParametersSupplier =
Suppliers.memoize(this::getMiningParameters);
private final Supplier<ApiConfiguration> apiConfigurationSupplier =
Suppliers.memoize(this::getApiConfiguration);
private RocksDBPlugin rocksDBPlugin;
private int maxPeers;
private int maxRemoteInitiatedPeers;
// CLI options defined by user at runtime.
// Options parsing is done with CLI library Picocli https://picocli.info/
// While this variable is never read it is needed for the PicoCLI to create
// the config file option that is read elsewhere.
@SuppressWarnings("UnusedVariable")
@CommandLine.Option(
names = {CONFIG_FILE_OPTION_NAME},
paramLabel = MANDATORY_FILE_FORMAT_HELP,
description = "TOML config file (default: none)")
private final File configFile = null;
@CommandLine.Option(
names = {"--data-path"},
paramLabel = MANDATORY_PATH_FORMAT_HELP,
description = "The path to Besu data directory (default: ${DEFAULT-VALUE})")
final Path dataPath = getDefaultBesuDataPath(this);
// Genesis file path with null default option.
// This default is handled by Runner
// to use mainnet json file from resources as indicated in the
// default network option
// Then we ignore genesis default value here.
@CommandLine.Option(
names = {"--genesis-file"},
paramLabel = MANDATORY_FILE_FORMAT_HELP,
description =
"Genesis file for your custom network. Setting this option requires --network-id to be set. (Cannot be used with --network)")
private final File genesisFile = null;
@Option(
names = {"--genesis-state-hash-cache-enabled"},
description =
"Use genesis state hash from data on startup if specified (default: ${DEFAULT-VALUE})")
private final Boolean genesisStateHashCacheEnabled = false;
@Option(
names = "--identity",
paramLabel = "<String>",
description = "Identification for this node in the Client ID",
arity = "1")
private final Optional<String> identityString = Optional.empty();
private Boolean printPathsAndExit = Boolean.FALSE;
private String besuUserName = "besu";
@Option(
names = "--print-paths-and-exit",
paramLabel = "<username>",
description = "Print the configured paths and exit without starting the node.",
arity = "0..1")
void setUserName(final String userName) {
PlatformEnum currentPlatform = SystemInfo.getCurrentPlatform();
// Only allow on Linux and macOS
if (currentPlatform == PlatformEnum.LINUX || currentPlatform == PlatformEnum.MACOS) {
if (userName != null) {
besuUserName = userName;
}
printPathsAndExit = Boolean.TRUE;
} else {
throw new UnsupportedOperationException(
"--print-paths-and-exit is only supported on Linux and macOS.");
}
}
// P2P Discovery Option Group
@CommandLine.ArgGroup(validate = false, heading = "@|bold P2P Discovery Options|@%n")
P2PDiscoveryOptions p2PDiscoveryOptions = new P2PDiscoveryOptions();
P2PDiscoveryConfiguration p2PDiscoveryConfig;
private final TransactionSelectionServiceImpl transactionSelectionServiceImpl;
private final TransactionPoolValidatorServiceImpl transactionPoolValidatorServiceImpl;
private final TransactionValidatorServiceImpl transactionValidatorServiceImpl;
private final TransactionSimulationServiceImpl transactionSimulationServiceImpl;
private final BlockchainServiceImpl blockchainServiceImpl;
private BesuComponent besuComponent;
@Option(
names = {"--sync-mode"},
paramLabel = MANDATORY_MODE_FORMAT_HELP,
description =
"Synchronization mode, possible values are ${COMPLETION-CANDIDATES} (default: SNAP if a --network is supplied. FULL otherwise.)")
private SyncMode syncMode = null;
@Option(
names = {"--sync-min-peers", "--fast-sync-min-peers"},
paramLabel = MANDATORY_INTEGER_FORMAT_HELP,
description =
"Minimum number of peers required before starting sync. Has effect only on non-PoS networks. (default: ${DEFAULT-VALUE})")
private final Integer syncMinPeerCount = SYNC_MIN_PEER_COUNT;
private NetworkDefinition network = null;
@Option(
names = {"--network"},
paramLabel = MANDATORY_NETWORK_FORMAT_HELP,
defaultValue = "MAINNET",
description =
"Synchronize against the indicated network, possible values are ${COMPLETION-CANDIDATES}."
+ " (default: ${DEFAULT-VALUE})")
void setNetwork(final String inputNetwork) {
// case-insensitive and (_,-)-insensitive
final var normalizedInputNetwork = inputNetwork.toLowerCase(Locale.ROOT).replace('-', '_');
this.network =
Arrays.stream(NetworkDefinition.values())
.filter(nd -> nd.name().toLowerCase(Locale.ROOT).equals(normalizedInputNetwork))
.findAny()
.orElseThrow(
() ->
new IllegalArgumentException(
"Network %s does not exist".formatted(inputNetwork)));
}
@Option(
names = {PROFILE_OPTION_NAME},
paramLabel = PROFILE_FORMAT_HELP,
completionCandidates = ProfilesCompletionCandidates.class,
description =
"Overwrite default settings. Possible values are ${COMPLETION-CANDIDATES}. (default: none)")
private String profile = null; // don't set it as final due to picocli completion candidates
@Option(
names = {"--nat-method"},
description =
"Specify the NAT circumvention method to be used, possible values are ${COMPLETION-CANDIDATES}."
+ " NONE disables NAT functionality. (default: ${DEFAULT-VALUE})")
private final NatMethod natMethod = DEFAULT_NAT_METHOD;
@Option(
names = {"--network-id"},
paramLabel = "<BIG INTEGER>",
description =
"P2P network identifier. (default: the selected network chain ID or custom genesis chain ID)",
arity = "1")
private final BigInteger networkId = null;
@Option(
names = {"--kzg-trusted-setup"},
paramLabel = MANDATORY_FILE_FORMAT_HELP,
description =
"Path to file containing the KZG trusted setup, mandatory for custom networks that support data blobs, "
+ "optional for overriding named networks default.",
arity = "1")
private final Path kzgTrustedSetupFile = null;
@Option(
names = {"--version-compatibility-protection"},
description =
"Perform compatibility checks between the version of Besu being started and the version of Besu that last started with this data directory. (default: ${DEFAULT-VALUE})")
private Boolean versionCompatibilityProtection = null;
@CommandLine.ArgGroup(validate = false, heading = "@|bold GraphQL Options|@%n")
GraphQlOptions graphQlOptions = new GraphQlOptions();
// Engine JSON-PRC Options
@CommandLine.ArgGroup(validate = false, heading = "@|bold Engine JSON-RPC Options|@%n")
EngineRPCOptions engineRPCOptions = new EngineRPCOptions();
EngineRPCConfiguration engineRPCConfig = engineRPCOptions.toDomainObject();
// JSON-RPC HTTP Options
@CommandLine.ArgGroup(validate = false, heading = "@|bold JSON-RPC HTTP Options|@%n")
JsonRpcHttpOptions jsonRpcHttpOptions = new JsonRpcHttpOptions();
// JSON-RPC Websocket Options
@CommandLine.ArgGroup(validate = false, heading = "@|bold JSON-RPC Websocket Options|@%n")
RpcWebsocketOptions rpcWebsocketOptions = new RpcWebsocketOptions();
// In-Process RPC Options
@CommandLine.ArgGroup(validate = false, heading = "@|bold In-Process RPC Options|@%n")
InProcessRpcOptions inProcessRpcOptions = InProcessRpcOptions.create();
// Metrics Option Group
@CommandLine.ArgGroup(validate = false, heading = "@|bold Metrics Options|@%n")
MetricsOptions metricsOptions = MetricsOptions.create();
@Option(
names = {"--host-allowlist"},
paramLabel = "<hostname>[,<hostname>...]... or * or all",
description =
"Comma separated list of hostnames to allow for RPC access, or * to accept any host (default: ${DEFAULT-VALUE})",
defaultValue = "localhost,127.0.0.1")
private final JsonRPCAllowlistHostsProperty hostsAllowlist = new JsonRPCAllowlistHostsProperty();
@SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"})
@Option(
names = {"--color-enabled"},
description =
"Force color output to be enabled/disabled (default: colorized only if printing to console)")
private static Boolean colorEnabled = null;
@Option(
names = {"--reorg-logging-threshold"},
description =
"How deep a chain reorganization must be in order for it to be logged (default: ${DEFAULT-VALUE})")
private final Long reorgLoggingThreshold = 6L;
// Permission Option Group
@CommandLine.ArgGroup(validate = false, heading = "@|bold Permissions Options|@%n")
PermissionsOptions permissionsOptions = new PermissionsOptions();
@Option(
names = {"--revert-reason-enabled"},
description =
"Enable passing the revert reason back through TransactionReceipts (default: ${DEFAULT-VALUE})")
private final Boolean isRevertReasonEnabled = false;
@Option(
names = {"--required-blocks", "--required-block"},
paramLabel = "BLOCK=HASH",
description = "Block number and hash peers are required to have.",
arity = "*",
split = ",")
private final Map<Long, Hash> requiredBlocks = new HashMap<>();
@SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"}) // PicoCLI requires non-final Strings.
@Option(
names = {"--key-value-storage"},
description = "Identity for the key-value storage to be used.",
arity = "1")
private String keyValueStorageName = DEFAULT_KEY_VALUE_STORAGE_NAME;
@SuppressWarnings({"FieldCanBeFinal", "FieldMayBeFinal"})
@Option(
names = {"--security-module"},
paramLabel = "<NAME>",
description = "Identity for the Security Module to be used.",
arity = "1")
private String securityModuleName = DEFAULT_SECURITY_MODULE;
@Option(
names = {"--auto-log-bloom-caching-enabled"},
description = "Enable automatic log bloom caching (default: ${DEFAULT-VALUE})",
arity = "1")
private final Boolean autoLogBloomCachingEnabled = true;
@Option(
names = {"--override-genesis-config"},
paramLabel = "NAME=VALUE",
description = "Overrides configuration values in the genesis file. Use with care.",
arity = "*",
hidden = true,
split = ",")
private final Map<String, String> genesisConfigOverrides =
new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
@CommandLine.Option(
names = {"--pid-path"},
paramLabel = MANDATORY_PATH_FORMAT_HELP,
description = "Path to PID file (optional)")
private final Path pidPath = null;
// API Configuration Option Group
@CommandLine.ArgGroup(validate = false, heading = "@|bold API Configuration Options|@%n")
ApiConfigurationOptions apiConfigurationOptions = new ApiConfigurationOptions();
@CommandLine.ArgGroup(validate = false, heading = "@|bold Block Access List Options|@%n")
BalConfigurationOptions balConfigurationOptions = new BalConfigurationOptions();
@CommandLine.Option(
names = {"--static-nodes-file"},
paramLabel = MANDATORY_FILE_FORMAT_HELP,
description =
"Specifies the static node file containing the static nodes for this node to connect to")
private final Path staticNodesFile = null;
@CommandLine.Option(
names = {"--cache-last-blocks"},
description = "Specifies the number of last blocks to cache (default: ${DEFAULT-VALUE})")
private final Integer numberOfBlocksToCache = 0;
@CommandLine.Option(
names = {"--cache-last-block-headers"},
description =
"Specifies the number of last block headers to cache (default: ${DEFAULT-VALUE})")
private final Integer numberOfBlockHeadersToCache = 0;
@CommandLine.Option(
names = {"--cache-last-block-headers-preload-enabled"},
description = "Enable preloading of the block header cache (default: ${DEFAULT-VALUE})")
private final Boolean isCacheLastBlockHeadersPreloadEnabled = false;
@CommandLine.Option(
names = {"--cache-precompiles"},
description = "Specifies whether to cache precompile results (default: ${DEFAULT-VALUE})")
private final Boolean enablePrecompileCaching = false;
// Plugins Configuration Option Group
@CommandLine.ArgGroup(validate = false)
PluginsConfigurationOptions pluginsConfigurationOptions = new PluginsConfigurationOptions();
private EthNetworkConfig ethNetworkConfig;
private JsonRpcConfiguration jsonRpcConfiguration;
private JsonRpcConfiguration engineJsonRpcConfiguration;
private GraphQLConfiguration graphQLConfiguration;
private WebSocketConfiguration webSocketConfiguration;
private JsonRpcIpcConfiguration jsonRpcIpcConfiguration;
private InProcessRpcConfiguration inProcessRpcConfiguration;
private MetricsConfiguration metricsConfiguration;
private Optional<PermissioningConfiguration> permissioningConfiguration;
private DataStorageConfiguration dataStorageConfiguration;
private Collection<EnodeURL> staticNodes;
private BesuController besuController;
private BesuConfigurationImpl pluginCommonConfiguration;
private Vertx vertx;
private EnodeDnsConfiguration enodeDnsConfiguration;
private KeyValueStorageProvider keyValueStorageProvider;
/**
* Besu command constructor.
*
* @param rlpBlockImporter RlpBlockImporter supplier
* @param jsonBlockImporterFactory instance of {@code Function<BesuController, JsonBlockImporter>}
* @param era1BlockImporter Era1BlockImporter supplier
* @param rlpBlockExporterFactory instance of {@code Function<Blockchain, RlpBlockExporter>}
* @param era1BlockExporterFactory instance of {@code Function<Blockchain, Era1BlockExporter>}
* @param runnerBuilder instance of RunnerBuilder
* @param controllerBuilder instance of BesuController.Builder
* @param besuPluginContext instance of BesuPluginContextImpl
* @param environment Environment variables map
* @param commandLogger instance of Logger for outputting to the CLI
*/
public BesuCommand(
final Supplier<RlpBlockImporter> rlpBlockImporter,
final Function<BesuController, JsonBlockImporter> jsonBlockImporterFactory,
final Supplier<Era1BlockImporter> era1BlockImporter,
final Function<Blockchain, RlpBlockExporter> rlpBlockExporterFactory,
final BiFunction<Blockchain, NetworkDefinition, Era1BlockExporter> era1BlockExporterFactory,
final RunnerBuilder runnerBuilder,
final BesuController.Builder controllerBuilder,
final BesuPluginContextImpl besuPluginContext,
final Map<String, String> environment,
final Logger commandLogger) {
this(
rlpBlockImporter,
jsonBlockImporterFactory,
era1BlockImporter,
rlpBlockExporterFactory,
era1BlockExporterFactory,
runnerBuilder,
controllerBuilder,
besuPluginContext,
environment,
new StorageServiceImpl(),
new SecurityModuleServiceImpl(),
new PermissioningServiceImpl(),
new RpcEndpointServiceImpl(),
new TransactionSelectionServiceImpl(),
new TransactionPoolValidatorServiceImpl(),
new TransactionSimulationServiceImpl(),
new BlockchainServiceImpl(),
new TransactionValidatorServiceImpl(),
commandLogger);
}
/**
* Overloaded Besu command constructor visible for testing.
*
* @param rlpBlockImporter RlpBlockImporter supplier
* @param jsonBlockImporterFactory instance of {@code Function<BesuController, JsonBlockImporter>}
* @param era1BlockImporter Era1BlockImporter supplier
* @param rlpBlockExporterFactory instance of {@code Function<Blockchain, RlpBlockExporter>}
* @param era1BlockExporterFactory instance of {@code Function<Blockchain, Era1BlockExporter>}
* @param runnerBuilder instance of RunnerBuilder
* @param controllerBuilder 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 rpcEndpointServiceImpl instance of RpcEndpointServiceImpl
* @param transactionSelectionServiceImpl instance of TransactionSelectionServiceImpl
* @param transactionPoolValidatorServiceImpl instance of TransactionPoolValidatorServiceImpl
* @param transactionSimulationServiceImpl instance of TransactionSimulationServiceImpl
* @param blockchainServiceImpl instance of BlockchainServiceImpl
* @param transactionValidatorServiceImpl instance of TransactionValidatorServiceImpl
* @param commandLogger instance of Logger for outputting to the CLI
*/
@VisibleForTesting
protected BesuCommand(
final Supplier<RlpBlockImporter> rlpBlockImporter,
final Function<BesuController, JsonBlockImporter> jsonBlockImporterFactory,
final Supplier<Era1BlockImporter> era1BlockImporter,
final Function<Blockchain, RlpBlockExporter> rlpBlockExporterFactory,
final BiFunction<Blockchain, NetworkDefinition, Era1BlockExporter> era1BlockExporterFactory,
final RunnerBuilder runnerBuilder,
final BesuController.Builder controllerBuilder,
final BesuPluginContextImpl besuPluginContext,
final Map<String, String> environment,
final StorageServiceImpl storageService,
final SecurityModuleServiceImpl securityModuleService,
final PermissioningServiceImpl permissioningService,
final RpcEndpointServiceImpl rpcEndpointServiceImpl,
final TransactionSelectionServiceImpl transactionSelectionServiceImpl,
final TransactionPoolValidatorServiceImpl transactionPoolValidatorServiceImpl,
final TransactionSimulationServiceImpl transactionSimulationServiceImpl,
final BlockchainServiceImpl blockchainServiceImpl,
final TransactionValidatorServiceImpl transactionValidatorServiceImpl,
final Logger commandLogger) {
this.logger = commandLogger;
this.rlpBlockImporter = rlpBlockImporter;
this.jsonBlockImporterFactory = jsonBlockImporterFactory;
this.era1BlockImporter = era1BlockImporter;
this.rlpBlockExporterFactory = rlpBlockExporterFactory;
this.era1BlockExporterFactory = era1BlockExporterFactory;
this.runnerBuilder = runnerBuilder;
this.controllerBuilder = controllerBuilder;
this.besuPluginContext = besuPluginContext;
this.environment = environment;
this.storageService = storageService;
this.securityModuleService = securityModuleService;
this.permissioningService = permissioningService;
if (besuPluginContext.getService(BesuConfigurationImpl.class).isPresent()) {
this.pluginCommonConfiguration =
besuPluginContext.getService(BesuConfigurationImpl.class).get();
} else {
this.pluginCommonConfiguration = new BesuConfigurationImpl();
besuPluginContext.addService(BesuConfiguration.class, this.pluginCommonConfiguration);
}
this.rpcEndpointServiceImpl = rpcEndpointServiceImpl;
this.transactionSelectionServiceImpl = transactionSelectionServiceImpl;
this.transactionPoolValidatorServiceImpl = transactionPoolValidatorServiceImpl;
this.transactionSimulationServiceImpl = transactionSimulationServiceImpl;
this.blockchainServiceImpl = blockchainServiceImpl;
this.transactionValidatorServiceImpl = transactionValidatorServiceImpl;
}
/**
* Parses command line arguments and configures the application accordingly.
*
* @param resultHandler The strategy to handle the execution result.
* @param parameterExceptionHandler Handler for exceptions related to command line parameters.
* @param executionExceptionHandler Handler for exceptions during command execution.
* @param in The input stream for commands.
* @param besuComponent The Besu component.
* @param args The command line arguments.
* @return The execution result status code.
*/
@VisibleForTesting
public int parse(
final IExecutionStrategy resultHandler,
final BesuParameterExceptionHandler parameterExceptionHandler,
final BesuExecutionExceptionHandler executionExceptionHandler,
final InputStream in,
final BesuComponent besuComponent,
final String... args) {
if (besuComponent == null) {
throw new IllegalArgumentException("BesuComponent must be provided");
}
this.besuComponent = besuComponent;
initializeCommandLineSettings(in);
// Create the execution strategy chain.
final IExecutionStrategy executeTask = createExecuteTask(resultHandler);
final IExecutionStrategy pluginRegistrationTask = createPluginRegistrationTask(executeTask);
final IExecutionStrategy setDefaultValueProviderTask =
createDefaultValueProviderTask(pluginRegistrationTask);
// 1- Config default value provider
// 2- Register plugins
// 3- Execute command
return executeCommandLine(
setDefaultValueProviderTask, parameterExceptionHandler, executionExceptionHandler, args);
}
private void initializeCommandLineSettings(final InputStream in) {
toCommandLine();
// Automatically adjust the width of usage messages to the terminal width.
commandLine.getCommandSpec().usageMessage().autoWidth(true);
handleStableOptions();
addSubCommands(in);
registerConverters();
handleUnstableOptions();
preparePlugins();
}
private IExecutionStrategy createExecuteTask(final IExecutionStrategy nextStep) {
return parseResult -> {
commandLine.setExecutionStrategy(nextStep);
// At this point we don't allow unmatched options since plugins were already registered
commandLine.setUnmatchedArgumentsAllowed(false);
return commandLine.execute(parseResult.originalArgs().toArray(new String[0]));
};
}
private IExecutionStrategy createPluginRegistrationTask(final IExecutionStrategy nextStep) {
return parseResult -> {
if (parseResult.isUsageHelpRequested() || parseResult.isVersionHelpRequested()) {
// suppressing the info log to avoid that plugin registrations logs are printed
// before the help or the version information
suppressInfoLog();
}
besuPluginContext.initialize(PluginsConfigurationOptions.fromCommandLine(commandLine));
besuPluginContext.registerPlugins();
commandLine.setExecutionStrategy(nextStep);
return commandLine.execute(parseResult.originalArgs().toArray(new String[0]));
};
}
@SuppressWarnings("BannedMethod")
private void suppressInfoLog() {
// this is specific for Log4j2, in case we switch to another logging framework,
// this need to be adapted for it
// silence already created loggers
LoggerContext.getContext(false).getLoggers().forEach(logger -> logger.setLevel(Level.WARN));
// silence future loggers by configuration
if (LogManager.getFactory() instanceof Log4jContextFactory log4jContextFactory) {
final var selector = log4jContextFactory.getSelector();
selector
.getLoggerContexts()
.forEach(
ctx ->
ctx.getConfiguration()
.getLoggers()
.values()
.forEach(loggerConfig -> loggerConfig.setLevel(Level.WARN)));
}
}
private IExecutionStrategy createDefaultValueProviderTask(final IExecutionStrategy nextStep) {
return new ConfigDefaultValueProviderStrategy(nextStep, environment);
}
/**
* Executes the command line with the provided execution strategy and exception handlers.
*
* @param executionStrategy The execution strategy to use.
* @param args The command line arguments.
* @return The execution result status code.
*/
private int executeCommandLine(
final IExecutionStrategy executionStrategy,
final BesuParameterExceptionHandler parameterExceptionHandler,
final BesuExecutionExceptionHandler executionExceptionHandler,
final String... args) {
try {
// Parse and run duplicate-check
// As this happens before the plugins registration and plugins can add options, we must
// allow unmatched options
final ParseResult pr = commandLine.setUnmatchedArgumentsAllowed(true).parseArgs(args);
rejectDuplicateScalarOptions(pr); // your generic validator
} catch (ParameterException e) {
// ← Send it to the standard handler: prints one line & exits status 1
return parameterExceptionHandler.handleParseException(e, args);
}
return commandLine
.setExecutionStrategy(executionStrategy)
.setParameterExceptionHandler(parameterExceptionHandler)
.setExecutionExceptionHandler(executionExceptionHandler)
// As this happens before the plugins registration and plugins can add options, we must
// allow unmatched options
.setUnmatchedArgumentsAllowed(true)
.execute(args);
}
/** Used by Dagger to parse all options into a commandline instance. */
public void toCommandLine() {
commandLine =
new CommandLine(this, new BesuCommandCustomFactory(besuPluginContext))
.setCaseInsensitiveEnumValuesAllowed(true)
.setToggleBooleanFlags(false);
}
@Override
public void run() {
if (network != null && network.isDeprecated()) {
logger.warn(NetworkDeprecationMessage.generate(network));
}
try {
configureLogging(true);
if (printPathsAndExit) {
// Print configured paths requiring read/write permissions to be adjusted
checkPermissionsAndPrintPaths(besuUserName);
System.exit(0); // Exit before any services are started
}
// set merge config on the basis of genesis config
setMergeConfigOptions();
instantiateSignatureAlgorithmFactory();
logger.info("Starting Besu");
// Need to create vertx after cmdline has been parsed, such that metricsSystem is configurable
vertx = createVertx(createVertxOptions(besuComponent.getMetricsSystem()));
validateOptions();
configure();
setIgnorableStorageSegments();
// If we're not running against a named network, or if version compat protection has been
// explicitly enabled, perform compatibility check
VersionMetadata.versionCompatibilityChecks(versionCompatibilityProtection, dataDir());
configureNativeLibs(Optional.ofNullable(network));
if (enablePrecompileCaching) {
configurePrecompileCaching();
}
besuController = buildController();
besuPluginContext.beforeExternalServices();
final var runner = buildRunner();
runner.startExternalServices();
startPlugins(runner);
setReleaseMetrics();
preSynchronization();
runner.startEthereumMainLoop();
besuPluginContext.afterExternalServicesMainLoop();
runner.awaitStop();
} catch (final Exception e) {
logger.error("Failed to start Besu: {}", e.getMessage());
logger.debug("Startup failure cause", e);
throw new ParameterException(this.commandLine, e.getMessage(), e);
}
}