-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnode.rs
More file actions
2159 lines (1967 loc) · 99.9 KB
/
node.rs
File metadata and controls
2159 lines (1967 loc) · 99.9 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
//! Node runner - ties Primary, Workers, and Network together
//!
//! # Task Supervision
//!
//! The node uses a [`NodeSupervisor`] for structured task management:
//! - All background tasks are tracked and can be cancelled gracefully
//! - Shutdown follows a specific order to ensure clean state
//! - Critical task failures trigger coordinated shutdown
//!
//! # Shutdown Order
//!
//! 1. Stop accepting new network connections
//! 2. Drain in-flight consensus rounds (via cancellation signal)
//! 3. Flush pending storage writes
//! 4. Close database connections
//! 5. Exit
use crate::config::NodeConfig;
use crate::execution_bridge::{BlockExecutionResult, ExecutionBridge};
use crate::execution_sync::{ExecutionSyncConfig, ExecutionSyncTracker, SyncAction};
use crate::network::{TcpPrimaryNetwork, TcpWorkerNetwork};
use crate::supervisor::NodeSupervisor;
use alloy_primitives::{Address, B256};
use anyhow::{Context, Result};
use cipherbft_consensus::{
create_context, default_consensus_params, default_engine_config_single_part, spawn_host,
spawn_network, spawn_sync, spawn_wal, ConsensusHeight, ConsensusSigner,
ConsensusSigningProvider, ConsensusValidator, EpochConfig, MalachiteEngineBuilder, SyncConfig,
};
use cipherbft_crypto::{BlsKeyPair, BlsPublicKey, Ed25519KeyPair, Ed25519PublicKey};
use cipherbft_data_chain::{
error::DclError,
primary::{Primary, PrimaryConfig, PrimaryEvent},
storage::BatchStore as DclBatchStore,
worker::{Worker, WorkerConfig},
Batch, Cut, DclMessage, WorkerMessage,
};
use cipherbft_execution::{
keccak256, Bytes as ExecutionBytes, ChainConfig, Log as ExecutionLog,
TransactionReceipt as ExecutionReceipt, U256,
};
use cipherbft_storage::{
Block, BlockStore, Database, DatabaseConfig, DclStore, Log as StorageLog, LogStore,
MdbxBlockStore, MdbxDclStore, MdbxLogStore, MdbxReceiptStore, MdbxTransactionStore,
Receipt as StorageReceipt, ReceiptStore, StoredLog, Transaction as StorageTransaction,
TransactionStore,
};
use cipherbft_types::genesis::{AttestationQuorum, Genesis};
use cipherbft_types::Hash;
use cipherbft_types::ValidatorId;
use informalsystems_malachitebft_metrics::SharedRegistry;
use informalsystems_malachitebft_network::{
Config as NetworkConfig, DiscoveryConfig, GossipSubConfig, Keypair, Multiaddr, PubSubProtocol,
TransportProtocol,
};
use std::collections::HashMap;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::mpsc;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, trace, warn};
use cipherbft_metrics;
/// Adapter to bridge DclStore (storage crate) to BatchStore (data-chain crate)
///
/// Workers require `BatchStore` from data-chain, but the node uses `DclStore` from storage.
/// This adapter wraps `DclStore` and implements the `BatchStore` trait, allowing Workers
/// to persist batches to the same storage used by `ExecutionBridge` for fetching transactions.
///
/// Without this adapter, batches created by Workers would only exist in memory and would
/// not be retrievable when executing Cuts (causing transactions to be skipped).
struct DclStoreBatchAdapter {
inner: Arc<dyn DclStore>,
}
impl DclStoreBatchAdapter {
fn new(store: Arc<dyn DclStore>) -> Self {
Self { inner: store }
}
}
#[async_trait::async_trait]
impl DclBatchStore for DclStoreBatchAdapter {
async fn put_batch(&self, batch: Batch) -> Result<Hash, DclError> {
let hash = batch.hash();
self.inner
.put_batch(batch)
.await
.map_err(|e| DclError::Storage(e.to_string()))?;
Ok(hash)
}
async fn get_batch(&self, hash: &Hash) -> Result<Option<Batch>, DclError> {
self.inner
.get_batch(hash)
.await
.map_err(|e| DclError::Storage(e.to_string()))
}
async fn has_batch(&self, hash: &Hash) -> Result<bool, DclError> {
self.inner
.has_batch(hash)
.await
.map_err(|e| DclError::Storage(e.to_string()))
}
}
/// Validator public key information for both DCL and Consensus layers
#[derive(Clone, Debug)]
pub struct ValidatorInfo {
/// BLS public key for DCL layer (threshold signatures)
pub bls_public_key: BlsPublicKey,
/// Ed25519 public key for Consensus layer (Malachite signing)
pub ed25519_public_key: Ed25519PublicKey,
/// Voting power for consensus
pub voting_power: u64,
/// Ethereum address (secp256k1) for block beneficiary
pub ethereum_address: Address,
}
impl ValidatorInfo {
/// Create a new validator info with default voting power
pub fn new(bls_public_key: BlsPublicKey, ed25519_public_key: Ed25519PublicKey) -> Self {
Self {
bls_public_key,
ed25519_public_key,
voting_power: 100, // Default voting power
ethereum_address: Address::ZERO,
}
}
/// Create with custom voting power
pub fn with_voting_power(
bls_public_key: BlsPublicKey,
ed25519_public_key: Ed25519PublicKey,
voting_power: u64,
) -> Self {
Self {
bls_public_key,
ed25519_public_key,
voting_power,
ethereum_address: Address::ZERO,
}
}
/// Create validator info with voting power and ethereum address
pub fn with_ethereum_address(
bls_public_key: BlsPublicKey,
ed25519_public_key: Ed25519PublicKey,
voting_power: u64,
ethereum_address: Address,
) -> Self {
Self {
bls_public_key,
ed25519_public_key,
voting_power,
ethereum_address,
}
}
}
/// Default gas limit for blocks (30 million)
const DEFAULT_GAS_LIMIT: u64 = 30_000_000;
/// A running CipherBFT node
pub struct Node {
/// Configuration
config: NodeConfig,
/// BLS keypair for DCL layer
bls_keypair: BlsKeyPair,
/// Ed25519 keypair for consensus layer
ed25519_keypair: Ed25519KeyPair,
/// Our validator ID
validator_id: ValidatorId,
/// Known validators with both BLS and Ed25519 public keys
validators: HashMap<ValidatorId, ValidatorInfo>,
/// Execution layer bridge
execution_bridge: Option<Arc<ExecutionBridge>>,
/// Shared DCL store for consensus sync and execution bridge.
/// When set to MdbxDclStore, enables persistent certificate storage for sync support.
dcl_store: Option<Arc<dyn DclStore>>,
/// Whether DCL (Data Chain Layer) is enabled.
/// When disabled, consensus proceeds without data availability attestations.
dcl_enabled: bool,
/// Epoch block reward in wei (from genesis staking params).
/// Used for validator reward distribution at epoch boundaries.
epoch_block_reward: U256,
/// Block beneficiary address (coinbase) from genesis.
/// This is the address that receives block rewards.
beneficiary: [u8; 20],
/// Block gas limit from genesis configuration.
gas_limit: u64,
/// Attestation quorum for DCL Cars (from genesis).
/// Determines how many validators must attest before a Car can be included.
attestation_quorum: AttestationQuorum,
}
impl Node {
/// Create a new node with provided keypairs
///
/// # Arguments
///
/// * `config` - Node configuration
/// * `bls_keypair` - BLS keypair for DCL layer (threshold signatures)
/// * `ed25519_keypair` - Ed25519 keypair for consensus layer (Malachite signing)
pub fn new(
config: NodeConfig,
bls_keypair: BlsKeyPair,
ed25519_keypair: Ed25519KeyPair,
) -> Result<Self> {
// Derive validator ID from Ed25519 public key (matches genesis)
let validator_id = ed25519_keypair.public_key.validator_id();
// Verify validator ID matches if configured
if let Some(config_vid) = config.validator_id {
if validator_id != config_vid {
anyhow::bail!(
"Validator ID mismatch: config has {:?}, derived {:?}",
config_vid,
validator_id
);
}
}
Ok(Self {
config,
bls_keypair,
ed25519_keypair,
validator_id,
validators: HashMap::new(),
execution_bridge: None,
dcl_store: None,
dcl_enabled: true, // Default to enabled, overridden by genesis
epoch_block_reward: U256::from(2_000_000_000_000_000_000u128), // Default: 2 CPH
gas_limit: DEFAULT_GAS_LIMIT, // Default, overridden by genesis
beneficiary: [0u8; 20], // Default zero, overridden by genesis
attestation_quorum: AttestationQuorum::default(), // Default 2f+1, overridden by genesis
})
}
/// Add a known validator with both BLS and Ed25519 public keys
pub fn add_validator(
&mut self,
id: ValidatorId,
bls_pubkey: BlsPublicKey,
ed25519_pubkey: Ed25519PublicKey,
) {
self.validators
.insert(id, ValidatorInfo::new(bls_pubkey, ed25519_pubkey));
}
/// Add a known validator with custom voting power
pub fn add_validator_with_power(
&mut self,
id: ValidatorId,
bls_pubkey: BlsPublicKey,
ed25519_pubkey: Ed25519PublicKey,
voting_power: u64,
) {
self.validators.insert(
id,
ValidatorInfo::with_voting_power(bls_pubkey, ed25519_pubkey, voting_power),
);
}
/// Bootstrap validators from genesis file (T029).
///
/// Parses validator public keys from genesis and adds them to the node's
/// validator set with voting power derived from staked amounts.
///
/// # Arguments
///
/// * `genesis` - Validated genesis configuration
///
/// # Errors
///
/// Returns an error if:
/// - Ed25519 public key parsing fails (invalid hex or length)
/// - BLS public key parsing fails (invalid hex or length)
pub fn bootstrap_validators_from_genesis(&mut self, genesis: &Genesis) -> Result<()> {
let total_stake = genesis.total_staked();
info!(
"Bootstrapping {} validators from genesis (total stake: {} wei)",
genesis.validator_count(),
total_stake
);
for validator in &genesis.cipherbft.validators {
// Parse Ed25519 public key (strip 0x prefix if present)
let ed25519_hex = validator.ed25519_pubkey.trim_start_matches("0x");
let ed25519_bytes = hex::decode(ed25519_hex).map_err(|e| {
anyhow::anyhow!(
"Invalid Ed25519 public key hex for {}: {}",
validator.address,
e
)
})?;
if ed25519_bytes.len() != 32 {
anyhow::bail!(
"Ed25519 public key for {} must be 32 bytes, got {}",
validator.address,
ed25519_bytes.len()
);
}
let mut ed25519_arr = [0u8; 32];
ed25519_arr.copy_from_slice(&ed25519_bytes);
let ed25519_pubkey = Ed25519PublicKey::from_bytes(&ed25519_arr).map_err(|e| {
anyhow::anyhow!(
"Invalid Ed25519 public key for {}: {:?}",
validator.address,
e
)
})?;
// Parse BLS public key (strip 0x prefix if present)
let bls_hex = validator.bls_pubkey.trim_start_matches("0x");
let bls_bytes = hex::decode(bls_hex).map_err(|e| {
anyhow::anyhow!(
"Invalid BLS public key hex for {}: {}",
validator.address,
e
)
})?;
if bls_bytes.len() != 48 {
anyhow::bail!(
"BLS public key for {} must be 48 bytes, got {}",
validator.address,
bls_bytes.len()
);
}
let mut bls_arr = [0u8; 48];
bls_arr.copy_from_slice(&bls_bytes);
let bls_pubkey = BlsPublicKey::from_bytes(&bls_arr).map_err(|e| {
anyhow::anyhow!("Invalid BLS public key for {}: {:?}", validator.address, e)
})?;
// Derive validator ID from Ed25519 public key (matches genesis)
let validator_id = ed25519_pubkey.validator_id();
// Calculate voting power from stake (proportional to total stake)
// Scale to reasonable voting power values (avoid overflow)
let voting_power = if total_stake.is_zero() {
100u64 // Default if no stake
} else {
// voting_power = (stake * 10000) / total_stake
// This gives voting power proportional to stake share
// with 10000 as the scaling factor for precision
let stake_u128: u128 = validator.staked_amount.try_into().unwrap_or(u128::MAX);
let total_u128: u128 = total_stake.try_into().unwrap_or(u128::MAX);
let power = (stake_u128.saturating_mul(10000)) / total_u128.max(1);
power.max(1) as u64 // Ensure at least 1 voting power
};
info!(
"Adding validator: genesis_address={}, derived_validator_id={}, ed25519_pubkey={}, voting_power={}",
validator.address, validator_id, validator.ed25519_pubkey, voting_power
);
self.validators.insert(
validator_id,
ValidatorInfo::with_ethereum_address(
bls_pubkey,
ed25519_pubkey,
voting_power,
validator.address, // This is the secp256k1 Ethereum address from genesis
),
);
}
info!(
"Bootstrapped {} validators from genesis",
self.validators.len()
);
// Set DCL enabled flag from genesis configuration
self.dcl_enabled = genesis.cipherbft.dcl.enabled;
if !self.dcl_enabled {
info!("DCL (Data Chain Layer) is DISABLED - consensus will proceed without data availability attestations");
}
// Set attestation quorum from genesis DCL params
self.attestation_quorum = genesis.cipherbft.dcl.attestation_quorum;
info!(
"Attestation quorum set from genesis: {:?}",
self.attestation_quorum
);
// Set beneficiary address from genesis coinbase (if specified)
if let Some(coinbase) = genesis.coinbase {
self.beneficiary = coinbase.0 .0;
info!("Block beneficiary set from genesis: {}", coinbase);
}
// Set gas limit from genesis
self.gas_limit = genesis.gas_limit.try_into().unwrap_or(DEFAULT_GAS_LIMIT);
info!("Block gas limit set from genesis: {}", self.gas_limit);
Ok(())
}
/// Enable execution layer integration
///
/// Must be called before `run()` to enable Cut execution.
///
/// # Note
/// This creates an execution layer with an in-memory DCL store (for testing),
/// but uses persistent MDBX storage for EVM state in the node's data directory.
/// For production use, prefer `with_execution_layer_from_genesis` to
/// initialize the staking state from the genesis file and enable
/// persistent storage for consensus sync support.
pub fn with_execution_layer(mut self) -> Result<Self> {
use cipherbft_storage::InMemoryStore;
let chain_config = ChainConfig::default();
let dcl_store: Arc<dyn DclStore> = Arc::new(InMemoryStore::new());
self.dcl_store = Some(dcl_store.clone());
// Ensure data directory exists for EVM storage
std::fs::create_dir_all(&self.config.data_dir)?;
let bridge = ExecutionBridge::new(chain_config, dcl_store, &self.config.data_dir)?;
self.execution_bridge = Some(Arc::new(bridge));
Ok(self)
}
/// Enable execution layer integration with genesis validators.
///
/// This is the preferred method for production use. It initializes the
/// staking precompile with the validator set from the genesis file,
/// ensuring validators are correctly registered on node startup.
///
/// Creates a persistent MdbxDclStore for DCL data and consensus certificates.
/// The same store is shared between the ExecutionBridge and the consensus sync
/// mechanism, enabling validators to sync from height 1.
///
/// # Arguments
///
/// * `genesis` - Validated genesis configuration
///
/// # Example
///
/// ```rust,ignore
/// let genesis = GenesisLoader::load_and_validate(path)?;
/// let node = Node::new(config, bls_keypair, ed25519_keypair)?
/// .with_execution_layer_from_genesis(&genesis)?;
/// ```
pub fn with_execution_layer_from_genesis(mut self, genesis: &Genesis) -> Result<Self> {
let chain_config = ChainConfig::default();
// Create persistent DCL store using MDBX for production use.
// This enables consensus sync support by persisting Cut + CommitCertificate pairs.
std::fs::create_dir_all(&self.config.data_dir)?;
let dcl_db_path = self.config.data_dir.join("dcl_storage");
let dcl_db_config = DatabaseConfig::new(&dcl_db_path);
let dcl_database =
Database::open(dcl_db_config).context("Failed to open DCL storage database")?;
let dcl_store: Arc<dyn DclStore> = Arc::new(MdbxDclStore::new(Arc::new(dcl_database)));
info!("Created persistent DCL store at {}", dcl_db_path.display());
// Store the dcl_store for later use in spawn_host (consensus sync)
self.dcl_store = Some(dcl_store.clone());
let bridge =
ExecutionBridge::from_genesis(chain_config, dcl_store, genesis, &self.config.data_dir)?;
self.execution_bridge = Some(Arc::new(bridge));
// Store epoch block reward from genesis for reward distribution at epoch boundaries
self.epoch_block_reward = genesis.cipherbft.staking.epoch_block_reward_wei;
info!(
"Execution layer initialized with {} validators from genesis (epoch reward: {} wei)",
genesis.validator_count(),
self.epoch_block_reward
);
Ok(self)
}
/// Run the node with a default supervisor.
///
/// Creates a new [`NodeSupervisor`] and runs the node until shutdown is triggered
/// (e.g., via Ctrl+C signal).
pub async fn run(self) -> Result<()> {
let supervisor = NodeSupervisor::new();
self.run_with_supervisor(supervisor).await
}
/// Run the node with a provided supervisor.
///
/// This allows external control over task supervision, useful for:
/// - Testing with custom shutdown timing
/// - Coordinating multiple nodes in a single process
/// - Custom shutdown ordering
///
/// # Arguments
///
/// * `supervisor` - The supervisor that manages task lifecycle
pub async fn run_with_supervisor(self, supervisor: NodeSupervisor) -> Result<()> {
info!("Starting node with validator ID: {:?}", self.validator_id);
// Initialize and start metrics server
cipherbft_metrics::init();
let metrics_addr: std::net::SocketAddr = format!("0.0.0.0:{}", self.config.metrics_port)
.parse()
.expect("valid metrics address");
let _metrics_handle = cipherbft_metrics::spawn_metrics_server(metrics_addr);
tracing::info!(
"Metrics server started on port {}",
self.config.metrics_port
);
// Create data directory if needed
std::fs::create_dir_all(&self.config.data_dir)?;
// Get cancellation token for graceful shutdown
let cancel_token = supervisor.cancellation_token();
// Create channel for CutReady events to Consensus Host
let (cut_tx, cut_rx) = mpsc::channel::<Cut>(100);
// Create channels for Primary (only used when DCL enabled)
let (primary_incoming_tx, mut primary_incoming_rx) =
mpsc::channel::<(ValidatorId, DclMessage)>(1000);
// Create channel to signal empty cut sender to advance (used when DCL disabled)
// This creates a lockstep between consensus decisions and cut generation
let (cut_advance_tx, mut cut_advance_rx) = mpsc::channel::<()>(1);
// Conditionally spawn DCL (Data Chain Layer) based on genesis config
// When disabled, we bypass DCL and send empty cuts directly to consensus
let mut primary_handle_opt: Option<cipherbft_data_chain::primary::PrimaryHandle> = None;
// Store reference to primary network for RPC NetworkApi
let mut primary_network_opt: Option<Arc<TcpPrimaryNetwork>> = None;
// Transaction channel sender for RPC -> Worker forwarding (created when DCL enabled)
let mut mempool_tx_sender_opt: Option<mpsc::Sender<Vec<u8>>> = None;
if self.dcl_enabled {
// Create primary network
let primary_network = Arc::new(TcpPrimaryNetwork::new(
self.validator_id,
&self.config.peers,
primary_incoming_tx.clone(),
));
// Store reference for RPC NetworkApi before moving into adapter
primary_network_opt = Some(Arc::clone(&primary_network));
// Start primary listener
Arc::clone(&primary_network)
.start_listener(self.config.primary_listen)
.await
.with_context(|| {
format!(
"Failed to start primary network listener on {}",
self.config.primary_listen
)
})?;
// Connect to peers (with retry) - supervised task
supervisor.spawn_cancellable("peer-connector", {
let network = Arc::clone(&primary_network);
move |token| async move {
// Initial delay to let other nodes start
tokio::time::sleep(Duration::from_secs(1)).await;
loop {
tokio::select! {
biased;
_ = token.cancelled() => {
info!("Peer connector shutting down");
break;
}
_ = tokio::time::sleep(Duration::from_secs(5)) => {
network.connect_to_all_peers().await;
}
}
}
Ok(())
}
});
// Create Primary configuration
// For devnet, allow unlimited empty cars so consensus can make progress without real transactions
let primary_config =
PrimaryConfig::new(self.validator_id, self.bls_keypair.secret_key.clone())
.with_car_interval(Duration::from_millis(self.config.car_interval_ms))
.with_max_empty_cars(u32::MAX)
.with_attestation_quorum(self.attestation_quorum);
// Extract BLS public keys for DCL layer (Primary uses BLS for threshold signatures)
let bls_pubkeys: HashMap<ValidatorId, BlsPublicKey> = self
.validators
.iter()
.map(|(id, info)| (*id, info.bls_public_key.clone()))
.collect();
// Log all known validators for debugging
info!(
"Primary will know {} validators: {:?}",
bls_pubkeys.len(),
bls_pubkeys.keys().collect::<Vec<_>>()
);
// Load the last finalized cut for Primary state restoration on restart
// This is CRITICAL for validator restart: without it, a restarted validator
// would create CARs at position 0, but other validators expect continuity
// from the last finalized position, causing PositionGap errors.
let initial_cut = if let Some(ref store) = self.dcl_store {
match store.get_latest_finalized_cut().await {
Ok(Some(cut)) => {
info!(
"Restoring Primary state from finalized cut at height {} with {} validators",
cut.height,
cut.cars.len()
);
Some(cut)
}
Ok(None) => {
info!("No finalized cut in storage, Primary starting fresh");
None
}
Err(e) => {
warn!(
"Failed to load finalized cut for Primary restart: {}, starting fresh",
e
);
None
}
}
} else {
debug!("No DCL store available, Primary starting without state restoration");
None
};
// Spawn Primary task with optional initial cut for restart recovery
let (primary_handle, worker_rxs) = Primary::spawn_with_initial_cut(
primary_config,
bls_pubkeys,
Box::new(TcpPrimaryNetworkAdapter {
network: primary_network,
}),
self.config.num_workers as u8,
None, // storage - not used for now
initial_cut,
);
// Create transaction channel for RPC -> Worker forwarding
// This channel is used by ChannelMempoolApi to send transactions to workers
let (mempool_tx_sender, mempool_tx_receiver) = mpsc::channel::<Vec<u8>>(4096);
mempool_tx_sender_opt = Some(mempool_tx_sender);
// Wrap receiver in Option so we can move it into worker 0's bridge
let mut mempool_tx_receiver_opt = Some(mempool_tx_receiver);
// Create batch storage adapter for Workers to persist batches
// This is CRITICAL: Workers must use the same storage as ExecutionBridge
// so that batches can be retrieved when executing Cuts.
let worker_batch_storage: Option<Arc<dyn DclBatchStore>> = self
.dcl_store
.clone()
.map(|store| Arc::new(DclStoreBatchAdapter::new(store)) as Arc<dyn DclBatchStore>);
// Spawn Workers and wire up channels
// Workers receive batches from peers and notify Primary when batches are ready
for (worker_idx, mut from_primary_rx) in worker_rxs.into_iter().enumerate() {
let worker_id = worker_idx as u8;
// Create Worker network with incoming message channel
let (worker_incoming_tx, mut worker_incoming_rx) =
mpsc::channel::<(ValidatorId, WorkerMessage)>(1024);
let worker_network = TcpWorkerNetwork::new(
self.validator_id,
worker_id,
&self.config.peers,
worker_incoming_tx,
);
// Start Worker network listener
if let Some(listen_addr) = self.config.worker_listens.get(worker_id as usize) {
let network_for_listener = Arc::new(worker_network.clone());
let listen_addr = *listen_addr;
tokio::spawn(async move {
if let Err(e) = network_for_listener.start_listener(listen_addr).await {
error!("Failed to start worker {} listener: {}", worker_id, e);
}
});
// Connect to peers after a brief delay to allow listeners to start
let network_for_connect = worker_network.clone();
tokio::spawn(async move {
tokio::time::sleep(Duration::from_millis(500)).await;
network_for_connect.connect_to_all_peers().await;
});
}
// Create Worker config and spawn with batch storage
// Passing the storage adapter ensures batches are persisted and retrievable
// during Cut execution (for transaction inclusion in blocks)
//
// IMPORTANT: flush_interval (50ms) must be shorter than Primary's car_interval (100ms)
// to ensure batches are flushed before Cars are created. Without this, there's a race
// condition where Primary creates empty Cars before Worker flushes pending batches.
let worker_config = WorkerConfig::new(self.validator_id, worker_id)
.with_flush_interval(std::time::Duration::from_millis(50))
.with_max_batch_txs(self.config.max_batch_txs)
.with_max_batch_bytes(self.config.max_batch_bytes);
let mut worker_handle = Worker::spawn_with_storage(
worker_config,
Box::new(worker_network),
worker_batch_storage.clone(),
);
// Combined bridge task: handles all communication with Worker
// - Primary -> Worker: forward batch requests
// - Worker -> Primary: forward batch digests
// - Network -> Worker: forward peer messages
// - RPC -> Worker: forward mempool transactions (worker 0 only)
let token = cancel_token.clone();
let primary_worker_sender = primary_handle.worker_sender();
// Worker 0 handles RPC transactions from the mempool channel
let mempool_rx = if worker_id == 0 {
mempool_tx_receiver_opt.take()
} else {
None
};
tokio::spawn(async move {
// Move mempool_rx into the async block
let mut mempool_rx = mempool_rx;
info!(
"Worker {} bridge started (mempool_rx: {})",
worker_id,
if mempool_rx.is_some() {
"enabled"
} else {
"disabled"
}
);
loop {
// Use a macro-like pattern to handle optional mempool receiver
// Worker 0 has mempool_rx, others don't
tokio::select! {
biased;
_ = token.cancelled() => {
debug!("Worker {} bridge shutting down", worker_id);
break;
}
// RPC -> Worker: forward mempool transactions (worker 0 only)
tx = async {
match &mut mempool_rx {
Some(rx) => rx.recv().await,
None => std::future::pending().await,
}
} => {
if let Some(tx_bytes) = tx {
trace!("Worker {} received transaction from RPC mempool ({} bytes)", worker_id, tx_bytes.len());
if worker_handle.submit_transaction(tx_bytes).await.is_err() {
warn!("Worker {} submit_transaction failed", worker_id);
// Don't break - continue processing other messages
} else {
trace!("Worker {} forwarded transaction to batch maker", worker_id);
}
}
}
// Primary -> Worker: forward batch requests and digests
msg = from_primary_rx.recv() => {
match msg {
Some(m) => {
if worker_handle.send_from_primary(m).await.is_err() {
warn!("Worker {} send_from_primary failed", worker_id);
break;
}
}
None => {
debug!("Worker {} primary channel closed", worker_id);
break;
}
}
}
// Worker -> Primary: forward batch availability notifications
msg = worker_handle.recv_from_worker() => {
match msg {
Some(m) => {
debug!("Worker {} bridge forwarding {:?} to Primary", worker_id, m);
if primary_worker_sender.send(m).await.is_err() {
warn!("Worker {} send to primary failed", worker_id);
break;
}
}
None => {
debug!("Worker {} receiver closed", worker_id);
break;
}
}
}
// Network -> Worker: forward peer messages (batches, sync requests)
msg = worker_incoming_rx.recv() => {
match msg {
Some((peer, worker_msg)) => {
if worker_handle.send_from_peer(peer, worker_msg).await.is_err() {
warn!("Worker {} send_from_peer failed", worker_id);
break;
}
}
None => {
debug!("Worker {} network channel closed", worker_id);
break;
}
}
}
}
}
});
info!("Worker {} spawned and wired", worker_id);
}
primary_handle_opt = Some(primary_handle);
info!(
"DCL layer spawned with Primary and {} workers",
self.config.num_workers
);
// Drop the cut_advance_rx receiver since it's only used when DCL is disabled.
// This ensures cut_advance_tx.send() fails immediately instead of blocking,
// preventing deadlock in the event loop.
drop(cut_advance_rx);
} else {
// DCL disabled: spawn a task that sends empty cuts directly to consensus
// This allows consensus to proceed without data availability attestations
// IMPORTANT: Cuts are sent in lockstep with consensus decisions to avoid
// the cut buffer filling up before consensus can use them
info!("DCL DISABLED - spawning empty cut sender for consensus bypass");
let cut_tx_bypass = cut_tx.clone();
supervisor.spawn_cancellable("empty-cut-sender", move |token| async move {
let mut height = 1u64;
// Send the first cut immediately at height 1
let empty_cut = Cut::new(height);
info!("Sending initial empty cut for height {}", height);
if let Err(e) = cut_tx_bypass.send(empty_cut).await {
warn!("Failed to send initial empty cut: {}", e);
return Ok(());
}
height += 1;
// After the first cut, wait for consensus to decide before sending the next
// This creates a lockstep: cut -> propose -> decide -> next cut
loop {
tokio::select! {
biased;
_ = token.cancelled() => {
info!("Empty cut sender shutting down");
break;
}
// Wait for signal that consensus decided, then send next cut
result = cut_advance_rx.recv() => {
match result {
Some(()) => {
let empty_cut = Cut::new(height);
info!("Sending empty cut for height {} (after consensus decision)", height);
if let Err(e) = cut_tx_bypass.send(empty_cut).await {
warn!("Failed to send empty cut: {}", e);
break;
}
height += 1;
}
None => {
info!("Cut advance channel closed, stopping empty cut sender");
break;
}
}
}
}
}
Ok(())
});
}
let (decided_tx, mut decided_rx) = mpsc::channel::<(ConsensusHeight, Cut)>(100);
// Get Ed25519 keypair for Consensus
let ed25519_pubkey = self.ed25519_keypair.public_key.clone();
// Extract secret key bytes before moving keypair (needed for libp2p Keypair)
let ed25519_secret_bytes = self.ed25519_keypair.secret_key.to_bytes();
let consensus_signer = ConsensusSigner::new(self.ed25519_keypair.clone());
let signing_provider = ConsensusSigningProvider::new(consensus_signer);
// Create Consensus context and validators
// Build validator set from all known validators using their Ed25519 public keys
// Chain ID: cipherbft-testnet-1 (Cosmos-style for consensus layer)
// Note: For EVM execution layer, use numeric chain ID 84530001
let chain_id = "cipherbft-testnet-1";
// Look up our own voting power from the validator set (set during bootstrap_validators_from_genesis)
// Fall back to 100 if not found (e.g., if bootstrap wasn't called)
let our_voting_power = self
.validators
.get(&self.validator_id)
.map(|info| info.voting_power)
.unwrap_or(100);
// Get our own ethereum address from the validator set (or use ZERO if not found)
let our_ethereum_address = self
.validators
.get(&self.validator_id)
.map(|info| info.ethereum_address)
.unwrap_or(Address::ZERO);
// Start with ourselves
let mut consensus_validators = vec![ConsensusValidator::new_with_ethereum_address(
self.validator_id,
ed25519_pubkey,
our_voting_power,
our_ethereum_address,
)];
// Add all other validators from the known validator set
for (validator_id, info) in &self.validators {
if *validator_id != self.validator_id {
consensus_validators.push(ConsensusValidator::new_with_ethereum_address(
*validator_id,
info.ed25519_public_key.clone(),
info.voting_power,
info.ethereum_address,
));
}
}
// Determine initial height from storage (for restart recovery)
// If we have persistent storage and there's a finalized cut, resume from that height + 1
let initial_height = if let Some(store) = &self.dcl_store {
match store.get_latest_finalized_cut().await {
Ok(Some(cut)) => {
let resume_height = cut.height + 1;
info!(
"Resuming consensus from height {} (latest finalized: {})",
resume_height, cut.height
);
Some(ConsensusHeight(resume_height))
}
Ok(None) => {
info!("No finalized cuts in storage, starting from height 1");
None
}
Err(e) => {
warn!(
"Failed to read latest finalized cut: {}, starting from height 1",
e
);
None
}
}
} else {
info!("No persistent DCL storage, starting consensus from height 1");
None
};
let ctx = create_context(chain_id, consensus_validators, initial_height)?;
// Find our own address in the sorted validator set by matching our validator ID.
// Note: The validator set is sorted by voting power (desc), then address (asc),
// so we cannot assume our position - we must search for ourselves.
let our_address = ctx
.validator_set()
.as_slice()
.iter()
.find(|v| v.address.0 == self.validator_id)
.expect("our validator must be in the validator set")
.address;
let params = default_consensus_params(&ctx, our_address);
let consensus_config = default_engine_config_single_part();
// Create metrics registry for consensus actors
let metrics = SharedRegistry::global().with_moniker("cipherbft-consensus");
// Create libp2p keypair from Ed25519 secret key for consensus network
// This ensures deterministic PeerId across node restarts
let consensus_keypair = Keypair::ed25519_from_bytes(ed25519_secret_bytes).map_err(|e| {
anyhow::anyhow!("Failed to create libp2p keypair from Ed25519 key: {}", e)
})?;
info!(
"Consensus network PeerId: {}",
consensus_keypair.public().to_peer_id()
);
// Create network config for consensus p2p layer
// Convert SocketAddr to Multiaddr format
let listen_addr: Multiaddr = format!(
"/ip4/{}/tcp/{}",
self.config.consensus_listen.ip(),
self.config.consensus_listen.port()
)
.parse()
.expect("valid multiaddr from config");