tenzro-consensus 0.1.0

HotStuff-2 BFT consensus engine for Tenzro Network with TEE-weighted leader selection and equivocation detection
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
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
//! Validator set management for consensus

use crate::error::{ConsensusError, Result};
use crate::leader_reputation::LeaderReputation;
use crate::voter::Vote;
use dashmap::DashMap;
use serde::{Deserialize, Deserializer, Serialize};
use std::sync::Arc;
use tenzro_crypto::pq::ML_DSA_65_VK_LEN;
use tenzro_crypto::PublicKey;

/// BLS12-381 G1-compressed public key length (`min_pk` scheme used by
/// `tenzro_crypto::bls`). Every validator MUST advertise a BLS verifying key
/// for HotStuff-2 vote-signature aggregation.
pub const BLS_G1_COMPRESSED_LEN: usize = 48;
use tenzro_types::primitives::{Address, Hash, Timestamp};
use tenzro_types::tee::{AttestationReport, AttestationResult};

/// Deserialize an ML-DSA-65 verifying key, rejecting any byte string that does
/// not match the FIPS 204 length (1952 bytes). This prevents downgrade or
/// truncation attacks at the wire level — every validator MUST advertise a
/// well-formed PQ key per the Wave 3d migration.
fn deserialize_pq_verifying_key<'de, D>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error>
where
    D: Deserializer<'de>,
{
    let bytes = Vec::<u8>::deserialize(deserializer)?;
    if bytes.len() != ML_DSA_65_VK_LEN {
        return Err(serde::de::Error::custom(format!(
            "validator PQ verifying key has wrong length: expected {} bytes (ML-DSA-65), got {}",
            ML_DSA_65_VK_LEN,
            bytes.len()
        )));
    }
    Ok(bytes)
}

/// Deserialize a BLS12-381 G1-compressed verifying key, rejecting any byte
/// string that does not match the 48-byte length. Every validator in the
/// active set MUST advertise a well-formed BLS key for HotStuff-2 vote
/// aggregation per ROADMAP B.1.
fn deserialize_bls_verifying_key<'de, D>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error>
where
    D: Deserializer<'de>,
{
    let bytes = Vec::<u8>::deserialize(deserializer)?;
    if bytes.len() != BLS_G1_COMPRESSED_LEN {
        return Err(serde::de::Error::custom(format!(
            "validator BLS verifying key has wrong length: expected {} bytes (BLS12-381 G1 compressed), got {}",
            BLS_G1_COMPRESSED_LEN,
            bytes.len()
        )));
    }
    Ok(bytes)
}

/// Information about a validator
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ValidatorInfo {
    /// Validator's address
    pub address: Address,

    /// Validator's classical public key (Ed25519) for signing
    pub public_key: PublicKey,

    /// Validator's ML-DSA-65 verifying key (1952 bytes, FIPS 204) for the
    /// post-quantum signing leg. Mandatory: every validator in the active set
    /// must advertise a hybrid key per the Wave 3d migration.
    #[serde(deserialize_with = "deserialize_pq_verifying_key")]
    pub pq_public_key: Vec<u8>,

    /// Validator's BLS12-381 G1-compressed verifying key (48 bytes, `min_pk`
    /// scheme). Mandatory: every validator MUST advertise a BLS key for
    /// HotStuff-2 vote-signature aggregation per ROADMAP B.1. The aggregation
    /// is the third signature leg alongside the per-vote Ed25519 + ML-DSA-65
    /// `CompositeSignature` — BLS provides O(1) bandwidth and verification
    /// CPU savings on the QC path; Composite preserves the PQ-hybrid property
    /// per individual vote (Composite is pre-quantum on its classical leg
    /// only, BLS12-381 itself is pre-quantum, hence we keep both).
    #[serde(deserialize_with = "deserialize_bls_verifying_key")]
    pub bls_public_key: Vec<u8>,

    /// Stake amount (voting power)
    pub stake: u128,

    /// TEE attestation report (optional)
    pub tee_attestation: Option<AttestationReport>,

    /// TEE attestation verification result
    pub tee_attestation_result: Option<AttestationResult>,

    /// Validator status
    pub status: ValidatorStatus,

    /// Registration timestamp
    pub registered_at: Timestamp,

    /// Last attestation update
    pub last_attestation_update: Option<Timestamp>,
}

