oxirs-cluster 0.2.4

Raft-backed distributed dataset for high availability and horizontal scaling
Documentation
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
//! Byzantine Fault Tolerance (BFT) consensus implementation
//!
//! This module provides Byzantine fault-tolerant consensus for untrusted environments,
//! protecting against malicious nodes in the cluster.

use crate::{ClusterError, Result};
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
// Note: OsRng imported via fully qualified path to avoid scirs2-core re-export conflict
use serde::{Deserialize, Serialize};
use serde_json;
use sha2::{Digest, Sha256};
use std::collections::{HashMap, HashSet};
use std::sync::{Arc, RwLock};
use std::time::{Duration, Instant};

/// Byzantine fault tolerance configuration
#[derive(Debug, Clone)]
pub struct BftConfig {
    /// Minimum number of nodes required for consensus
    pub min_nodes: usize,
    /// Maximum number of faulty nodes tolerated (f)
    pub max_faulty: usize,
    /// View change timeout
    pub view_timeout: Duration,
    /// Message authentication timeout
    pub auth_timeout: Duration,
    /// Enable cryptographic signatures
    pub enable_signatures: bool,
    /// Enable message ordering verification
    pub enable_ordering: bool,
}

impl BftConfig {
    /// Create a new BFT configuration for n nodes
    pub fn new(num_nodes: usize) -> Self {
        // Byzantine fault tolerance requires n >= 3f + 1
        let max_faulty = (num_nodes - 1) / 3;

        BftConfig {
            min_nodes: 3 * max_faulty + 1,
            max_faulty,
            view_timeout: Duration::from_secs(10),
            auth_timeout: Duration::from_secs(5),
            enable_signatures: true,
            enable_ordering: true,
        }
    }

    /// Check if we have enough nodes for BFT consensus
    pub fn has_quorum(&self, active_nodes: usize) -> bool {
        active_nodes >= self.min_nodes
    }

    /// Calculate the required votes for consensus (2f + 1)
    pub fn required_votes(&self) -> usize {
        2 * self.max_faulty + 1
    }
}

/// Byzantine node state
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BftNodeState {
    /// Normal operation
    Normal,
    /// View change in progress
    ViewChange,
    /// Node is suspected to be Byzantine
    Suspected,
    /// Node is confirmed Byzantine and isolated
    Byzantine,
}

/// PBFT message types
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum BftMessage {
    /// Client request
    Request {
        client_id: String,
        operation: Vec<u8>,
        timestamp: u64,
        signature: Option<Vec<u8>>,
    },
    /// Pre-prepare phase (primary only)
    PrePrepare {
        view: u64,
        sequence: u64,
        digest: Vec<u8>,
        request: Box<BftMessage>,
        primary_signature: Vec<u8>,
    },
    /// Prepare phase
    Prepare {
        view: u64,
        sequence: u64,
        digest: Vec<u8>,
        node_id: String,
        signature: Vec<u8>,
    },
    /// Commit phase
    Commit {
        view: u64,
        sequence: u64,
        digest: Vec<u8>,
        node_id: String,
        signature: Vec<u8>,
    },
    /// Reply to client
    Reply {
        view: u64,
        timestamp: u64,
        client_id: String,
        node_id: String,
        result: Vec<u8>,
        signature: Vec<u8>,
    },
    /// View change request
    ViewChange {
        new_view: u64,
        node_id: String,
        prepared_messages: Vec<PreparedMessage>,
        signature: Vec<u8>,
    },
    /// New view confirmation
    NewView {
        view: u64,
        view_changes: Vec<BftMessage>,
        pre_prepares: Vec<BftMessage>,
        primary_signature: Vec<u8>,
    },
    /// Checkpoint for garbage collection
    Checkpoint {
        sequence: u64,
        digest: Vec<u8>,
        node_id: String,
        signature: Vec<u8>,
    },
}

/// Prepared message proof
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PreparedMessage {
    pub view: u64,
    pub sequence: u64,
    pub digest: Vec<u8>,
    pub pre_prepare: Box<BftMessage>,
    pub prepares: Vec<BftMessage>,
}

