Repository navigation
Expand file tree
/
Copy pathstart.rs
More file actions
1835 lines (1649 loc) · 62.7 KB
/
Copy pathstart.rs
File metadata and controls
1835 lines (1649 loc) · 62.7 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 2025 Circle Internet Group, Inc. All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
// 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.
use std::net::SocketAddr;
use std::path::PathBuf;
use arc_consensus_types::rpc_sync::SyncEndpointUrl;
use clap::Parser;
use color_eyre::eyre;
use serde::{Deserialize, Serialize};
use tracing::{info, warn};
use url::Url;
use arc_consensus_types::Address;
use malachitebft_app::consensus::Multiaddr;
use crate::file::save_priv_validator_key;
use crate::new::generate_private_keys;
/// Tokio single-threaded runtime flavor.
pub const RUNTIME_SINGLE_THREADED: &str = "single-threaded";
/// Tokio multi-threaded runtime flavor.
pub const RUNTIME_MULTI_THREADED: &str = "multi-threaded";
/// Start command to run a node.
///
/// Derives `clap::Parser` for CLI parsing and `serde::Serialize` /
/// `serde::Deserialize` for TOML-based deserialization by external
/// tooling. Deployment-specific fields are marked `#[serde(skip)]`, so
/// TOML cannot set them. They inherit their values from
/// `StartCmd::default()` via the container-level `#[serde(default)]`.
#[derive(Parser, Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
pub struct StartCmd {
// ===== Node Identity =====
/// A custom human-readable name for this node.
///
/// If not provided, a random moniker will be generated.
#[clap(long, value_name = "NAME")]
#[serde(skip)]
pub moniker: Option<String>,
// ===== P2P Networking =====
/// P2P listen multiaddr
///
/// Example: /ip4/172.19.0.5/tcp/27000
#[clap(
long = "p2p.addr",
value_name = "MULTIADDR",
default_value = "/ip4/0.0.0.0/tcp/27000"
)]
#[serde(skip)]
pub p2p_addr: Multiaddr,
/// Comma-separated list of persistent peer multiaddrs to connect to
///
/// Example: /ip4/172.19.0.21/tcp/27000,/ip4/172.19.0.22/tcp/27000
#[clap(long = "p2p.persistent-peers", value_delimiter = ',', num_args = 0..)]
#[serde(skip)]
pub p2p_persistent_peers: Vec<Multiaddr>,
/// Only allow connections to/from persistent peers.
///
/// When set, the node will reject connections from peers that are not
/// in the persistent peers list. Useful for sentry node setups where
/// a validator should only communicate with known trusted peers.
#[clap(long = "p2p.persistent-peers-only")]
#[serde(skip)]
pub p2p_persistent_peers_only: bool,
/// Enable gossipsub explicit peering for persistent peers.
///
/// When enabled, persistent peers are added as explicit peers in GossipSub,
/// meaning a node always sends and forwards messages to its explicit peers,
/// regardless of mesh membership.
#[clap(long = "gossipsub.explicit-peering", help_heading = "GossipSub")]
#[serde(skip)]
pub gossipsub_explicit_peering: bool,
/// Enable gossipsub mesh peer scoring / prioritization.
///
/// When enabled, peers are scored and prioritized based on their type
/// during mesh formation.
#[clap(long = "gossipsub.mesh-prioritization", help_heading = "GossipSub")]
#[serde(skip)]
pub gossipsub_mesh_prioritization: bool,
/// Gossipsub network load profile controlling mesh size and bandwidth.
///
/// - low: fewer mesh peers, lower bandwidth (mesh_n=3)
/// - average: balanced for typical deployments (mesh_n=6) [default]
/// - high: more mesh peers, higher bandwidth (mesh_n=10)
#[clap(
long = "gossipsub.load",
value_name = "PROFILE",
help_heading = "GossipSub",
value_parser = ["low", "average", "high"]
)]
#[serde(skip)]
pub gossipsub_load: Option<String>,
// ===== Logging =====
/// Log level
#[clap(long, value_name = "LOG_LEVEL")]
pub log_level: Option<malachitebft_config::LogLevel>,
/// Log format
#[clap(long, value_name = "LOG_FORMAT")]
pub log_format: Option<malachitebft_config::LogFormat>,
// ===== Discovery =====
/// Enable peer discovery
#[clap(long)]
pub discovery: bool,
/// Number of outbound peers for discovery
#[clap(
long = "discovery.num-outbound-peers",
value_name = "COUNT",
default_value = "20"
)]
pub discovery_num_outbound_peers: usize,
/// Number of inbound peers for discovery
#[clap(
long = "discovery.num-inbound-peers",
value_name = "COUNT",
default_value = "20"
)]
pub discovery_num_inbound_peers: usize,
// ===== Consensus =====
/// Disable consensus protocol participation.
///
/// When set, the node only runs the synchronization protocol
/// and does not subscribe to consensus-related gossip topics.
/// Use for sync-only full nodes.
#[clap(long, conflicts_with = "validator")]
pub no_consensus: bool,
/// Run as a validator node.
///
/// When set, the node loads its consensus signing key,
/// signs a validator proof, and advertises a
/// validator identity on the P2P network. Requires
/// `--suggested-fee-recipient` so tips and rewards go to
/// an explicit address rather than being silently burned.
///
/// Without this flag the node runs as a full node: it
/// participates in gossip but does not sign votes or proposals.
#[clap(
long,
conflicts_with_all = ["no_consensus", "follow"],
requires = "suggested_fee_recipient",
)]
pub validator: bool,
// ===== Value Sync =====
/// Enable value sync
#[clap(
long,
default_value_t = true,
num_args = 0..=1,
default_missing_value = "true",
)]
pub value_sync: bool,
// ===== Execution Layer Connection =====
/// The path to the Ethereum IPC socket. For reth with default settings,
/// this will be /tmp/reth.ipc. To change the path in reth, you need to
/// provide the `--ipcpath` flag.
///
/// This is recommended option if the consensus and execution layers are colocated on the same machine.
#[clap(long, value_name = "PATH")]
#[serde(skip)]
pub eth_socket: Option<String>,
/// The path to the execution engine socket. To enable this in reth, you
/// need to provide the `--auth-ipc` and `--auth-ipc.path` flags.
///
/// This is recommended option if the consensus and execution layers are colocated on the same machine.
#[clap(long, value_name = "PATH")]
#[serde(skip)]
pub execution_socket: Option<String>,
/// The URL of the Ethereum JSON-RPC API. If the Ethereum full node is
/// running on the same computer with the default port, this will be
/// http://localhost:8545. Most of the execution clients provide this
/// functionality.
///
/// Use this option if the consensus and executation layer are on different machines.
#[clap(long, value_name = "URL")]
#[serde(skip)]
pub eth_rpc_endpoint: Option<Url>,
/// The URL of the execution engine API. If the execution engine is running
/// on the same computer with the default port, this will be
/// http://localhost:8551.
///
/// Use this option if the consensus and executation layer are on different machines.
#[clap(long, value_name = "URL")]
#[serde(skip)]
pub execution_endpoint: Option<Url>,
/// The WebSocket URL of the execution engine. Used for subscribing to
/// real-time execution layer events (e.g. persisted block notifications).
///
/// If omitted, derived from --eth-rpc-endpoint using the convention
/// (scheme http→ws / https→wss, port + 1).
///
/// Example: ws://localhost:8546
#[clap(long, value_name = "URL")]
#[serde(skip)]
pub execution_ws_endpoint: Option<Url>,
/// Enable persistence backpressure during startup replay. When enabled,
/// the consensus layer waits for the execution layer to persist blocks
/// before replaying further.
///
/// Requires --execution-ws-endpoint (RPC mode) or IPC mode.
#[clap(long = "execution-persistence-backpressure")]
pub execution_persistence_backpressure: bool,
/// Maximum canonical-minus-persisted gap the execution layer may have
/// before persistence backpressure is applied.
///
/// Backpressure begins once the gap reaches this threshold.
///
/// Only takes effect when --execution-persistence-backpressure is enabled.
/// Large values weaken backpressure and may allow the execution layer
/// to accumulate a significant unpersisted block buffer.
#[clap(
long = "execution-persistence-backpressure-threshold",
value_name = "BLOCKS",
default_value = "16"
)]
pub execution_persistence_backpressure_threshold: u64,
/// The path to the JWT secret file shared by Malachite and the execution
/// engine. This is a mandatory form of authentication which ensures that
/// Malachite has the authority to control the execution engine.
///
/// Use this option if the consensus and executation layer are on different machines.
#[clap(long, value_name = "PATH")]
#[serde(skip)]
pub execution_jwt: Option<String>,
// ===== Metrics =====
/// Enable Prometheus metrics and set listen address.
///
/// If omitted, metrics are disabled.
/// If provided, metrics are enabled on the given address.
///
/// Example: 0.0.0.0:29000
#[clap(long, value_name = "ADDR")]
#[serde(skip)]
pub metrics: Option<SocketAddr>,
// ===== RPC =====
/// Enable RPC server and set listen address.
///
/// If omitted, RPC is disabled.
/// If provided, RPC is enabled on the given address.
///
/// Example: 0.0.0.0:31000
#[clap(long = "rpc.addr", value_name = "ADDR")]
#[serde(skip)]
pub rpc_addr: Option<SocketAddr>,
/// Enable the admin RPC routes.
///
/// Disabled by default. These routes mutate node state and have no
/// authentication, so they stay unreachable unless explicitly enabled.
/// Only enable on an internal, trusted RPC interface.
#[clap(long = "rpc.admin", default_value_t = false)]
#[serde(skip)]
pub rpc_admin: bool,
// ===== Runtime =====
/// Tokio runtime flavor to use.
#[clap(
long = "runtime.flavor",
value_name = "FLAVOR",
default_value = RUNTIME_MULTI_THREADED,
value_parser = [RUNTIME_SINGLE_THREADED, RUNTIME_MULTI_THREADED]
)]
pub runtime_flavor: String,
/// Number of worker threads for the Tokio multi-threaded runtime.
///
/// If not set, the runtime will default to the number of CPU cores.
/// This option is ignored if the single-threaded runtime is selected.
#[clap(long = "runtime.worker-threads", value_name = "COUNT")]
pub worker_threads: Option<usize>,
// ===== Pruning presets =====
/// Full-node pruning preset. Sets --prune.certificates.distance 237600.
/// Mutually exclusive with --minimal and the individual --prune.certificates.* flags.
/// Note: on the CL, both --full and --minimal retain the same certificate
/// history for now; the distinction applies at the EL layer.
#[clap(
long = "full",
default_value_t = false,
conflicts_with_all = &["minimal", "prune_certificates_distance", "prune_certificates_before"],
help_heading = "Arc pruning presets"
)]
#[serde(skip)]
pub full: bool,
/// Minimal-storage pruning preset. Sets --prune.certificates.distance 237600.
/// Mutually exclusive with --full and the individual --prune.certificates.* flags.
/// Note: on the CL, both --full and --minimal retain the same certificate
/// history for now; the distinction applies at the EL layer.
#[clap(
long = "minimal",
default_value_t = false,
conflicts_with_all = &["full", "prune_certificates_distance", "prune_certificates_before"],
help_heading = "Arc pruning presets"
)]
#[serde(skip)]
pub minimal: bool,
// ===== Pruning =====
/// Keep certificates for the last N heights. Certificates for heights older than
/// current_height - N will be pruned. Mirrors reth's --prune.*.distance semantics.
/// Setting this to 0 disables distance-based pruning.
/// Mutually exclusive with --prune.certificates.before and the pruning presets.
#[clap(
long = "prune.certificates.distance",
alias = "pruning.block-interval",
value_name = "COUNT",
default_value = "0",
conflicts_with_all = &["prune_certificates_before", "full", "minimal"]
)]
pub prune_certificates_distance: u64,
/// Prune all certificates at heights strictly below this value.
/// Setting this to 0 disables height-based pruning.
/// Mutually exclusive with --prune.certificates.distance and the pruning presets.
#[clap(
long = "prune.certificates.before",
alias = "pruning.min-height",
value_name = "HEIGHT",
default_value = "0",
conflicts_with_all = &["prune_certificates_distance", "full", "minimal"]
)]
pub prune_certificates_before: u64,
// ===== Other =====
/// The path to the validator private key file.
///
/// This file contains the private key used for:
/// - P2P/libp2p network identity (always required)
/// - Consensus message signing (only when using local signing, not with --signing.remote)
///
/// When using --signing.remote, if this file doesn't exist, it will be automatically
/// generated with a random key for P2P network identity purposes.
///
/// Default: {home_dir}/config/priv_validator_key.json
/// where `home_dir` is the directory provided with the `--home` global option
#[clap(long, value_name = "PATH")]
#[serde(skip)]
pub private_key: Option<PathBuf>,
/// Profiling server bind address
#[clap(
long = "pprof.addr",
value_name = "ADDR",
default_value = "0.0.0.0:6060"
)]
#[serde(skip)]
pub pprof_addr: String,
/// Activate jemalloc heap profiling at startup.
///
/// When built with the `pprof` feature, heap profiling infrastructure is
/// always available but inactive by default. This flag activates it so
/// that the `/debug/pprof/allocs` endpoint returns meaningful data.
#[clap(long = "pprof.heap-prof", default_value_t = false)]
pub pprof_heap_prof: bool,
/// 20-byte ethereum-style address to receive tips (transactions' priority fee)
/// and rewards.
///
/// The execution layer deposits fees and rewards to this address whenever the
/// validator successfully proposes a new block. The zero address is rejected
/// because rewards credited to it bypass the native-coin blocklist and are
/// unrecoverable.
#[clap(long, value_name = "ADDRESS", value_parser = parse_non_zero_address)]
#[serde(skip)]
pub suggested_fee_recipient: Option<Address>,
/// Skip database schema upgrade on startup.
///
/// WARNING: This flag should only be used when a database upgrade failed.
/// Not upgrading the database may lead to errors or data corruption.
#[clap(long = "db.skip-upgrade")]
#[serde(skip)]
pub skip_db_upgrade: bool,
// ===== Signing =====
/// Use remote signing with the specified endpoint URL
///
/// If not provided, local signing will be used (default behavior).
///
/// Only meaningful together with `--validator`; for full and sync-only nodes
/// no consensus signing occurs.
///
/// Example: http://validator-signer-proxy:10340
#[clap(
long = "signing.remote",
value_name = "ENDPOINT",
requires = "validator"
)]
#[serde(skip)]
pub signing_remote: Option<String>,
/// Path to TLS certificate for remote signing
///
/// Only used when --signing.remote is specified.
/// If provided, TLS will be automatically enabled.
#[clap(
long = "signing.tls-cert-path",
value_name = "PATH",
requires = "signing_remote"
)]
#[serde(skip)]
pub signing_tls_cert_path: Option<String>,
/// Enable RPC sync mode (follow with verification).
///
/// In RPC sync mode, the node fetches blocks from trusted RPC endpoints
/// instead of participating in consensus. This is useful for running
/// read-only nodes that sync from validators.
///
/// When no --follow.endpoint is provided, a default endpoint is resolved
/// from the chain ID at startup.
#[clap(long = "follow")]
#[serde(skip)]
pub follow: bool,
/// RPC endpoint to fetch blocks from in RPC sync mode.
/// This flag can be repeated.
/// Optional when --follow is set; defaults are resolved from the chain ID.
///
/// Format:
/// <http_url>[,<ws_protocol>=<port_or_host_or_host:port>]
/// where <http_url> is an http:// or https:// URL,
/// and <ws_protocol> is either ws or wss.
///
/// The WebSocket override value can be:
/// - A port number (e.g., wss=8546) — same host, explicit port
/// - A hostname (e.g., wss=ws.example.com) — different host, default port
/// - A host:port pair (e.g., wss=ws.example.com:1212) — different host and port
///
/// If not specified, the WebSocket URL is derived from the HTTP URL
/// (scheme http->ws / https->wss, port HTTP+1 if non-default).
///
/// Examples:
/// http://validator1:8545,ws=8546
/// https://validator1:8545,wss=8546
/// https://example.com,wss=ws.example.com
/// https://example.com,wss=ws.example.com:1212
#[clap(long = "follow.endpoint", value_name = "ENDPOINT", requires = "follow")]
#[serde(skip)]
pub follow_endpoints: Vec<SyncEndpointUrl>,
/// Byzantine behavior configuration as a JSON blob. Testnet / Quake only.
///
/// Deserializes into `arc_consensus_types::ByzantineConfig` and enables
/// configurable Byzantine faults: vote/proposal equivocation, message
/// dropping, inbound-proposal drops, amnesia, force-precommit-nil.
///
/// Example: --byzantine='{"equivocate_votes":{"mode":"always"},"seed":42}'
#[cfg(feature = "byzantine")]
#[clap(
long,
value_name = "JSON",
value_parser = parse_byzantine_json,
help_heading = "Byzantine (testnet only)"
)]
#[serde(default, skip_serializing_if = "Option::is_none")]
pub byzantine: Option<arc_consensus_types::ByzantineConfig>,
}
#[cfg(feature = "byzantine")]
fn parse_byzantine_json(s: &str) -> Result<arc_consensus_types::ByzantineConfig, String> {
serde_json::from_str(s).map_err(|e| format!("invalid --byzantine JSON: {e}"))
}
fn parse_non_zero_address(s: &str) -> Result<Address, String> {
let addr: Address = s.parse().map_err(|e| format!("invalid address: {e}"))?;
if addr.to_alloy_address().is_zero() {
return Err(
"must not be the zero address; rewards credited to 0x0 bypass the \
native-coin blocklist and are unrecoverable"
.to_string(),
);
}
Ok(addr)
}
impl Default for StartCmd {
fn default() -> Self {
Self {
moniker: None,
p2p_addr: "/ip4/0.0.0.0/tcp/27000".parse().expect("valid multiaddr"),
p2p_persistent_peers: Vec::new(),
p2p_persistent_peers_only: false,
gossipsub_explicit_peering: false,
gossipsub_mesh_prioritization: false,
gossipsub_load: None,
log_level: None,
log_format: None,
discovery: false,
discovery_num_outbound_peers: 20,
discovery_num_inbound_peers: 20,
no_consensus: false,
validator: false,
value_sync: true,
eth_socket: None,
execution_socket: None,
eth_rpc_endpoint: None,
execution_endpoint: None,
execution_ws_endpoint: None,
execution_persistence_backpressure: false,
execution_persistence_backpressure_threshold: 16,
execution_jwt: None,
metrics: None,
rpc_addr: None,
rpc_admin: false,
runtime_flavor: RUNTIME_MULTI_THREADED.to_string(),
worker_threads: None,
full: false,
minimal: false,
prune_certificates_distance: 0,
prune_certificates_before: 0,
private_key: None,
pprof_addr: "0.0.0.0:6060".to_string(),
pprof_heap_prof: false,
suggested_fee_recipient: None,
skip_db_upgrade: false,
signing_remote: None,
signing_tls_cert_path: None,
#[cfg(feature = "byzantine")]
byzantine: None,
follow: false,
follow_endpoints: Vec::new(),
}
}
}
impl StartCmd {
/// Generate CLI flag strings for all non-default, manifest-configurable fields.
///
/// Each field maps 1:1 to its `#[clap(long = "...")]` name. Only fields
/// whose values differ from `StartCmd::default()` are emitted. Deployment-
/// specific fields (marked `#[serde(skip)]`) are included here because
/// callers populate these before invoking.
pub fn to_cli_flags(&self) -> Vec<String> {
let defaults = Self::default();
let mut flags = Vec::new();
macro_rules! push_each {
($flag:literal, $items:expr) => {
for item in $items {
flags.push(format!(concat!("--", $flag, "={}"), item));
}
};
}
macro_rules! push_if_some {
($flag:literal, $opt:expr) => {
if let Some(ref v) = $opt {
flags.push(format!(concat!("--", $flag, "={}"), v));
}
};
}
macro_rules! push_if {
($flag:literal, $cond:expr) => {
if $cond {
flags.push(concat!("--", $flag).to_string());
}
};
}
macro_rules! push_if_non_default {
($flag:literal, $field:ident) => {
if self.$field != defaults.$field {
flags.push(format!(concat!("--", $flag, "={}"), self.$field));
}
};
}
// --- Deployment-specific fields (set by quake at runtime) ---
push_if_some!("moniker", self.moniker);
push_if_non_default!("p2p.addr", p2p_addr);
if !self.p2p_persistent_peers.is_empty() {
let peers: Vec<String> = self
.p2p_persistent_peers
.iter()
.map(|p| p.to_string())
.collect();
flags.push(format!("--p2p.persistent-peers={}", peers.join(",")));
}
push_if!("p2p.persistent-peers-only", self.p2p_persistent_peers_only);
push_if!(
"gossipsub.explicit-peering",
self.gossipsub_explicit_peering
);
push_if!(
"gossipsub.mesh-prioritization",
self.gossipsub_mesh_prioritization
);
push_if_some!("gossipsub.load", self.gossipsub_load);
// --- Manifest-configurable fields ---
push_if_some!("log-level", self.log_level);
push_if_some!("log-format", self.log_format);
push_if!("discovery", self.discovery);
push_if_non_default!("discovery.num-outbound-peers", discovery_num_outbound_peers);
push_if_non_default!("discovery.num-inbound-peers", discovery_num_inbound_peers);
push_if!("no-consensus", self.no_consensus);
push_if!("validator", self.validator);
push_if_non_default!("value-sync", value_sync);
push_if!(
"execution-persistence-backpressure",
self.execution_persistence_backpressure
);
push_if_non_default!(
"execution-persistence-backpressure-threshold",
execution_persistence_backpressure_threshold
);
push_if_non_default!("runtime.flavor", runtime_flavor);
push_if_some!("runtime.worker-threads", self.worker_threads);
push_if_non_default!("prune.certificates.distance", prune_certificates_distance);
push_if_non_default!("prune.certificates.before", prune_certificates_before);
// --- Deployment-specific fields (set by quake, continued) ---
push_if_some!("eth-socket", self.eth_socket);
push_if_some!("execution-socket", self.execution_socket);
push_if_some!("eth-rpc-endpoint", self.eth_rpc_endpoint);
push_if_some!("execution-endpoint", self.execution_endpoint);
push_if_some!("execution-ws-endpoint", self.execution_ws_endpoint);
push_if_some!("execution-jwt", self.execution_jwt);
push_if_some!("metrics", self.metrics);
push_if_some!("rpc.addr", self.rpc_addr);
push_if!("rpc.admin", self.rpc_admin);
push_if!("full", self.full);
push_if!("minimal", self.minimal);
if let Some(ref path) = self.private_key {
flags.push(format!("--private-key={}", path.display()));
}
push_if_non_default!("pprof.addr", pprof_addr);
push_if!("pprof.heap-prof", self.pprof_heap_prof);
push_if_some!("suggested-fee-recipient", self.suggested_fee_recipient);
push_if!("db.skip-upgrade", self.skip_db_upgrade);
push_if_some!("signing.remote", self.signing_remote);
push_if_some!("signing.tls-cert-path", self.signing_tls_cert_path);
push_if!("follow", self.follow);
push_each!("follow.endpoint", &self.follow_endpoints);
#[cfg(feature = "byzantine")]
if let Some(ref byz) = self.byzantine {
let json =
serde_json::to_string(byz).expect("ByzantineConfig serialization cannot fail");
flags.push(format!("--byzantine={json}"));
}
flags
}
/// Validates that conflicting options are not provided simultaneously.
///
/// This method ensures that users don't specify both IPC and RPC options
/// at the same time, as they represent different communication methods.
pub fn validate(&self) -> eyre::Result<()> {
// Check if both IPC and RPC options are provided
let has_ipc_options = self.eth_socket.is_some() || self.execution_socket.is_some();
let has_rpc_options = self.eth_rpc_endpoint.is_some()
|| self.execution_endpoint.is_some()
|| self.execution_jwt.is_some();
if has_ipc_options && has_rpc_options {
return Err(eyre::eyre!(
"Conflicting options detected: Cannot specify both IPC and RPC options simultaneously.\n\
IPC options: --eth-socket, --execution-socket\n\
RPC options: --eth-rpc-endpoint, --execution-endpoint, --execution-jwt\n\
Please choose either IPC (for local communication) or RPC (for remote communication)."
));
}
// The RPC/HTTP CL<->EL transport is deprecated and removed in v0.9.0.
// Warn on any RPC option; --execution-ws-endpoint only applies to RPC.
let uses_rpc_transport = self.eth_rpc_endpoint.is_some()
|| self.execution_endpoint.is_some()
|| self.execution_ws_endpoint.is_some()
|| self.execution_jwt.is_some();
if uses_rpc_transport {
warn!(
"DEPRECATION: the RPC/HTTP transport for CL<->EL (Engine API) \
communication is deprecated and will be removed in v0.9.0. \
Migrate to IPC: on the consensus layer use --eth-socket and \
--execution-socket in place of --eth-rpc-endpoint, \
--execution-endpoint, --execution-ws-endpoint, and \
--execution-jwt; on the execution layer enable IPC with \
--ipcpath, --auth-ipc, and --auth-ipc.path. See \
docs/running-an-arc-node.md."
);
}
// Validate persistent-peers-only configuration
if self.p2p_persistent_peers_only && self.p2p_persistent_peers.is_empty() {
return Err(eyre::eyre!(
"--p2p.persistent-peers-only requires at least one --p2p.persistent-peers entry.\n\
Without persistent peers, the node would reject all connections."
));
}
if self.execution_persistence_backpressure_threshold == 0 {
return Err(eyre::eyre!(
"--execution-persistence-backpressure-threshold must be greater than 0.\n\
A value of 0 would cause persistence backpressure to stall indefinitely once active."
));
}
Ok(())
}
pub fn private_key_file(&self, default: PathBuf) -> eyre::Result<PathBuf> {
let priv_key_path = self.private_key.as_ref().unwrap_or(&default);
if priv_key_path.exists() {
info!(path = %priv_key_path.display(), "Using existing private key file");
return Ok(priv_key_path.clone());
}
// The private key file does not exist.
if self.signing_remote.is_some() {
// With remote signing, we can auto-generate a key for P2P identity.
info!(file = %priv_key_path.display(), "Generating private key for P2P network identity");
let private_keys = generate_private_keys(1, false)?;
let priv_validator_key = private_keys[0].clone();
save_priv_validator_key(priv_key_path, &priv_validator_key)?;
info!(
path = %priv_key_path.display(),
"✅ Private key generated successfully for P2P network identity"
);
Ok(priv_key_path.clone())
} else if self.private_key.is_some() {
// A specific key file was requested but not found.
Err(eyre::eyre!(
"The specified private key file does not exist: {}",
priv_key_path.display()
))
} else {
// Using default path, but the key file is not found.
Err(eyre::eyre!(
"The default private key file does not exist: {}. \n\n\
You can generate it by running 'arc-node-consensus init' or \
provide a path to the existing file using the --private-key option.",
priv_key_path.display()
))
}
}
/// Get the moniker, generating a random one if not provided.
pub fn get_moniker(&self) -> String {
self.moniker.clone().unwrap_or_else(|| {
use rand::Rng;
let adjectives = [
"happy", "brave", "swift", "wise", "quiet", "bright", "calm", "eager", "gentle",
"kind", "noble", "proud", "swift", "witty", "zesty",
];
let nouns = [
"node",
"validator",
"sentinel",
"guardian",
"keeper",
"watcher",
"beacon",
"herald",
"oracle",
"pilot",
"ranger",
"scout",
];
let mut rng = rand::thread_rng();
let adj = adjectives[rng.gen_range(0..adjectives.len())];
let noun = nouns[rng.gen_range(0..nouns.len())];
let num = rng.gen_range(100..999);
format!("{}-{}-{}", adj, noun, num)
})
}
/// Get the P2P listen multiaddr.
pub fn p2p_listen_addr(&self) -> eyre::Result<Multiaddr> {
Ok(self.p2p_addr.clone())
}
/// Get persistent peers multiaddrs
pub fn persistent_peers(&self) -> Vec<Multiaddr> {
self.p2p_persistent_peers.clone()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use tempfile::tempdir;
const TEST_FEE_RECIPIENT: &str = "0xf97e180c050e5ab072211ad2c213eb5aee4df134";
fn new_start_cmd() -> StartCmd {
StartCmd {
moniker: Some("test-node".to_string()),
p2p_addr: "/ip4/127.0.0.1/tcp/27000".parse().unwrap(),
..Default::default()
}
}
fn dummy_url() -> Url {
Url::parse("http://localhost:8545").unwrap()
}
/// Assert that a file has secure permissions (0600 - read/write for owner only) on Unix systems
#[cfg(unix)]
fn assert_file_permissions_secure(path: &std::path::Path) {
use std::os::unix::fs::PermissionsExt;
let metadata = std::fs::metadata(path).unwrap();
let permissions = metadata.permissions();
assert_eq!(
permissions.mode() & 0o777,
0o600,
"File permissions should be 0600 (read/write for owner only)"
);
}
#[test]
fn validate_ok_with_no_conflicting_options() {
let cmd = new_start_cmd();
assert!(
cmd.validate().is_ok(),
"Command with valid options should be valid"
);
}
#[test]
fn validate_ok_with_only_ipc_options() {
let mut cmd = new_start_cmd();
cmd.eth_socket = Some("/tmp/reth.ipc".to_string());
cmd.execution_socket = Some("/tmp/reth-auth.ipc".to_string());
assert!(
cmd.validate().is_ok(),
"Should be valid with only IPC options"
);
}
#[test]
fn validate_ok_with_only_rpc_options() {
let mut cmd = new_start_cmd();
cmd.eth_rpc_endpoint = Some(dummy_url());
cmd.execution_endpoint = Some(dummy_url());
cmd.execution_jwt = Some("/path/to/jwt.hex".to_string());
assert!(
cmd.validate().is_ok(),
"Should be valid with only RPC options"
);
}
#[test]
#[tracing_test::traced_test]
fn validate_warns_on_deprecated_rpc_transport() {
let mut cmd = new_start_cmd();
cmd.eth_rpc_endpoint = Some(dummy_url());
cmd.execution_endpoint = Some(dummy_url());
cmd.execution_jwt = Some("/path/to/jwt.hex".to_string());
assert!(cmd.validate().is_ok(), "RPC options remain valid");
assert!(
logs_contain("deprecated") && logs_contain("v0.9.0"),
"RPC transport must emit a deprecation warning naming v0.9.0"
);
}
#[test]
#[tracing_test::traced_test]
fn validate_warns_on_execution_ws_endpoint_alone() {
let mut cmd = new_start_cmd();
cmd.execution_ws_endpoint = Some(dummy_url());
assert!(cmd.validate().is_ok(), "ws endpoint alone stays valid");
assert!(
logs_contain("deprecated"),
"--execution-ws-endpoint must trigger the deprecation warning"
);
}
#[test]
#[tracing_test::traced_test]
fn validate_no_deprecation_warning_in_ipc_mode() {
let mut cmd = new_start_cmd();
cmd.eth_socket = Some("/tmp/reth.ipc".to_string());
cmd.execution_socket = Some("/tmp/reth-auth.ipc".to_string());
assert!(cmd.validate().is_ok(), "IPC options remain valid");
assert!(
!logs_contain("deprecated"),
"IPC mode must not emit the RPC deprecation warning"
);
}
#[test]
fn validate_err_when_mixing_ipc_and_rpc() {
let mut cmd = new_start_cmd();
cmd.eth_socket = Some("/tmp/reth.ipc".to_string());
cmd.eth_rpc_endpoint = Some(dummy_url());
let result = cmd.validate();
assert!(result.is_err(), "Should fail when mixing IPC and RPC");
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("Conflicting options detected"));
}
#[test]
fn validate_err_with_another_mix_of_options() {
let mut cmd = new_start_cmd();
cmd.execution_socket = Some("/tmp/reth-auth.ipc".to_string());
cmd.execution_jwt = Some("/path/to/jwt.hex".to_string());
let result = cmd.validate();
assert!(
result.is_err(),
"Should fail with another mix of IPC and RPC"
);
}
#[test]
fn validate_err_with_zero_persistence_backpressure_threshold() {
let mut cmd = new_start_cmd();
cmd.execution_persistence_backpressure_threshold = 0;
let result = cmd.validate();
assert!(
result.is_err(),
"Should fail with zero persistence backpressure threshold"
);
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("execution-persistence-backpressure-threshold"));
}
#[test]
fn private_key_file_uses_provided_path_if_it_exists() {
let dir = tempdir().unwrap();
let key_path = dir.path().join("priv_validator_key.json");
File::create(&key_path).unwrap();
let mut cmd = new_start_cmd();
cmd.private_key = Some(key_path.clone());
let default_path = PathBuf::from("/non/existent/path");
let result = cmd.private_key_file(default_path);
assert!(result.is_ok());
assert_eq!(result.unwrap(), key_path);
}
#[test]
fn private_key_file_errs_if_provided_path_does_not_exist() {
let non_existent_path = PathBuf::from("/some/made/up/path/key.json");
let mut cmd = new_start_cmd();
cmd.private_key = Some(non_existent_path.clone());
let result = cmd.private_key_file(PathBuf::from("/another/path"));
assert!(result.is_err());
let err_msg = result.unwrap_err().to_string();
assert!(err_msg.contains("private key file does not exist"));
assert!(err_msg.contains(non_existent_path.to_str().unwrap()));
}
#[test]