impl ValidatorInfo {
    /// Creates a new validator info.
    ///
    /// # Panics
    ///
    /// Panics if:
    /// - `pq_public_key.len() != ML_DSA_65_VK_LEN` (1952 bytes), or
    /// - `bls_public_key.len() != BLS_G1_COMPRESSED_LEN` (48 bytes).
    ///
    /// Both keys are mandatory; there is no fallback path. Construct the PQ
    /// key via `MlDsaSigningKey::generate()` and pass
    /// `key.verifying_key_bytes().to_vec()`. Construct the BLS key via
    /// `tenzro_crypto::bls::BlsKeyPair::generate()` and pass
    /// `keypair.public_key().to_bytes().to_vec()`.
    pub fn new(
        address: Address,
        public_key: PublicKey,
        pq_public_key: Vec<u8>,
        bls_public_key: Vec<u8>,
        stake: u128,
    ) -> Self {
        assert_eq!(
            pq_public_key.len(),
            ML_DSA_65_VK_LEN,
            "validator PQ verifying key has wrong length: expected {} bytes (ML-DSA-65), got {}",
            ML_DSA_65_VK_LEN,
            pq_public_key.len()
        );
        assert_eq!(
            bls_public_key.len(),
            BLS_G1_COMPRESSED_LEN,
            "validator BLS verifying key has wrong length: expected {} bytes (BLS12-381 G1 compressed), got {}",
            BLS_G1_COMPRESSED_LEN,
            bls_public_key.len()
        );
        Self {
            address,
            public_key,
            pq_public_key,
            bls_public_key,
            stake,
            tee_attestation: None,
            tee_attestation_result: None,
            status: ValidatorStatus::Active,
            registered_at: Timestamp::now(),
            last_attestation_update: None,
        }
    }

    /// Returns the composite (classical + PQ) public key for this validator,
    /// suitable for hybrid signature verification via `StandardHybridVerifier`.
    pub fn composite_public_key(&self) -> tenzro_crypto::composite::CompositePublicKey {
        tenzro_crypto::composite::CompositePublicKey::new(
            self.public_key.clone(),
            self.pq_public_key.clone(),
        )
    }

    /// Adds TEE attestation to the validator
    pub fn with_tee_attestation(
        mut self,
        attestation: AttestationReport,
        result: AttestationResult,
    ) -> Self {
        self.tee_attestation = Some(attestation);
        self.tee_attestation_result = Some(result);
        self.last_attestation_update = Some(Timestamp::now());
        self
    }

    /// Returns whether the validator has valid TEE attestation
    pub fn has_valid_tee_attestation(&self) -> bool {
        self.tee_attestation_result
            .as_ref()
            .map(|r| r.valid)
            .unwrap_or(false)
    }

    /// Returns whether the validator is active
    pub fn is_active(&self) -> bool {
        self.status == ValidatorStatus::Active
    }

    /// Returns the voting power of the validator
    pub fn voting_power(&self) -> u128 {
        if self.is_active() {
            self.stake
        } else {
            0
        }
    }

    /// Returns the base priority for leader selection.
    ///
    /// This is just the validator's voting power (stake when active, zero
    /// otherwise). Any TEE multiplier is applied by the proposer-election
    /// implementation (see [`ReputationProposer`]), not baked into the
    /// validator's intrinsic priority — so a TEE-attested validator with
    /// degraded behaviour can still be deprioritized by reputation.
    pub fn leader_priority(&self) -> u128 {
        self.voting_power()
    }
}

/// Validator operational status.
///
/// This mirrors the lifecycle in [`tenzro_token::ValidatorRegistryStatus`]
/// but is the local view consensus uses to decide who participates in the
/// current round. The token-side registry is the source of truth across
/// epoch boundaries; consensus only ever sees `Active` / `Inactive` /
/// `Jailed` / `Unbonding` states reflected from the registry's transition
/// plan.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ValidatorStatus {
    /// Active and participating in consensus
    Active,
    /// Temporarily inactive
    Inactive,
    /// Jailed due to misbehavior
    Jailed,
    /// Unbonding (pending removal)
    Unbonding,
}