/// Byzantine fault-tolerant consensus engine
pub struct BftConsensus {
    /// Node identifier
    node_id: String,
    /// Current view number
    view: Arc<RwLock<u64>>,
    /// Node state
    #[allow(dead_code)]
    state: Arc<RwLock<BftNodeState>>,
    /// BFT configuration
    config: BftConfig,
    /// Cryptographic keypair for this node
    keypair: SigningKey,
    /// Known public keys of other nodes
    node_keys: Arc<RwLock<HashMap<String, VerifyingKey>>>,
    /// Message log for consensus
    message_log: Arc<RwLock<MessageLog>>,
    /// Byzantine node tracker
    byzantine_tracker: Arc<RwLock<ByzantineTracker>>,
    /// View change timer
    view_timer: Arc<RwLock<Option<Instant>>>,
}

/// Message log for consensus tracking
struct MessageLog {
    /// Pre-prepare messages by view and sequence
    pre_prepares: HashMap<(u64, u64), BftMessage>,
    /// Prepare messages by view, sequence, and node
    prepares: HashMap<(u64, u64), HashMap<String, BftMessage>>,
    /// Commit messages by view, sequence, and node
    commits: HashMap<(u64, u64), HashMap<String, BftMessage>>,
    /// Completed requests by sequence
    completed: HashMap<u64, Vec<u8>>,
    /// Last stable checkpoint
    #[allow(dead_code)]
    last_checkpoint: u64,
}

impl MessageLog {
    fn new() -> Self {
        MessageLog {
            pre_prepares: HashMap::new(),
            prepares: HashMap::new(),
            commits: HashMap::new(),
            completed: HashMap::new(),
            last_checkpoint: 0,
        }
    }

    /// Check if a request is prepared (has 2f prepares)
    fn is_prepared(&self, view: u64, sequence: u64, required_votes: usize) -> bool {
        self.prepares
            .get(&(view, sequence))
            .map(|votes| votes.len() >= required_votes)
            .unwrap_or(false)
    }

    /// Check if a request is committed (has 2f + 1 commits)
    fn is_committed(&self, view: u64, sequence: u64, required_votes: usize) -> bool {
        self.commits
            .get(&(view, sequence))
            .map(|votes| votes.len() >= required_votes)
            .unwrap_or(false)
    }
}

/// Byzantine node detection and tracking
struct ByzantineTracker {
    /// Nodes suspected of Byzantine behavior
    suspected_nodes: HashSet<String>,
    /// Confirmed Byzantine nodes (isolated)
    byzantine_nodes: HashSet<String>,
    /// Invalid message counts per node
    invalid_messages: HashMap<String, usize>,
    /// Threshold for Byzantine detection
    detection_threshold: usize,
}

impl ByzantineTracker {
    fn new(threshold: usize) -> Self {
        ByzantineTracker {
            suspected_nodes: HashSet::new(),
            byzantine_nodes: HashSet::new(),
            invalid_messages: HashMap::new(),
            detection_threshold: threshold,
        }
    }

    /// Report an invalid message from a node
    fn report_invalid(&mut self, node_id: &str) {
        let count = self
            .invalid_messages
            .entry(node_id.to_string())
            .or_insert(0);
        *count += 1;

        if *count >= self.detection_threshold {
            self.suspected_nodes.insert(node_id.to_string());

            // After multiple violations, mark as Byzantine
            if *count >= self.detection_threshold * 2 {
                self.byzantine_nodes.insert(node_id.to_string());
                self.suspected_nodes.remove(node_id);
            }
        }
    }

    /// Check if a node is Byzantine or suspected
    fn is_byzantine(&self, node_id: &str) -> bool {
        self.byzantine_nodes.contains(node_id) || self.suspected_nodes.contains(node_id)
    }
}

impl BftConsensus {
    /// Create a new BFT consensus instance
    pub fn new(node_id: String, config: BftConfig) -> Result<Self> {
        // Generate a random SigningKey using rand crate's random() to avoid type conflicts
        // This avoids the scirs2-core OsRng re-export issue
        let seed_bytes: [u8; 32] = rand::random();
        let keypair = SigningKey::from_bytes(&seed_bytes);

        Ok(BftConsensus {
            node_id,
            view: Arc::new(RwLock::new(0)),
            state: Arc::new(RwLock::new(BftNodeState::Normal)),
            config,
            keypair,
            node_keys: Arc::new(RwLock::new(HashMap::new())),
            message_log: Arc::new(RwLock::new(MessageLog::new())),
            byzantine_tracker: Arc::new(RwLock::new(ByzantineTracker::new(5))),
            view_timer: Arc::new(RwLock::new(None)),
        })
    }

