-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.rs
More file actions
1853 lines (1585 loc) · 61.4 KB
/
main.rs
File metadata and controls
1853 lines (1585 loc) · 61.4 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
//! CipherBFT Node CLI
//!
//! A Cosmos SDK-style CLI for the CipherBFT blockchain node.
use alloy_primitives::U256;
use anyhow::{Context, Result};
use cipherbft_crypto::{
BlsKeyPair, BlsSecretKey, Ed25519KeyPair, Ed25519SecretKey, ExposeSecret, KeyMetadata, Keyring,
KeyringBackend,
};
use cipherd::key_cli::KeyringBackendArg;
use cipherd::{
execute_keys_command, generate_local_configs, GenesisGenerator, GenesisGeneratorConfig,
GenesisLoader, KeysCommand, Node, NodeConfig, NodeSupervisor, ValidatorKeyFile,
CIPHERD_HOME_ENV, DEFAULT_HOME_DIR,
};
use clap::{Parser, Subcommand};
use std::path::PathBuf;
use tracing::{info, Level};
use tracing_subscriber::EnvFilter;
/// CipherBFT Daemon
#[derive(Parser)]
#[command(name = "cipherd")]
#[command(author = "CipherBFT Contributors")]
#[command(version)]
#[command(about = "CipherBFT Daemon", long_about = None)]
#[command(propagate_version = true)]
#[command(arg_required_else_help = true)]
struct Cli {
/// Directory for config and data
#[arg(long, global = true, default_value_os_t = default_home_dir())]
home: PathBuf,
/// The logging level (trace|debug|info|warn|error)
#[arg(long, global = true, default_value = "info")]
log_level: String,
/// The logging format (json|plain)
#[arg(long, global = true, default_value = "plain")]
log_format: String,
/// Disable colored logs
#[arg(long, global = true, default_value = "false")]
log_no_color: bool,
/// Print out full stack trace on errors
#[arg(long, global = true, default_value = "false")]
trace: bool,
#[command(subcommand)]
command: Commands,
}
#[derive(Subcommand)]
enum Commands {
/// Initialize private validator, p2p, genesis, and application configuration files
Init {
/// Moniker for this node
#[arg(long)]
moniker: Option<String>,
/// EVM Chain ID for the network (default: 85300)
#[arg(long, default_value = "85300")]
chain_id: u64,
/// Network identifier (e.g., "cipherbft-testnet-1")
#[arg(long, default_value = "cipherbft-testnet-1")]
network_id: String,
/// Initial stake per validator in ETH (default: 32)
#[arg(long, default_value = "32")]
initial_stake_eth: u64,
/// Overwrite existing configuration
#[arg(long, default_value = "false")]
overwrite: bool,
},
/// Run the full node
Start {
/// Path to configuration file (overrides --home)
#[arg(long)]
config: Option<PathBuf>,
/// Path to genesis file (overrides config and env var)
#[arg(long)]
genesis: Option<PathBuf>,
/// Keyring backend for key storage (overrides client.toml setting)
///
/// - file: EIP-2335 encrypted keystores (default, recommended)
/// - os: OS native keyring (macOS Keychain, Windows Credential Manager)
/// - test: Unencrypted storage (development only!)
#[arg(long, value_enum)]
keyring_backend: Option<KeyringBackendArg>,
},
/// Generate testnet/devnet configuration files for local multi-validator testing
#[command(alias = "devnet")]
Testnet {
#[command(subcommand)]
command: TestnetCommands,
},
/// Manage your application's keys (secure EIP-2335 keystores)
///
/// Common options like --keyring-backend can be specified at this level
/// or at the subcommand level. Subcommand-level options take precedence.
Keys {
/// Keyring backend for key storage (can also be specified per-subcommand)
///
/// - file: EIP-2335 encrypted keystores (default, recommended)
/// - os: OS native keyring (macOS Keychain, Windows Credential Manager)
/// - test: Unencrypted storage (development only!)
#[arg(long, value_enum)]
keyring_backend: Option<KeyringBackendArg>,
/// Directory containing keystore files (can also be specified per-subcommand)
#[arg(long)]
keys_dir: Option<PathBuf>,
#[command(subcommand)]
command: KeysCommand,
},
/// Utilities for managing application configuration
Config {
#[command(subcommand)]
command: ConfigCommands,
},
/// Query remote node for status via JSON-RPC
Status {
/// Node RPC URL to query (e.g., http://localhost:8545)
#[arg(long, default_value = "http://localhost:8545")]
node: String,
},
/// Print the application binary version information
Version {
/// Output format (text|json)
#[arg(long, default_value = "text")]
output: String,
},
/// Validates the genesis file at the default location or at the location passed as an arg
Validate {
/// Path to genesis file (optional, uses default if not provided)
#[arg(long)]
genesis: Option<PathBuf>,
},
/// Genesis file generation and management commands
Genesis {
#[command(subcommand)]
command: GenesisCommands,
},
/// Tool for helping with debugging your application
Debug {
#[command(subcommand)]
command: DebugCommands,
},
}
// Old KeysCommands removed - now using key_cli::KeysCommand with EIP-2335 encrypted storage
#[derive(Subcommand)]
enum ConfigCommands {
/// Show current configuration
Show,
/// Set a configuration value
Set {
/// Configuration key
key: String,
/// Configuration value
value: String,
},
/// Get a configuration value
Get {
/// Configuration key
key: String,
},
}
#[derive(Subcommand)]
enum GenesisCommands {
/// Generate a new genesis file with auto-generated validator keys
Generate {
/// Number of validators to generate
#[arg(short = 'n', long, default_value = "4")]
validators: usize,
/// Chain ID for the EVM network
#[arg(long, default_value = "85300")]
chain_id: u64,
/// Network identifier (e.g., "cipherbft-testnet-1")
#[arg(long, default_value = "cipherbft-testnet-1")]
network_id: String,
/// Initial stake per validator in ETH (default: 32 ETH)
#[arg(long, default_value = "32")]
initial_stake_eth: u64,
/// Output path for the genesis file
#[arg(short, long, default_value = "./genesis.json")]
output: PathBuf,
/// Output directory for validator key files (default: ./keys)
#[arg(long, default_value = "./keys")]
keys_dir: PathBuf,
/// Skip writing validator key files
#[arg(long, default_value = "false")]
no_keys: bool,
/// Extra account allocations in format address:balance_eth (can be repeated)
/// Example: --extra-alloc 0x123...abc:1000 --extra-alloc 0x456...def:500
#[arg(long = "extra-alloc", value_name = "ADDR:ETH")]
extra_alloc: Vec<String>,
},
/// Add a genesis account to an existing genesis file
#[command(name = "add-genesis-account")]
AddGenesisAccount {
/// Account address (0x... format)
address: String,
/// Initial balance in ETH
#[arg(long, default_value = "100")]
balance_eth: u64,
/// Path to genesis file
#[arg(long)]
genesis: Option<PathBuf>,
},
/// Generate a genesis transaction (gentx) for a validator
Gentx {
/// Path to validator key file (validator-N.json)
#[arg(long)]
key_file: PathBuf,
/// Stake amount in ETH
#[arg(long, default_value = "32")]
stake_eth: u64,
/// Validator moniker/name
#[arg(long)]
moniker: Option<String>,
/// Commission rate percentage (0-100)
#[arg(long, default_value = "10")]
commission_rate: u8,
/// Output directory for gentx file
#[arg(long, default_value = "./gentx")]
output_dir: PathBuf,
},
/// Collect genesis transactions and add them to genesis file
#[command(name = "collect-gentxs")]
CollectGentxs {
/// Directory containing gentx files
#[arg(long, default_value = "./gentx")]
gentx_dir: PathBuf,
/// Path to genesis file
#[arg(long)]
genesis: Option<PathBuf>,
},
}
#[derive(Subcommand)]
enum DebugCommands {
/// Print raw bytes for a block at a given height
RawBytes {
/// Block height
height: u64,
},
/// Decode and print a transaction
DecodeTx {
/// Hex-encoded transaction bytes
tx_bytes: String,
},
}
#[derive(Subcommand)]
enum TestnetCommands {
/// Initialize testnet configuration files for multi-validator setup
#[command(name = "init-files")]
InitFiles {
/// Number of validators to generate
#[arg(short = 'n', long, default_value = "4")]
validators: usize,
/// Output directory for testnet files
#[arg(short, long, default_value = "./testnet")]
output: PathBuf,
/// Chain ID for the network
#[arg(long, default_value = "85300")]
chain_id: u64,
/// Network identifier
#[arg(long, default_value = "cipherbft-testnet-1")]
network_id: String,
/// Initial stake per validator in ETH
#[arg(long, default_value = "32")]
initial_stake_eth: u64,
/// Initial balance per validator in ETH (for gas fees and transactions)
#[arg(long, default_value = "100")]
initial_balance_eth: u64,
/// Starting P2P port (increments by 10 for each validator)
#[arg(long, default_value = "9000")]
starting_port: u16,
/// Extra account allocations in format address:balance_eth (can be repeated)
/// Example: --extra-alloc 0x123...abc:1000 --extra-alloc 0x456...def:500
#[arg(long = "extra-alloc", value_name = "ADDR:ETH")]
extra_alloc: Vec<String>,
},
/// Start a local testnet with multiple validators (in-process)
Start {
/// Number of validators
#[arg(short = 'n', long, default_value = "4")]
validators: usize,
/// Duration to run in seconds (0 = run until Ctrl+C)
#[arg(short, long, default_value = "0")]
duration: u64,
},
}
/// Returns the default home directory for cipherd.
///
/// Resolution order:
/// 1. `CIPHERD_HOME` environment variable (if set)
/// 2. `~/.cipherd` (default)
fn default_home_dir() -> PathBuf {
// Check for CIPHERD_HOME environment variable first
if let Ok(home) = std::env::var(CIPHERD_HOME_ENV) {
return PathBuf::from(home);
}
// Fall back to default: ~/.cipherd
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
.join(DEFAULT_HOME_DIR)
}
#[tokio::main]
async fn main() -> Result<()> {
let cli = Cli::parse();
// Initialize tracing based on global flags
init_tracing(&cli.log_level, &cli.log_format, cli.log_no_color);
let result = match cli.command {
Commands::Init {
moniker,
chain_id,
network_id,
initial_stake_eth,
overwrite,
} => cmd_init(
&cli.home,
moniker,
chain_id,
&network_id,
initial_stake_eth,
overwrite,
),
Commands::Start {
config,
genesis,
keyring_backend,
} => {
let config_path = config.unwrap_or_else(|| cli.home.join("config/node.json"));
cmd_start(config_path, genesis, keyring_backend).await
}
Commands::Testnet { command } => cmd_testnet(command).await,
Commands::Keys {
keyring_backend,
keys_dir,
command,
} => execute_keys_command(&cli.home, keyring_backend, keys_dir, command),
Commands::Config { command } => cmd_config(&cli.home, command),
Commands::Status { node } => cmd_status(&node).await,
Commands::Version { output } => cmd_version(&output),
Commands::Validate { genesis } => cmd_validate(&cli.home, genesis),
Commands::Genesis { command } => cmd_genesis(&cli.home, command),
Commands::Debug { command } => cmd_debug(command),
};
if let Err(e) = &result {
if cli.trace {
eprintln!("Error: {:?}", e);
} else {
eprintln!("Error: {}", e);
}
std::process::exit(1);
}
Ok(())
}
fn init_tracing(log_level: &str, log_format: &str, no_color: bool) {
let level = match log_level.to_lowercase().as_str() {
"trace" => Level::TRACE,
"debug" => Level::DEBUG,
"info" => Level::INFO,
"warn" => Level::WARN,
"error" => Level::ERROR,
_ => Level::INFO,
};
let filter =
EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(level.to_string()));
let subscriber = tracing_subscriber::fmt()
.with_env_filter(filter)
.with_target(true)
.with_thread_ids(true)
.with_ansi(!no_color);
match log_format {
"json" => subscriber.json().init(),
_ => subscriber.init(),
}
}
// =============================================================================
// Command Implementations
// =============================================================================
fn cmd_init(
home: &std::path::Path,
moniker: Option<String>,
chain_id: u64,
network_id: &str,
initial_stake_eth: u64,
overwrite: bool,
) -> Result<()> {
let config_dir = home.join("config");
let data_dir = home.join("data");
// Keys are stored in {home}/keys (consistent with client.toml and keys commands)
let keys_dir = home.join("keys");
if config_dir.exists() && !overwrite {
anyhow::bail!(
"Configuration already exists at {}. Use --overwrite to replace.",
home.display()
);
}
// Create directory structure
std::fs::create_dir_all(&config_dir)?;
std::fs::create_dir_all(&data_dir)?;
std::fs::create_dir_all(&keys_dir)?;
// Generate a random node identifier for the moniker (not validator ID)
let node_id: [u8; 4] = rand::random();
let node_moniker = moniker.unwrap_or_else(|| format!("node-{}", hex::encode(node_id)));
// ========================================
// Generate genesis with single validator
// ========================================
println!("Generating genesis file with single validator...");
// Convert ETH to wei (1 ETH = 10^18 wei)
let initial_stake = U256::from(initial_stake_eth) * U256::from(1_000_000_000_000_000_000u128);
let genesis_config = GenesisGeneratorConfig {
num_validators: 1,
chain_id,
network_id: network_id.to_string(),
initial_stake,
..Default::default()
};
let mut rng = rand::thread_rng();
let genesis_result = GenesisGenerator::generate(&mut rng, genesis_config)
.context("Failed to generate genesis")?;
// Save genesis file
let genesis_path = config_dir.join("genesis.json");
genesis_result
.genesis
.save(&genesis_path)
.context("Failed to save genesis file")?;
// Save validator key file
let validator = &genesis_result.validators[0];
let key_file = ValidatorKeyFile::from_generated(0, validator);
let validator_key_path = keys_dir.join("validator-0.json");
let key_json = key_file
.to_json()
.context("Failed to serialize validator key")?;
std::fs::write(&validator_key_path, key_json)?;
// Create client.toml (Cosmos SDK style) for CLI settings
let client_config = cipherd::ClientConfig {
chain_id: chain_id.to_string(),
keyring_backend: cipherd::DEFAULT_KEYRING_BACKEND.to_string(),
keyring_dir: String::new(), // Use default: {home}/keys
keyring_default_keyname: cipherd::DEFAULT_KEY_NAME.to_string(),
output: "text".to_string(),
node: "tcp://localhost:26657".to_string(),
broadcast_mode: "sync".to_string(),
};
client_config.save(home)?;
// Create NodeConfig without validator_id (will be derived at start time from keys)
// Note: keystore settings are now in client.toml
let base_port = 9000u16;
let config = NodeConfig {
validator_id: None, // Derived at runtime from BLS key
keyring_backend: cipherd::DEFAULT_KEYRING_BACKEND.to_string(),
key_name: cipherd::DEFAULT_KEY_NAME.to_string(),
keystore_dir: None, // Use client.toml settings
keystore_account: Some(0),
primary_listen: format!("127.0.0.1:{}", base_port)
.parse()
.expect("default address format is always valid"),
consensus_listen: format!("127.0.0.1:{}", base_port + 5)
.parse()
.expect("default address format is always valid"),
worker_listens: vec![format!("127.0.0.1:{}", base_port + 1)
.parse()
.expect("default address format is always valid")],
peers: Vec::new(),
num_workers: 1,
home_dir: Some(home.to_path_buf()),
data_dir: data_dir.clone(),
genesis_path: Some(genesis_path.clone()),
car_interval_ms: 100,
max_batch_txs: 100,
max_batch_bytes: 1024 * 1024,
rpc_enabled: true,
rpc_http_port: cipherd::DEFAULT_RPC_HTTP_PORT,
rpc_ws_port: cipherd::DEFAULT_RPC_WS_PORT,
metrics_port: cipherd::DEFAULT_METRICS_PORT,
sync: cipherd::SyncConfig::default(),
};
let config_path = config_dir.join("node.json");
config.save(&config_path)?;
// Write a node info file with basic metadata
let node_info_path = config_dir.join("node_info.json");
let node_info = serde_json::json!({
"moniker": node_moniker,
"chain_id": chain_id,
"network_id": network_id,
"created_at": chrono::Utc::now().to_rfc3339(),
});
std::fs::write(&node_info_path, serde_json::to_string_pretty(&node_info)?)?;
let client_config_path = cipherd::ClientConfig::config_path(home);
println!();
println!("Successfully initialized node configuration");
println!();
println!(" Home: {}", home.display());
println!(" Moniker: {}", node_moniker);
println!(" Chain ID: {}", chain_id);
println!(" Network ID: {}", network_id);
println!(" Node config: {}", config_path.display());
println!(" Client config: {}", client_config_path.display());
println!(" Genesis: {}", genesis_path.display());
println!(" Keys dir: {}", keys_dir.display());
println!();
println!("Genesis Summary:");
println!(
" Validators: {}",
genesis_result.genesis.validator_count()
);
println!(" Total Stake: {} ETH", initial_stake_eth);
println!(
" Validator: {} (ed25519: {}...)",
validator.address,
&validator.ed25519_pubkey_hex[..16]
);
println!();
println!("Validator key saved to: {}", validator_key_path.display());
println!();
println!("Next steps:");
println!();
println!(" 1. Start the node:");
println!(" cipherd start --home {}", home.display());
println!();
println!(" 2. (Optional) For joining an existing network, replace the genesis file:");
println!(" {}", genesis_path.display());
Ok(())
}
async fn cmd_start(
config_path: PathBuf,
genesis_override: Option<PathBuf>,
keyring_backend_override: Option<KeyringBackendArg>,
) -> Result<()> {
use cipherbft_crypto::{Keyring, KeyringBackend};
if !config_path.exists() {
anyhow::bail!(
"Configuration file not found: {}\nRun 'cipherd init' first to create configuration.",
config_path.display()
);
}
info!("Loading configuration from {}", config_path.display());
let mut config = NodeConfig::load(&config_path)?;
// Derive home directory from config path (config_path is typically {home}/config/node.json)
let home = config_path
.parent() // config/
.and_then(|p| p.parent()) // home/
.ok_or_else(|| anyhow::anyhow!("Cannot determine home directory from config path"))?;
// Load client config (Cosmos SDK style) for keyring settings
let client_config = cipherd::ClientConfig::load(home)?;
// Determine keyring backend: CLI flag > node.json > client.toml > default
let keyring_backend: KeyringBackend = if let Some(backend_arg) = keyring_backend_override {
// CLI flag takes precedence
backend_arg.into()
} else {
// Prefer node.json keyring_backend, fall back to client.toml
let keyring_backend_str = config.effective_keyring_backend();
keyring_backend_str
.parse()
.map_err(|_| anyhow::anyhow!("Invalid keyring backend: {}", keyring_backend_str))?
};
// Warn if using non-production backend
if !keyring_backend.is_production_safe() {
eprintln!(
"WARNING: Using '{}' backend which is NOT safe for production!",
keyring_backend
);
}
// Get keys directory: node.json keystore_dir > client.toml > default
// This allows devnet init-files to set keystore_dir in node.json
let keys_dir = if config.keystore_dir.is_some() {
config.effective_keystore_dir()
} else {
client_config.effective_keyring_dir(home)
};
// Use key_name from node.json
let key_name = config.effective_key_name();
let account = config.effective_keystore_account();
info!(
"Loading keys from {} (backend: {}, key: {})",
keys_dir.display(),
keyring_backend,
key_name
);
// Create keyring
let keyring = Keyring::new(keyring_backend, &keys_dir)
.map_err(|e| anyhow::anyhow!("Failed to initialize keyring: {}", e))?;
// Key names follow the pattern: {key_name}_{account}_{type}
let ed25519_key_name = format!("{}_{}_ed25519", key_name, account);
let bls_key_name = format!("{}_{}_bls", key_name, account);
// Check if keys exist
if !keyring.key_exists(&ed25519_key_name) {
anyhow::bail!(
"Ed25519 key '{}' not found.\n\
Run 'cipherd keys add {} --validator' to create keys.",
ed25519_key_name,
key_name
);
}
if !keyring.key_exists(&bls_key_name) {
anyhow::bail!(
"BLS key '{}' not found.\n\
Validators require both Ed25519 and BLS keys.\n\
Run 'cipherd keys add {} --validator' to create keys.",
bls_key_name,
key_name
);
}
// Get passphrase if required by the backend
let passphrase = if keyring_backend.requires_passphrase() {
Some(
rpassword::prompt_password("Enter keystore passphrase: ")
.context("Failed to read passphrase")?,
)
} else {
None
};
// Load Ed25519 key
info!("Loading Ed25519 key: {}", ed25519_key_name);
let ed25519_secret_bytes = keyring
.get_key(&ed25519_key_name, passphrase.as_deref())
.map_err(|e| anyhow::anyhow!("Failed to load Ed25519 key: {}", e))?;
let ed25519_bytes: [u8; 32] = ed25519_secret_bytes
.expose_secret()
.as_slice()
.try_into()
.map_err(|_| anyhow::anyhow!("Invalid Ed25519 key length, expected 32 bytes"))?;
let ed25519_secret = Ed25519SecretKey::from_bytes(&ed25519_bytes);
let ed25519_keypair = Ed25519KeyPair::from_secret_key(ed25519_secret);
// Load BLS key
info!("Loading BLS key: {}", bls_key_name);
let bls_secret_bytes = keyring
.get_key(&bls_key_name, passphrase.as_deref())
.map_err(|e| anyhow::anyhow!("Failed to load BLS key: {}", e))?;
let bls_bytes: [u8; 32] = bls_secret_bytes
.expose_secret()
.as_slice()
.try_into()
.map_err(|_| anyhow::anyhow!("Invalid BLS key length, expected 32 bytes"))?;
let bls_secret = BlsSecretKey::from_bytes(&bls_bytes)
.map_err(|e| anyhow::anyhow!("Invalid BLS key: {:?}", e))?;
let bls_keypair = BlsKeyPair::from_secret_key(bls_secret);
// Derive validator ID from Ed25519 public key (consistent with genesis)
let validator_id = ed25519_keypair.public_key.validator_id();
info!("Derived validator ID: {:?}", validator_id);
// Override genesis path if provided via CLI
if genesis_override.is_some() {
config.genesis_path = genesis_override;
}
// Resolve and load genesis file
let genesis_path = config.effective_genesis_path();
info!("Loading genesis from {}", genesis_path.display());
let genesis = GenesisLoader::load_and_validate(&genesis_path)?;
info!("Starting node as validator {:?}", validator_id);
// Create node with keypairs, enable execution layer, and bootstrap validators from genesis
let mut node = Node::new(config, bls_keypair, ed25519_keypair)?
.with_execution_layer_from_genesis(&genesis)?;
node.bootstrap_validators_from_genesis(&genesis)?;
// Create a supervisor for structured task management and graceful shutdown
let supervisor = NodeSupervisor::new();
// Set up signal handling for graceful shutdown
let shutdown_supervisor = supervisor.clone();
tokio::spawn(async move {
if let Err(e) = tokio::signal::ctrl_c().await {
tracing::error!("Failed to listen for Ctrl+C: {}", e);
return;
}
info!("Received Ctrl+C, initiating graceful shutdown...");
if let Err(e) = shutdown_supervisor.shutdown().await {
tracing::warn!("Shutdown warning: {}", e);
}
});
// Run node with the supervisor for coordinated task management
node.run_with_supervisor(supervisor).await?;
Ok(())
}
async fn cmd_testnet(command: TestnetCommands) -> Result<()> {
match command {
TestnetCommands::InitFiles {
validators,
output,
chain_id,
network_id,
initial_stake_eth,
initial_balance_eth,
starting_port,
extra_alloc,
} => cmd_testnet_init_files(
validators,
&output,
chain_id,
&network_id,
initial_stake_eth,
initial_balance_eth,
starting_port,
extra_alloc,
),
TestnetCommands::Start {
validators,
duration,
} => cmd_testnet_start(validators, duration).await,
}
}
#[allow(clippy::too_many_arguments)]
fn cmd_testnet_init_files(
num_validators: usize,
output: &std::path::Path,
chain_id: u64,
network_id: &str,
initial_stake_eth: u64,
initial_balance_eth: u64,
starting_port: u16,
extra_alloc: Vec<String>,
) -> Result<()> {
use alloy_primitives::Address;
use cipherd::PeerConfig;
println!(
"Generating testnet configuration for {} validators...",
num_validators
);
println!();
std::fs::create_dir_all(output)?;
// Parse extra alloc entries
let mut extra_alloc_parsed: Vec<(Address, U256)> = Vec::new();
for entry in &extra_alloc {
let parts: Vec<&str> = entry.split(':').collect();
if parts.len() != 2 {
anyhow::bail!(
"Invalid extra-alloc format: '{}'. Expected address:balance_eth",
entry
);
}
let address: Address = parts[0]
.parse()
.map_err(|_| anyhow::anyhow!("Invalid address in extra-alloc: {}", parts[0]))?;
let balance_eth: u64 = parts[1].parse().map_err(|_| {
anyhow::anyhow!(
"Invalid balance in extra-alloc: {}. Expected integer ETH value",
parts[1]
)
})?;
let balance_wei = U256::from(balance_eth) * U256::from(1_000_000_000_000_000_000u128);
extra_alloc_parsed.push((address, balance_wei));
}
// Generate genesis with validators - this is our single source of truth for keys
let eth_to_wei = U256::from(1_000_000_000_000_000_000u128);
let initial_stake = U256::from(initial_stake_eth) * eth_to_wei;
let initial_balance = U256::from(initial_balance_eth) * eth_to_wei;
let genesis_config = GenesisGeneratorConfig {
num_validators,
chain_id,
network_id: network_id.to_string(),
initial_stake,
initial_balance,
extra_alloc: extra_alloc_parsed,
..Default::default()
};
let mut rng = rand::thread_rng();
let genesis_result = GenesisGenerator::generate(&mut rng, genesis_config)?;
// Write shared genesis file
let genesis_path = output.join("genesis.json");
let genesis_json = genesis_result.genesis.to_json()?;
std::fs::write(&genesis_path, genesis_json)?;
println!(" Created shared genesis: {}", genesis_path.display());
// Build peer configs from genesis validators (same keys as genesis)
let peer_configs: Vec<PeerConfig> = genesis_result
.validators
.iter()
.enumerate()
.map(|(i, v)| {
let port_offset = starting_port + (i as u16 * 10);
PeerConfig {
validator_id: hex::encode(v.validator_id.as_bytes()),
bls_public_key_hex: v.bls_pubkey_hex.clone(),
ed25519_public_key_hex: v.ed25519_pubkey_hex.clone(),
primary_addr: format!("127.0.0.1:{}", port_offset).parse().unwrap(),
consensus_addr: format!("127.0.0.1:{}", port_offset + 5).parse().unwrap(),
worker_addrs: vec![format!("127.0.0.1:{}", port_offset + 1).parse().unwrap()],
}
})
.collect();
// Create directories and configs for each node using genesis validators
for (i, validator) in genesis_result.validators.iter().enumerate() {
let node_dir = output.join(format!("node{}", i));
let config_dir = node_dir.join("config");
let data_dir = node_dir.join("data");
let keys_dir = node_dir.join("keys");
std::fs::create_dir_all(&config_dir)?;
std::fs::create_dir_all(&data_dir)?;
std::fs::create_dir_all(&keys_dir)?;
let port_offset = starting_port + (i as u16 * 10);
let key_name = format!("validator-{}", i);
let account = 0u32;
// Store keys in the node's keyring using "test" backend (no passphrase for devnet)
let keyring = Keyring::new(KeyringBackend::Test, &keys_dir)
.map_err(|e| anyhow::anyhow!("Failed to create keyring: {}", e))?;
// Key names follow the pattern: {key_name}_{account}_{type}
let ed25519_key_name = format!("{}_{}_ed25519", key_name, account);
let bls_key_name = format!("{}_{}_bls", key_name, account);
// Store Ed25519 key
let ed25519_secret = hex::decode(validator.ed25519_secret_hex.clone().unwrap_or_default())
.map_err(|e| anyhow::anyhow!("Invalid ed25519 secret hex: {}", e))?;
let ed25519_metadata =
KeyMetadata::new(&ed25519_key_name, "ed25519", &validator.ed25519_pubkey_hex)
.with_description(&format!("Devnet validator {} Ed25519 key", i));
keyring
.store_key(&ed25519_metadata, &ed25519_secret, None)
.map_err(|e| anyhow::anyhow!("Failed to store Ed25519 key: {}", e))?;
// Store BLS key
let bls_secret = hex::decode(validator.bls_secret_hex.clone().unwrap_or_default())
.map_err(|e| anyhow::anyhow!("Invalid BLS secret hex: {}", e))?;
let bls_metadata = KeyMetadata::new(&bls_key_name, "bls12-381", &validator.bls_pubkey_hex)
.with_description(&format!("Devnet validator {} BLS key", i));
keyring
.store_key(&bls_metadata, &bls_secret, None)
.map_err(|e| anyhow::anyhow!("Failed to store BLS key: {}", e))?;
// Build node config using the SAME validator ID as in genesis
// Use "test" backend for devnet (no passphrase required)
let node_config = NodeConfig {
validator_id: Some(validator.validator_id),
keyring_backend: "test".to_string(),
key_name: key_name.clone(),
keystore_dir: Some(keys_dir.clone()),
keystore_account: Some(account),
primary_listen: format!("0.0.0.0:{}", port_offset).parse()?,
consensus_listen: format!("0.0.0.0:{}", port_offset + 5).parse()?,
worker_listens: vec![format!("0.0.0.0:{}", port_offset + 1).parse()?],
// Add all other validators as peers
peers: peer_configs
.iter()
.enumerate()
.filter(|(j, _)| *j != i)
.map(|(_, p)| p.clone())
.collect(),
num_workers: 1,
home_dir: Some(node_dir.clone()),
data_dir: data_dir.clone(),
genesis_path: Some(genesis_path.clone()),
car_interval_ms: 100,
max_batch_txs: 100,
max_batch_bytes: 1024 * 1024,
rpc_enabled: true,
// Each validator gets HTTP and WS ports spaced by 10 to avoid conflicts
rpc_http_port: cipherd::DEFAULT_RPC_HTTP_PORT + (i as u16 * 10),
rpc_ws_port: cipherd::DEFAULT_RPC_WS_PORT + (i as u16 * 10),
metrics_port: cipherd::DEFAULT_METRICS_PORT + (i as u16 * 10),
sync: cipherd::SyncConfig::default(),
};
let config_path = config_dir.join("node.json");
node_config.save(&config_path)?;
println!(
" Created node{} (validator {:?}, port {})",
i, validator.validator_id, port_offset
);
}
// Write validator key files
let keys_dir = output.join("keys");
std::fs::create_dir_all(&keys_dir)?;
for (i, validator) in genesis_result.validators.iter().enumerate() {
let key_file = ValidatorKeyFile::from_generated(i, validator);
let key_path = keys_dir.join(format!("validator-{}.json", i));
let key_json = key_file.to_json()?;
std::fs::write(&key_path, key_json)?;
}
println!(