/// A set of validators for an epoch
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidatorSet {
    /// Current epoch number
    pub epoch: u64,

    /// List of validators
    validators: Vec<ValidatorInfo>,

    /// Total stake across all validators
    total_stake: u128,

    /// Epoch start timestamp
    pub epoch_start: Timestamp,
}

impl ValidatorSet {
    /// Creates a new validator set for the given epoch
    pub fn new(epoch: u64, validators: Vec<ValidatorInfo>) -> Result<Self> {
        if validators.is_empty() {
            return Err(ConsensusError::InvalidValidatorSet(
                "Validator set cannot be empty".to_string(),
            ));
        }

        let total_stake = validators.iter().map(|v| v.voting_power()).sum();

        Ok(Self {
            epoch,
            validators,
            total_stake,
            epoch_start: Timestamp::now(),
        })
    }

    /// Returns the validator at the given index
    pub fn get(&self, index: usize) -> Option<&ValidatorInfo> {
        self.validators.get(index)
    }

    /// Returns the validator with the given address
    pub fn get_by_address(&self, address: &Address) -> Option<&ValidatorInfo> {
        self.validators.iter().find(|v| &v.address == address)
    }

    /// Returns the position of a validator in `self.validators` matching the
    /// given address, or `None` if not present.
    ///
    /// This is the canonical "validator index" used for bitmap-based BLS
    /// signer encoding in [`crate::voter::QuorumCertificate::signer_bitmap`].
    /// The index is stable for the lifetime of the validator set (i.e. the
    /// duration of one epoch); a new epoch may renumber.
    pub fn index_of(&self, address: &Address) -> Option<usize> {
        self.validators.iter().position(|v| &v.address == address)
    }

    /// Returns the validators slice in canonical order (insertion / epoch
    /// order). The position of each entry in this slice is the bit index used
    /// by [`crate::voter::QuorumCertificate::signer_bitmap`] when verifying
    /// the BLS aggregate.
    pub fn active_validators(&self) -> &[ValidatorInfo] {
        &self.validators
    }

    /// Returns the number of validators
    pub fn len(&self) -> usize {
        self.validators.len()
    }

    /// Returns whether the validator set is empty
    pub fn is_empty(&self) -> bool {
        self.validators.is_empty()
    }

    /// Returns an iterator over the validators
    pub fn iter(&self) -> std::slice::Iter<'_, ValidatorInfo> {
        self.validators.iter()
    }

    /// Returns the total stake
    pub fn total_stake(&self) -> u128 {
        self.total_stake
    }

    /// Returns the total voting power (sum of active validators' stake)
    pub fn total_voting_power(&self) -> u128 {
        self.validators.iter().map(|v| v.voting_power()).sum()
    }

    /// Returns whether the given address is a validator
    pub fn is_validator(&self, address: &Address) -> bool {
        self.get_by_address(address).is_some()
    }

    /// Selects the leader for the given view via deterministic round-robin.
    ///
    /// This is the simplest possible proposer election: `view % N`. It is
    /// retained as a fallback / test path; production deployments should use
    /// [`ReputationProposer`] via [`ProposerElection`] which incorporates
    /// observed-behaviour reputation and a stake-weighted draw.
    pub fn select_leader_round_robin(&self, view: u64) -> Result<&ValidatorInfo> {
        if self.validators.is_empty() {
            return Err(ConsensusError::InvalidValidatorSet(
                "No validators available".to_string(),
            ));
        }
        let index = (view as usize) % self.validators.len();
        Ok(&self.validators[index])
    }

    /// Calculates the quorum threshold (2f+1)
    pub fn quorum_threshold(&self) -> usize {
        let n = self.validators.len();
        let f = (n.saturating_sub(1)) / 3;
        2 * f + 1
    }

    /// Returns the validators with valid TEE attestation
    pub fn tee_attested_validators(&self) -> Vec<&ValidatorInfo> {
        self.validators
            .iter()
            .filter(|v| v.has_valid_tee_attestation())
            .collect()
    }

    /// Returns the percentage of validators with TEE attestation
    pub fn tee_attestation_rate(&self) -> f64 {
        if self.validators.is_empty() {
            return 0.0;
        }
        let attested = self.tee_attested_validators().len();
        (attested as f64 / self.validators.len() as f64) * 100.0
    }
}