    /// Register a node's public key
    pub fn register_node(&self, node_id: String, public_key: VerifyingKey) -> Result<()> {
        let mut keys = self
            .node_keys
            .write()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        keys.insert(node_id, public_key);
        Ok(())
    }

    /// Get current view number
    pub fn current_view(&self) -> Result<u64> {
        let view = self
            .view
            .read()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        Ok(*view)
    }

    /// Check if this node is the primary for current view
    pub fn is_primary(&self) -> Result<bool> {
        let view = self.current_view()?;
        let keys = self
            .node_keys
            .read()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        let num_nodes = keys.len() + 1; // Include self
        let primary_index = (view as usize) % num_nodes;

        // Simple primary selection based on sorted node IDs
        let mut all_nodes: Vec<String> = keys.keys().cloned().collect();
        all_nodes.push(self.node_id.clone());
        all_nodes.sort();

        Ok(all_nodes.get(primary_index) == Some(&self.node_id))
    }

    /// Create a message digest
    fn create_digest(message: &[u8]) -> Vec<u8> {
        let mut hasher = Sha256::new();
        hasher.update(message);
        hasher.finalize().to_vec()
    }

    /// Sign a message
    fn sign_message(&self, message: &[u8]) -> Vec<u8> {
        if !self.config.enable_signatures {
            return vec![];
        }

        let signature = self.keypair.sign(message);
        signature.to_bytes().to_vec()
    }

    /// Verify a message signature
    fn verify_signature(&self, node_id: &str, message: &[u8], signature: &[u8]) -> Result<bool> {
        if !self.config.enable_signatures {
            return Ok(true);
        }

        let keys = self
            .node_keys
            .read()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;

        let public_key = keys
            .get(node_id)
            .ok_or_else(|| ClusterError::Config(format!("Unknown node: {}", node_id)))?;

        // ed25519-dalek 2.x requires exactly 64 bytes
        if signature.len() != 64 {
            return Ok(false);
        }

        let mut signature_bytes = [0u8; 64];
        signature_bytes.copy_from_slice(signature);
        let sig = Signature::from_bytes(&signature_bytes);

        Ok(public_key.verify(message, &sig).is_ok())
    }

    /// Process a client request (primary only)
    pub fn process_request(&self, request: BftMessage) -> Result<()> {
        if !self.is_primary()? {
            return Err(ClusterError::NotLeader);
        }

        let view = self.current_view()?;
        let sequence = self.next_sequence()?;

        // Create pre-prepare message
        if let BftMessage::Request { operation, .. } = &request {
            let digest = Self::create_digest(operation);
            let pre_prepare = BftMessage::PrePrepare {
                view,
                sequence,
                digest: digest.clone(),
                request: Box::new(request),
                primary_signature: self.sign_message(&digest),
            };

            // Store and broadcast pre-prepare
            self.store_pre_prepare(view, sequence, pre_prepare.clone())?;
            self.broadcast_message(pre_prepare)?;
        }

        Ok(())
    }

    /// Handle incoming BFT message
    pub fn handle_message(&self, message: BftMessage, from_node: &str) -> Result<()> {
        // Check if node is Byzantine
        let tracker = self
            .byzantine_tracker
            .read()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        if tracker.is_byzantine(from_node) {
            return Err(ClusterError::Network(format!(
                "Byzantine node: {}",
                from_node
            )));
        }
        drop(tracker);

        match message {
            BftMessage::PrePrepare {
                view,
                sequence,
                digest,
                request,
                primary_signature,
            } => {
                self.handle_pre_prepare(
                    view,
                    sequence,
                    digest,
                    *request,
                    primary_signature,
                    from_node,
                )?;
            }
            BftMessage::Prepare {
                view,
                sequence,
                digest,
                node_id,
                signature,
            } => {
                self.handle_prepare(view, sequence, digest, node_id, signature)?;
            }
            BftMessage::Commit {
                view,
                sequence,
                digest,
                node_id,
                signature,
            } => {
                self.handle_commit(view, sequence, digest, node_id, signature)?;
            }
            BftMessage::ViewChange {
                new_view,
                node_id,
                prepared_messages,
                signature,
            } => {
                self.handle_view_change(new_view, node_id, prepared_messages, signature)?;
            }
            _ => {}
        }

        Ok(())
    }