/// Evidence of validator equivocation (voting for multiple blocks in the same view)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct EquivocationEvidence {
    /// The validator who equivocated
    pub validator: Address,

    /// View number where equivocation occurred
    pub view: u64,

    /// First vote
    pub vote1: Vote,

    /// Second conflicting vote
    pub vote2: Vote,

    /// Timestamp when evidence was detected
    pub detected_at: Timestamp,
}

impl EquivocationEvidence {
    /// Creates new equivocation evidence
    pub fn new(validator: Address, view: u64, vote1: Vote, vote2: Vote) -> Self {
        Self {
            validator,
            view,
            vote1,
            vote2,
            detected_at: Timestamp::now(),
        }
    }

    /// Verifies that the evidence is valid (same view, different blocks)
    pub fn is_valid(&self) -> bool {
        self.vote1.view == self.vote2.view
            && self.vote1.view == self.view
            && self.vote1.voter == self.vote2.voter
            && self.vote1.voter == self.validator
            && self.vote1.block_hash != self.vote2.block_hash
            && self.vote1.vote_type == self.vote2.vote_type
    }
}

/// Key for tracking votes per (validator, view) pair
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ValidatorViewKey {
    validator: Address,
    view: u64,
}

/// Tracks validator votes to detect equivocation
pub struct EquivocationDetector {
    /// Stores (block_hash, vote_type) for each (validator, view) pair
    /// Key: (validator, view), Value: (block_hash, vote_type)
    votes: Arc<DashMap<ValidatorViewKey, (Hash, crate::voter::VoteType)>>,

    /// Detected equivocation evidence
    evidence: Arc<DashMap<(Address, u64), EquivocationEvidence>>,

    /// Optional persistence backend. When set, every recorded vote
    /// and every detected EquivocationEvidence writes through to a
    /// dedicated `equivocation:*` keyspace in `CF_AUDIT` and is
    /// hydrated on construction. Without persistence, a validator
    /// equivocator can simply restart their node to wipe the
    /// detector's state and avoid slashing.
    storage: Option<Arc<dyn tenzro_storage::KvStore>>,
}

impl EquivocationDetector {
    /// Creates a new equivocation detector (in-memory only — test
    /// path).
    pub fn new() -> Self {
        Self {
            votes: Arc::new(DashMap::new()),
            evidence: Arc::new(DashMap::new()),
            storage: None,
        }
    }

    /// Production constructor: write-through to `CF_AUDIT` under
    /// `equivocation/votes/*` and `equivocation/evidence/*`. Hydrates
    /// both maps on construction.
    pub fn with_storage(storage: Arc<dyn tenzro_storage::KvStore>) -> Self {
        let d = Self {
            votes: Arc::new(DashMap::new()),
            evidence: Arc::new(DashMap::new()),
            storage: Some(storage),
        };
        d.hydrate();
        d
    }

    fn vote_key(validator: &Address, view: u64) -> Vec<u8> {
        let mut k = b"equivocation/votes/".to_vec();
        k.extend_from_slice(validator.as_bytes());
        k.push(b'/');
        k.extend_from_slice(&view.to_le_bytes());
        k
    }
    fn evidence_key(validator: &Address, view: u64) -> Vec<u8> {
        let mut k = b"equivocation/evidence/".to_vec();
        k.extend_from_slice(validator.as_bytes());
        k.push(b'/');
        k.extend_from_slice(&view.to_le_bytes());
        k
    }

    fn hydrate(&self) {
        let Some(ref storage) = self.storage else {
            return;
        };
        if let Ok(entries) =
            storage.scan_prefix(tenzro_storage::CF_AUDIT, b"equivocation/votes/")
        {
            for (key, value) in entries {
                if let Some(vk) = Self::parse_vote_key(&key) {
                    if let Ok(payload) =
                        serde_json::from_slice::<(Hash, crate::voter::VoteType)>(&value)
                    {
                        self.votes.insert(vk, payload);
                    }
                }
            }
        }
        if let Ok(entries) =
            storage.scan_prefix(tenzro_storage::CF_AUDIT, b"equivocation/evidence/")
        {
            for (key, value) in entries {
                if let Some((addr, view)) = Self::parse_evidence_key(&key) {
                    if let Ok(ev) =
                        serde_json::from_slice::<EquivocationEvidence>(&value)
                    {
                        self.evidence.insert((addr, view), ev);
                    }
                }
            }
        }
    }

    fn parse_vote_key(key: &[u8]) -> Option<ValidatorViewKey> {
        let prefix = b"equivocation/votes/";
        if !key.starts_with(prefix) {
            return None;
        }
        let rest = &key[prefix.len()..];
        if rest.len() < 9 {
            return None;
        }
        let addr_end = rest.len() - 9;
        if rest[addr_end] != b'/' {
            return None;
        }
        let validator = Address::from_bytes(&rest[..addr_end])?;
        let mut view_buf = [0u8; 8];
        view_buf.copy_from_slice(&rest[addr_end + 1..]);
        let view = u64::from_le_bytes(view_buf);
        Some(ValidatorViewKey { validator, view })
    }

    fn parse_evidence_key(key: &[u8]) -> Option<(Address, u64)> {
        let prefix = b"equivocation/evidence/";
        if !key.starts_with(prefix) {
            return None;
        }
        let rest = &key[prefix.len()..];
        if rest.len() < 9 {
            return None;
        }
        let addr_end = rest.len() - 9;
        if rest[addr_end] != b'/' {
            return None;
        }
        let validator = Address::from_bytes(&rest[..addr_end])?;
        let mut view_buf = [0u8; 8];
        view_buf.copy_from_slice(&rest[addr_end + 1..]);
        let view = u64::from_le_bytes(view_buf);
        Some((validator, view))
    }

    fn persist_vote(
        &self,
        vk: &ValidatorViewKey,
        payload: &(Hash, crate::voter::VoteType),
    ) {
        if let Some(ref storage) = self.storage {
            if let Ok(bytes) = serde_json::to_vec(payload) {
                let _ = storage.put(
                    tenzro_storage::CF_AUDIT,
                    &Self::vote_key(&vk.validator, vk.view),
                    &bytes,
                );
            }
        }
    }

    fn persist_evidence(&self, ev: &EquivocationEvidence) {
        if let Some(ref storage) = self.storage {
            if let Ok(bytes) = serde_json::to_vec(ev) {
                let _ = storage.put(
                    tenzro_storage::CF_AUDIT,
                    &Self::evidence_key(&ev.validator, ev.view),
                    &bytes,
                );
            }
        }
    }

    /// Records a vote and checks for equivocation
    /// Returns Ok(None) if no equivocation detected
    /// Returns Ok(Some(evidence)) if equivocation detected
    /// Returns Err if the vote itself is invalid
    pub fn check_vote(&self, vote: &Vote) -> Result<Option<EquivocationEvidence>> {
        let key = ValidatorViewKey {
            validator: vote.voter,
            view: vote.view,
        };

        // Check if validator already voted in this view
        if let Some(existing) = self.votes.get(&key) {
            let (existing_hash, existing_type) = *existing;

            // If voting for the same block, it's a duplicate (not equivocation)
            if existing_hash == vote.block_hash && existing_type == vote.vote_type {
                return Err(ConsensusError::AlreadyVoted(vote.view));
            }

            // If voting for a different block in the same view with same type, it's equivocation
            if existing_type == vote.vote_type {
                // Create the evidence
                // We need to reconstruct the first vote from stored data.
                // The original signature/public_key were not stored (we only
                // need the height, hash, voter, and type to prove
                // equivocation), so we synthesise an empty composite signature
                // and reuse the second vote's public key as a stand-in. The
                // EquivocationEvidence::is_valid() check inspects only
                // view/voter/block_hash/vote_type, so this is sufficient for
                // slashing evidence.
                let placeholder_sig = tenzro_crypto::composite::CompositeSignature::new(
                    Vec::new(),
                    Vec::new(),
                );
                // BLS signature follows the same stand-in rationale as the
                // composite sig + public key above — `EquivocationEvidence::is_valid`
                // only inspects view/voter/block_hash/vote_type.
                let placeholder_bls = vote.bls_signature.clone();
                let vote1 = Vote::new(
                    vote.view,
                    vote.height,
                    existing_hash,
                    vote.voter,
                    placeholder_sig,
                    vote.public_key.clone(),
                    placeholder_bls,
                    existing_type,
                    vote.high_qc_view,
                );

                let evidence = EquivocationEvidence::new(
                    vote.voter,
                    vote.view,
                    vote1,
                    vote.clone(),
                );

                // Store the evidence
                self.evidence.insert((vote.voter, vote.view), evidence.clone());
                self.persist_evidence(&evidence);

                tracing::warn!(
                    validator = %vote.voter,
                    view = vote.view,
                    block1 = %existing_hash,
                    block2 = %vote.block_hash,
                    "Equivocation detected"
                );

                return Ok(Some(evidence));
            }
        }

        // Record this vote
        let payload = (vote.block_hash, vote.vote_type);
        self.votes.insert(key.clone(), payload);
        self.persist_vote(&key, &payload);

        Ok(None)
    }