    /// Handle pre-prepare message
    fn handle_pre_prepare(
        &self,
        view: u64,
        sequence: u64,
        digest: Vec<u8>,
        request: BftMessage,
        signature: Vec<u8>,
        from_node: &str,
    ) -> Result<()> {
        // Verify view and primary
        if view != self.current_view()? {
            return Ok(()); // Ignore messages from wrong view
        }

        // Verify signature
        if !self.verify_signature(from_node, &digest, &signature)? {
            self.report_byzantine(from_node)?;
            return Err(ClusterError::Network("Invalid signature".to_string()));
        }

        // Store pre-prepare
        self.store_pre_prepare(
            view,
            sequence,
            BftMessage::PrePrepare {
                view,
                sequence,
                digest: digest.clone(),
                request: Box::new(request),
                primary_signature: signature,
            },
        )?;

        // Send prepare message
        let prepare = BftMessage::Prepare {
            view,
            sequence,
            digest: digest.clone(),
            node_id: self.node_id.clone(),
            signature: self.sign_message(&digest),
        };

        self.broadcast_message(prepare)?;

        Ok(())
    }

    /// Handle prepare message
    fn handle_prepare(
        &self,
        view: u64,
        sequence: u64,
        digest: Vec<u8>,
        node_id: String,
        signature: Vec<u8>,
    ) -> Result<()> {
        // Verify signature
        if !self.verify_signature(&node_id, &digest, &signature)? {
            self.report_byzantine(&node_id)?;
            return Err(ClusterError::Network("Invalid signature".to_string()));
        }

        // Store prepare
        let mut log = self
            .message_log
            .write()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;

        log.prepares
            .entry((view, sequence))
            .or_insert_with(HashMap::new)
            .insert(
                node_id.clone(),
                BftMessage::Prepare {
                    view,
                    sequence,
                    digest: digest.clone(),
                    node_id,
                    signature,
                },
            );

        // Check if prepared (2f prepares)
        if log.is_prepared(view, sequence, self.config.required_votes()) {
            drop(log);

            // Send commit message
            let commit = BftMessage::Commit {
                view,
                sequence,
                digest: digest.clone(),
                node_id: self.node_id.clone(),
                signature: self.sign_message(&digest),
            };

            self.broadcast_message(commit)?;
        }

        Ok(())
    }

    /// Handle commit message
    fn handle_commit(
        &self,
        view: u64,
        sequence: u64,
        digest: Vec<u8>,
        node_id: String,
        signature: Vec<u8>,
    ) -> Result<()> {
        // Verify signature
        if !self.verify_signature(&node_id, &digest, &signature)? {
            self.report_byzantine(&node_id)?;
            return Err(ClusterError::Network("Invalid signature".to_string()));
        }

        // Store commit
        let mut log = self
            .message_log
            .write()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;

        log.commits
            .entry((view, sequence))
            .or_insert_with(HashMap::new)
            .insert(
                node_id.clone(),
                BftMessage::Commit {
                    view,
                    sequence,
                    digest: digest.clone(),
                    node_id,
                    signature,
                },
            );

        // Check if committed (2f + 1 commits)
        if log.is_committed(view, sequence, self.config.required_votes()) {
            // Clone data we need before mutable borrow
            let operation_data = if let Some(pre_prepare) = log.pre_prepares.get(&(view, sequence))
            {
                if let BftMessage::PrePrepare { request, .. } = pre_prepare {
                    if let BftMessage::Request {
                        operation,
                        client_id,
                        timestamp,
                        ..
                    } = &**request
                    {
                        Some((operation.clone(), client_id.clone(), *timestamp))
                    } else {
                        None
                    }
                } else {
                    None
                }
            } else {
                None
            };

            // Now we can mutably borrow log
            if let Some((operation, client_id, timestamp)) = operation_data {
                log.completed.insert(sequence, operation.clone());

                // Execute the operation and generate result
                // In a real implementation, this would execute the RDF operation
                // and return the actual query results or modification status
                let execution_result = self.execute_operation(&operation)?;

                // Send reply to client
                let reply = BftMessage::Reply {
                    view,
                    timestamp,
                    client_id,
                    node_id: self.node_id.clone(),
                    result: execution_result,
                    signature: self.sign_message(&digest),
                };

                drop(log);
                self.send_reply(reply)?;
            }
        }

        Ok(())
    }