    /// Gets all detected equivocation evidence
    pub fn get_all_evidence(&self) -> Vec<EquivocationEvidence> {
        self.evidence.iter().map(|entry| entry.value().clone()).collect()
    }

    /// Gets equivocation evidence for a specific validator and view
    pub fn get_evidence(&self, validator: &Address, view: u64) -> Option<EquivocationEvidence> {
        self.evidence.get(&(*validator, view)).map(|e| e.clone())
    }

    /// Clears votes for views below the given minimum (cleanup).
    ///
    /// Prunes both the in-memory vote map AND the persisted
    /// `equivocation/votes/*` rows — without the persisted delete, every
    /// restart re-hydrated an unbounded backlog of stale votes that the
    /// in-memory prune had already discarded (unbounded CF_AUDIT growth
    /// plus stale-vote mis-fires after view-state resets).
    ///
    /// Evidence is deliberately KEPT — in memory and on disk. Evidence is
    /// the slashing record; pruning it by view would let an equivocator
    /// outlast the cleanup window and escape the penalty.
    pub fn cleanup_old_votes(&self, min_view: u64) {
        let mut pruned: Vec<ValidatorViewKey> = Vec::new();
        self.votes.retain(|key, _| {
            let keep = key.view >= min_view;
            if !keep {
                pruned.push(key.clone());
            }
            keep
        });
        if let Some(ref storage) = self.storage {
            for key in &pruned {
                let _ = storage.delete(
                    tenzro_storage::CF_AUDIT,
                    &Self::vote_key(&key.validator, key.view),
                );
            }
        }
    }

    /// Returns the number of tracked votes
    pub fn vote_count(&self) -> usize {
        self.votes.len()
    }

    /// Returns the number of detected equivocations
    pub fn evidence_count(&self) -> usize {
        self.evidence.len()
    }
}

impl Default for EquivocationDetector {
    fn default() -> Self {
        Self::new()
    }
}

// ---------------------------------------------------------------------------
// Proposer election
// ---------------------------------------------------------------------------

/// Strategy interface for selecting the proposer of a given round/view.
///
/// Two concrete implementations are provided:
///
/// - [`RoundRobinProposer`] — naïve `view % N` rotation. Useful for tests and
///   for validator sets so small that reputation history is not yet
///   meaningful. **Not recommended for production.**
/// - [`ReputationProposer`] — Aptos LeaderReputation. Stake-weighted draw
///   whose per-validator weight is multiplied by an observed-behaviour term
///   (active / inactive / failed). A flaky validator's effective weight
///   collapses to ~0.1% of a healthy peer's within ~20 rounds, which is what
///   prevents naïve round-robin from wedging the chain when one of N
///   validators is unresponsive.
///
/// The trait returns an [`Address`] (not a `&ValidatorInfo`) so it composes
/// cleanly with the engine's hot path: the engine resolves the address back
/// to the validator info via `validator_set.get_by_address` only when needed.
pub trait ProposerElection: Send + Sync {
    /// Selects the proposer for `round` in `epoch`.
    ///
    /// `prev_block_id` is the hash of the most recently finalized block —
    /// this is the anti-grinding seed component (the parent the new proposal
    /// will extend). For round-robin this argument is unused; for
    /// reputation-based selection it is mixed into the seed.
    fn select_leader(
        &self,
        round: u64,
        epoch: u64,
        prev_block_id: [u8; 32],
        validator_set: &ValidatorSet,
    ) -> Result<Address>;
}

/// Naïve `view % N` round-robin proposer.
///
/// Retained because some configurations (smoke tests, very small validator
/// sets, deterministic-replay benchmarks) genuinely want it. Production
/// deployments must use [`ReputationProposer`].
#[derive(Debug, Default, Clone, Copy)]
pub struct RoundRobinProposer;

impl RoundRobinProposer {
    pub const fn new() -> Self {
        Self
    }
}

impl ProposerElection for RoundRobinProposer {
    fn select_leader(
        &self,
        round: u64,
        _epoch: u64,
        _prev_block_id: [u8; 32],
        validator_set: &ValidatorSet,
    ) -> Result<Address> {
        validator_set
            .select_leader_round_robin(round)
            .map(|v| v.address)
    }
}

/// Aptos LeaderReputation proposer.
///
/// Wraps a shared [`LeaderReputation`] state and dispatches to its seeded
/// weighted draw. The wrapped state is the same one the engine feeds with
/// `record_round_outcome` / `record_round_voters` after each round closes —
/// so the reputation evolves alongside consensus rather than being a
/// per-call computation.
#[derive(Clone)]
pub struct ReputationProposer {
    reputation: Arc<LeaderReputation>,
}

impl ReputationProposer {
    /// Wraps an existing [`LeaderReputation`] instance.
    pub fn new(reputation: Arc<LeaderReputation>) -> Self {
        Self { reputation }
    }

    /// Borrowed handle to the wrapped reputation state — useful for the
    /// engine to record outcomes / voters after round close without going
    /// through the trait.
    pub fn reputation(&self) -> &Arc<LeaderReputation> {
        &self.reputation
    }
}