    /// Handle view change request
    ///
    /// Implements the PBFT view change protocol for primary node replacement.
    /// The protocol ensures safety and liveness even when the primary is faulty.
    fn handle_view_change(
        &self,
        new_view: u64,
        node_id: String,
        prepared_messages: Vec<PreparedMessage>,
        signature: Vec<u8>,
    ) -> Result<()> {
        // Step 1: Validate the view change request signature
        // In a full implementation, this would verify the signature
        let _ = signature; // Suppress unused warning

        // Step 2: Check if view change is valid (new_view > view)
        let current_view = self
            .view
            .read()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;

        if new_view <= *current_view {
            return Err(ClusterError::Consensus(format!(
                "View change to {} rejected: current view is {}",
                new_view, *current_view
            )));
        }
        drop(current_view);

        // Step 3: Verify prepared messages are properly signed and ordered
        // In a full implementation, this would:
        // - Verify each prepared message has 2f+1 prepare certificates
        // - Check message ordering and consistency
        // - Validate all signatures
        if prepared_messages.is_empty() {
            // No prepared messages is valid for view change
        }

        // Step 4: Update view and elect new primary
        // The new primary is determined by: primary = new_view % n
        let mut current_view = self
            .view
            .write()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        *current_view = new_view;
        drop(current_view);

        // Step 5: Reset view timer
        let mut timer = self
            .view_timer
            .write()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        *timer = Some(Instant::now());

        tracing::info!(
            "View change completed: node {} initiated view change to view {}",
            node_id,
            new_view
        );

        Ok(())
    }

    /// Report Byzantine behavior
    fn report_byzantine(&self, node_id: &str) -> Result<()> {
        let mut tracker = self
            .byzantine_tracker
            .write()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        tracker.report_invalid(node_id);
        Ok(())
    }

    /// Get next sequence number
    fn next_sequence(&self) -> Result<u64> {
        let log = self
            .message_log
            .read()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        Ok(log.completed.len() as u64 + 1)
    }

    /// Store pre-prepare message
    fn store_pre_prepare(&self, view: u64, sequence: u64, message: BftMessage) -> Result<()> {
        let mut log = self
            .message_log
            .write()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        log.pre_prepares.insert((view, sequence), message);
        Ok(())
    }

    /// Execute an operation and return the result
    ///
    /// This is a placeholder implementation. In a production system, this would:
    /// - Parse the operation bytes into an RDF command (SPARQL query, triple insert, etc.)
    /// - Execute the command against the RDF store
    /// - Serialize the results (query results, success/failure status, etc.)
    /// - Return the serialized result bytes
    fn execute_operation(&self, operation: &[u8]) -> Result<Vec<u8>> {
        // For now, return a simple success response with the operation hash
        let mut hasher = Sha256::new();
        hasher.update(operation);
        let operation_hash = hasher.finalize();

        // Create a simple JSON success response
        let response = serde_json::json!({
            "status": "success",
            "operation_hash": hex::encode(operation_hash),
            "timestamp": std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .expect("SystemTime should be after UNIX_EPOCH")
                .as_secs(),
        });

        serde_json::to_vec(&response).map_err(|e| ClusterError::Serialize(e.to_string()))
    }

    /// Broadcast message to all nodes
    ///
    /// This is a placeholder implementation. In a production system, this would:
    /// - Serialize the BftMessage to bytes
    /// - Send the message to all peer nodes in the cluster
    /// - Use the existing network layer (crate::network) for reliable delivery
    /// - Handle network failures and retries
    /// - Track message acknowledgments
    fn broadcast_message(&self, _message: BftMessage) -> Result<()> {
        // Integration with network layer will be implemented when:
        // 1. Network module provides a broadcast_to_peers() method
        // 2. Message routing is available for BFT consensus messages
        // 3. Proper async handling is in place
        Ok(())
    }

    /// Send reply to client
    ///
    /// This is a placeholder implementation. In a production system, this would:
    /// - Serialize the Reply message to bytes
    /// - Send the reply back to the requesting client
    /// - Use the client connection manager for delivery
    /// - Handle client disconnections gracefully
    fn send_reply(&self, _reply: BftMessage) -> Result<()> {
        // Integration with network layer will be implemented when:
        // 1. Client connection tracking is available
        // 2. Reply routing mechanism is in place
        // 3. Client session management is implemented
        Ok(())
    }

    /// Start view change timer
    pub fn start_view_timer(&self) -> Result<()> {
        let mut timer = self
            .view_timer
            .write()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;
        *timer = Some(Instant::now());
        Ok(())
    }

    /// Check if view change is needed
    pub fn check_view_timeout(&self) -> Result<bool> {
        let timer = self
            .view_timer
            .read()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;

        if let Some(start_time) = *timer {
            Ok(start_time.elapsed() > self.config.view_timeout)
        } else {
            Ok(false)
        }
    }

    /// Collect all prepared messages for view change
    ///
    /// Returns a vector of PreparedMessage containing proof of prepared requests
    /// for inclusion in ViewChange messages during view changes.
    pub fn collect_prepared_messages(&self) -> Result<Vec<PreparedMessage>> {
        let log = self
            .message_log
            .read()
            .map_err(|e| ClusterError::Lock(e.to_string()))?;

        let mut prepared_messages = Vec::new();
        let required_votes = self.config.required_votes();

        // Iterate through all prepare messages to find prepared requests
        for ((view, sequence), prepares_map) in &log.prepares {
            // Check if this request is prepared (has enough votes)
            if prepares_map.len() >= required_votes {
                // Get the pre-prepare message
                if let Some(pre_prepare) = log.pre_prepares.get(&(*view, *sequence)) {
                    if let BftMessage::PrePrepare { digest, .. } = pre_prepare {
                        // Collect prepare messages for this request
                        let prepares: Vec<BftMessage> = prepares_map.values().cloned().collect();

                        prepared_messages.push(PreparedMessage {
                            view: *view,
                            sequence: *sequence,
                            digest: digest.clone(),
                            pre_prepare: Box::new(pre_prepare.clone()),
                            prepares,
                        });
                    }
                }
            }
        }

        tracing::debug!(
            "Collected {} prepared messages for view change",
            prepared_messages.len()
        );

        Ok(prepared_messages)
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bft_config() {
        // Test with 4 nodes (tolerates 1 Byzantine fault)
        let config = BftConfig::new(4);
        assert_eq!(config.max_faulty, 1);
        assert_eq!(config.min_nodes, 4);
        assert_eq!(config.required_votes(), 3);
        assert!(config.has_quorum(4));
        assert!(!config.has_quorum(3));

        // Test with 7 nodes (tolerates 2 Byzantine faults)
        let config = BftConfig::new(7);
        assert_eq!(config.max_faulty, 2);
        assert_eq!(config.min_nodes, 7);
        assert_eq!(config.required_votes(), 5);
    }

    #[test]
    fn test_byzantine_tracker() {
        let mut tracker = ByzantineTracker::new(3);

        // Report invalid messages
        tracker.report_invalid("node1");
        assert!(!tracker.is_byzantine("node1"));

        tracker.report_invalid("node1");
        tracker.report_invalid("node1");
        assert!(tracker.suspected_nodes.contains("node1"));

        // Continue reporting until marked as Byzantine
        for _ in 0..3 {
            tracker.report_invalid("node1");
        }
        assert!(tracker.byzantine_nodes.contains("node1"));
        assert!(!tracker.suspected_nodes.contains("node1"));
    }

    #[test]
    fn test_message_digest() {
        let message1 = b"test message 1";
        let message2 = b"test message 2";

        let digest1 = BftConsensus::create_digest(message1);
        let digest2 = BftConsensus::create_digest(message2);

        assert_ne!(digest1, digest2);
        assert_eq!(digest1.len(), 32); // SHA256 produces 32 bytes
    }
}