impl ProposerElection for ReputationProposer {
    fn select_leader(
        &self,
        round: u64,
        epoch: u64,
        prev_block_id: [u8; 32],
        validator_set: &ValidatorSet,
    ) -> Result<Address> {
        let prev_hash = Hash::new(prev_block_id);
        self.reputation
            .select_leader(round, epoch, &prev_hash, validator_set)
            .map(|v| v.address)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tenzro_crypto::bls::BlsKeyPair;
    use tenzro_crypto::pq::MlDsaSigningKey;
    use tenzro_crypto::{KeyPair, KeyType};

    fn create_test_validator(stake: u128) -> ValidatorInfo {
        let keypair = KeyPair::generate(KeyType::Ed25519).unwrap();
        // Convert tenzro_crypto::Address (20 bytes) to tenzro_types::Address (32 bytes)
        let crypto_addr = keypair.address();
        let mut addr_bytes = [0u8; 32];
        addr_bytes[..20].copy_from_slice(crypto_addr.as_bytes());
        let address = Address::new(addr_bytes);
        let pq = MlDsaSigningKey::generate();
        let bls = BlsKeyPair::generate().unwrap();
        ValidatorInfo::new(
            address,
            keypair.public_key().clone(),
            pq.verifying_key_bytes().to_vec(),
            bls.public_key().to_bytes().to_vec(),
            stake,
        )
    }

    #[test]
    fn test_validator_info() {
        let validator = create_test_validator(1000);
        assert_eq!(validator.voting_power(), 1000);
        assert!(validator.is_active());
        assert!(!validator.has_valid_tee_attestation());
    }

    #[test]
    fn test_validator_set_creation() {
        let validators = vec![
            create_test_validator(1000),
            create_test_validator(2000),
            create_test_validator(3000),
        ];

        let set = ValidatorSet::new(1, validators).unwrap();
        assert_eq!(set.len(), 3);
        assert_eq!(set.total_voting_power(), 6000);
        assert_eq!(set.quorum_threshold(), 1); // 2f+1 where f=(n-1)/3=(3-1)/3=0, so 2*0+1=1
    }

    #[test]
    fn test_leader_selection() {
        let validators = vec![
            create_test_validator(1000),
            create_test_validator(2000),
            create_test_validator(3000),
        ];

        let set = ValidatorSet::new(1, validators).unwrap();

        // Round-robin
        let leader0 = set.select_leader_round_robin(0).unwrap();
        let leader1 = set.select_leader_round_robin(1).unwrap();
        let leader2 = set.select_leader_round_robin(2).unwrap();
        let leader3 = set.select_leader_round_robin(3).unwrap();

        assert_eq!(leader0.address, set.validators[0].address);
        assert_eq!(leader1.address, set.validators[1].address);
        assert_eq!(leader2.address, set.validators[2].address);
        assert_eq!(leader3.address, set.validators[0].address); // wraps around
    }

    #[test]
    fn test_empty_validator_set() {
        let result = ValidatorSet::new(1, vec![]);
        assert!(result.is_err());
    }

    #[test]
    fn test_equivocation_detection() {
        use crate::voter::{Vote, VoteType};
        use tenzro_crypto::composite::{CompositePublicKey, CompositeSignature};
        use tenzro_types::primitives::BlockHeight;

        let detector = EquivocationDetector::new();
        let validator = create_test_validator(1000);

        let placeholder_pk = CompositePublicKey::new(
            validator.public_key.clone(),
            validator.pq_public_key.clone(),
        );
        let placeholder_sig = CompositeSignature::new(vec![0u8; 64], vec![0u8; 3309]);
        // EquivocationDetector::check_vote inspects view/voter/block_hash/vote_type
        // only, so a real BLS signature over arbitrary bytes is enough — the
        // detector never re-verifies it.
        let placeholder_bls_kp = BlsKeyPair::generate().unwrap();
        let placeholder_bls = placeholder_bls_kp.sign(b"__placeholder__");

        let vote1 = Vote::new(
            1,
            BlockHeight::from(10),
            Hash::default(),
            validator.address,
            placeholder_sig.clone(),
            placeholder_pk.clone(),
            placeholder_bls.clone(),
            VoteType::Prepare,
            0,
        );

        // First vote should be recorded without issue
        let result = detector.check_vote(&vote1);
        assert!(result.is_ok());
        assert!(result.unwrap().is_none());

        // Same vote again should error (already voted)
        let result = detector.check_vote(&vote1);
        assert!(result.is_err());

        // Different block hash in same view should detect equivocation
        let mut different_hash = [0u8; 32];
        different_hash[0] = 1;
        let vote2 = Vote::new(
            1,
            BlockHeight::from(10),
            Hash::new(different_hash),
            validator.address,
            placeholder_sig.clone(),
            placeholder_pk.clone(),
            placeholder_bls.clone(),
            VoteType::Prepare,
            0,
        );

        let result = detector.check_vote(&vote2);
        assert!(result.is_ok());
        let evidence = result.unwrap();
        assert!(evidence.is_some());

        let evidence = evidence.unwrap();
        assert_eq!(evidence.validator, validator.address);
        assert_eq!(evidence.view, 1);
        assert!(evidence.is_valid());
    }

    #[test]
    fn test_equivocation_detector_cleanup() {
        use crate::voter::{Vote, VoteType};
        use tenzro_crypto::composite::{CompositePublicKey, CompositeSignature};
        use tenzro_types::primitives::BlockHeight;

        let detector = EquivocationDetector::new();
        let validator = create_test_validator(1000);

        let placeholder_pk = CompositePublicKey::new(
            validator.public_key.clone(),
            validator.pq_public_key.clone(),
        );
        let placeholder_sig = CompositeSignature::new(vec![0u8; 64], vec![0u8; 3309]);
        let placeholder_bls_kp = BlsKeyPair::generate().unwrap();
        let placeholder_bls = placeholder_bls_kp.sign(b"__placeholder__");

        // Add votes for views 1, 2, 3
        for view in 1..=3 {
            let vote = Vote::new(
                view,
                BlockHeight::from(10),
                Hash::default(),
                validator.address,
                placeholder_sig.clone(),
                placeholder_pk.clone(),
                placeholder_bls.clone(),
                VoteType::Prepare,
                0,
            );
            let _ = detector.check_vote(&vote);
        }

        assert_eq!(detector.vote_count(), 3);

        // Cleanup views below 2
        detector.cleanup_old_votes(2);

        // Should only have views 2 and 3 remaining
        assert_eq!(detector.vote_count(), 2);
    }
}