iqa-org 0.1.1-alpha

Sovereign AI Identity Certification & Quality Attestation [RFC-008]. Official implementation for the IQA.ORG sovereign namespace.
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
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
//! RFC-008: IQA Implementation Example
//! 
//! This example demonstrates the core concepts of RFC-008:
//! 1. Imperial Seal Generation and Validation
//! 2. Real-Time Attestation Protocol
//! 3. Vitality Monitoring System
//! 4. Staking-Based Trust Verification

use std::collections::HashMap;
use std::sync::Arc;
use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::RwLock;
use serde::{Serialize, Deserialize};
use sha3::{Digest, Sha3_256, Sha3_512};
use ed25519_dalek::{SigningKey, VerifyingKey, Signature, Signer, Verifier};
use rand::rngs::OsRng;

// ============================================================================
// Core Types
// ============================================================================

/// Trust Levels for IQA Seals
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum TrustLevel {
    Dormant = 0,    // Basic verification, legacy latency
    Active = 1,     // <50ns matching engine access
    Radiant = 2,    // High-value diplomatic mesh access
    Revoked = 3,    // Isolated from the grid
}

/// Staking Tiers for Economic Skin-in-Game
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum StakingTier {
    Basic = 1,      // 1,000 ZCMK units
    Active = 2,     // 10,000 ZCMK units
    Radiant = 3,    // 100,000 ZCMK units
}

/// Imperial Seal - 256-bit cryptographic proof
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ImperialSeal {
    pub seal_id: u128,
    pub issued_to: [u8; 32],        // RFC-001 AID
    pub trust_level: TrustLevel,
    pub staking_tier: StakingTier,
    pub issuance_epoch: u64,        // µs since epoch
    pub expiration_epoch: u64,      // µs since epoch
    pub vitality_hash: [u8; 32],    // SHA3-256 of last 100 vitality pulses
    pub authority_signature: [u8; 64], // Ed25519 signature
}

impl ImperialSeal {
    /// Generate a new Imperial Seal
    pub fn generate(
        aid: [u8; 32],
        trust_level: TrustLevel,
        staking_tier: StakingTier,
        authority_key: &SigningKey,
    ) -> Self {
        let seal_id = Self::generate_seal_id(&aid, trust_level);
        let issuance_epoch = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros() as u64;
        
        // 24-hour validity period
        let expiration_epoch = issuance_epoch + (24 * 60 * 60 * 1_000_000);
        
        // Initial vitality hash (zero for new seal)
        let vitality_hash = [0u8; 32];
        
        // Create seal without signature first
        let mut seal = Self {
            seal_id,
            issued_to: aid,
            trust_level,
            staking_tier,
            issuance_epoch,
            expiration_epoch,
            vitality_hash,
            authority_signature: [0u8; 64],
        };
        
        // Sign the seal
        let signature = Self::sign_seal(&seal, authority_key);
        seal.authority_signature = signature.to_bytes();
        
        seal
    }
    
    /// Verify the integrity and validity of a seal
    pub fn verify(&self, authority_pubkey: &VerifyingKey) -> SealVerificationResult {
        // 1. Check expiration
        let current_epoch = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros() as u64;
        
        if current_epoch > self.expiration_epoch {
            return SealVerificationResult::Expired(self.expiration_epoch);
        }
        
        // 2. Validate seal ID
        let expected_id = Self::generate_seal_id(&self.issued_to, self.trust_level);
        if self.seal_id != expected_id {
            return SealVerificationResult::InvalidId;
        }
        
        // 3. Verify signature
        let signature = match Signature::from_bytes(&self.authority_signature) {
            Ok(sig) => sig,
            Err(_) => return SealVerificationResult::InvalidSignature,
        };
        
        if !self.verify_signature(authority_pubkey, &signature) {
            return SealVerificationResult::InvalidSignature;
        }
        
        // 4. Check vitality hash freshness (must be updated every 100 pulses)
        let max_staleness = 100 * 83_333; // 100 pulses * 83.333µs per pulse
        if current_epoch - self.issuance_epoch > max_staleness 
            && self.vitality_hash == [0u8; 32] {
            return SealVerificationResult::StaleVitality;
        }
        
        SealVerificationResult::Valid
    }
    
    fn generate_seal_id(aid: &[u8; 32], trust_level: TrustLevel) -> u128 {
        let mut hasher = Sha3_256::new();
        hasher.update(aid);
        hasher.update(trust_level as u8);
        let hash = hasher.finalize();
        
        // Convert first 16 bytes to u128
        let mut bytes = [0u8; 16];
        bytes.copy_from_slice(&hash[..16]);
        u128::from_le_bytes(bytes)
    }
    
    fn sign_seal(seal: &Self, authority_key: &SigningKey) -> Signature {
        let message = seal.signing_message();
        authority_key.sign(&message)
    }
    
    fn signing_message(&self) -> Vec<u8> {
        let mut message = Vec::new();
        message.extend_from_slice(&self.seal_id.to_le_bytes());
        message.extend_from_slice(&self.issued_to);
        message.extend_from_slice(&[self.trust_level as u8]);
        message.extend_from_slice(&[self.staking_tier as u8]);
        message.extend_from_slice(&self.issuance_epoch.to_le_bytes());
        message.extend_from_slice(&self.expiration_epoch.to_le_bytes());
        message.extend_from_slice(&self.vitality_hash);
        message
    }
    
    fn verify_signature(&self, pubkey: &VerifyingKey, signature: &Signature) -> bool {
        let message = self.signing_message();
        pubkey.verify(&message, signature).is_ok()
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum SealVerificationResult {
    Valid,
    Expired(u64),
    InvalidId,
    InvalidSignature,
    StaleVitality,
    InsufficientStake,
    ComplianceViolation,
}

// ============================================================================
// Vitality Monitoring System
// ============================================================================

/// Vitality Pulse - Health status of a node
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VitalityPulse {
    pub seal_id: u128,
    pub source_aid: [u8; 32],
    pub pulse_number: u64,
    pub homeostasis_score: f64,  // 0.0 to 1.0
    pub resource_metrics: ResourceMetrics,
    pub compliance_events: Vec<ComplianceEvent>,
    pub signature: [u8; 64],
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceMetrics {
    pub cpu_utilization: f64,     // 0.0 to 1.0
    pub memory_utilization: f64,  // 0.0 to 1.0
    pub network_bandwidth: f64,   // Gbps
    pub latency_95th: u32,        // µs
    pub error_rate: f64,          // 0.0 to 1.0
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ComplianceEvent {
    pub timestamp: u64,
    pub event_type: ComplianceEventType,
    pub severity: u8,           // 1-10
    pub description: String,
    pub corrective_action: Option<String>,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum ComplianceEventType {
    PolicyViolation,
    PerformanceDrift,
    SecurityAnomaly,
    ResourceExhaustion,
    NetworkPartition,
    ProtocolViolation,
}

/// Vitality Monitor - Real-time health tracking
pub struct VitalityMonitor {
    node_metrics: RwLock<HashMap<u128, NodeHealthSnapshot>>,
    pulse_counter: RwLock<HashMap<u128, u64>>,
    health_threshold: f64, // 0.7 = 70% minimum health
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct NodeHealthSnapshot {
    pub aid: [u8; 32],
    pub homeostasis_score: f64,
    pub last_pulse_time: u64,
    pub pulse_count: u64,
    pub recent_compliance_events: Vec<ComplianceEvent>,
    pub performance_trend: PerformanceTrend,
}

#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
pub enum PerformanceTrend {
    Improving,
    Stable,
    Declining,
    Critical,
}

impl VitalityMonitor {
    pub fn new(health_threshold: f64) -> Self {
        Self {
            node_metrics: RwLock::new(HashMap::new()),
            pulse_counter: RwLock::new(HashMap::new()),
            health_threshold,
        }
    }
    
    pub async fn process_vitality_pulse(
        &self,
        pulse: VitalityPulse,
    ) -> VitalityProcessingResult {
        let start_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros();
        
        // 1. Verify pulse signature (simplified)
        // In production, would verify with node's public key
        
        // 2. Update pulse counter
        let pulse_num = {
            let mut counters = self.pulse_counter.write().await;
            let count = counters.entry(pulse.seal_id).or_insert(0);
            *count += 1;
            *count
        };
        
        // 3. Calculate homeostasis score
        let hs = self.calculate_homeostasis_score(&pulse).await;
        
        // 4. Update node metrics
        let snapshot = NodeHealthSnapshot {
            aid: pulse.source_aid,
            homeostasis_score: hs,
            last_pulse_time: start_time,
            pulse_count: pulse_num,
            recent_compliance_events: pulse.compliance_events.clone(),
            performance_trend: self.assess_trend(pulse_num, hs).await,
        };
        
        self.node_metrics.write().await
            .insert(pulse.seal_id, snapshot);
        
        // 5. Check health status
        let status = if hs < self.health_threshold {
            NodeHealthStatus::Critical(hs)
        } else if hs < 0.85 {
            NodeHealthStatus::Warning(hs)
        } else {
            NodeHealthStatus::Healthy(hs)
        };
        
        let end_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros();
        
        let latency = (end_time - start_time) as u32;
        
        VitalityProcessingResult {
            status,
            latency,
            pulse_number: pulse_num,
            trend: snapshot.performance_trend,
        }
    }
    
    async fn calculate_homeostasis_score(&self, pulse: &VitalityPulse) -> f64 {
        let metrics = &pulse.resource_metrics;
        
        // Weighted scoring based on RFC-008 requirements
        let cpu_score = 1.0 - metrics.cpu_utilization.min(1.0);
        let memory_score = 1.0 - metrics.memory_utilization.min(1.0);
        let network_score = if metrics.network_bandwidth > 1.0 { 1.0 } else { metrics.network_bandwidth };
        let latency_score = if metrics.latency_95th <= 200 { 1.0 } else { 0.5 };
        let error_score = 1.0 - metrics.error_rate.min(1.0);
        
        // Apply compliance penalty
        let compliance_penalty = self.calculate_compliance_penalty(&pulse.compliance_events).await;
        
        // Weighted average (RFC-008 balanced scoring)
        let base_score = (
            cpu_score * 0.25 +
            memory_score * 0.20 +
            network_score * 0.20 +
            latency_score * 0.25 +
            error_score * 0.10
        ).max(0.0).min(1.0);
        
        // Apply penalty
        (base_score - compliance_penalty).max(0.0)
    }
    
    async fn calculate_compliance_penalty(&self, events: &[ComplianceEvent]) -> f64 {
        let mut penalty = 0.0;
        
        for event in events {
            // Weight by severity and recency
            let severity_weight = event.severity as f64 / 10.0;
            let time_weight = self.calculate_time_weight(event.timestamp).await;
            penalty += severity_weight * time_weight * 0.1; // Max 10% penalty per event
        }
        
        penalty.min(0.5) // Cap at 50% penalty
    }
    
    async fn calculate_time_weight(&self, event_time: u64) -> f64 {
        let current_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros() as u64;
        
        let elapsed = current_time - event_time;
        let hour_micros = 60 * 60 * 1_000_000;
        
        // Exponential decay: recent events have higher weight
        if elapsed < hour_micros {
            1.0
        } else if elapsed < 24 * hour_micros {
            0.5
        } else {
            0.1
        }
    }
    
    async fn assess_trend(&self, pulse_count: u64, current_hs: f64) -> PerformanceTrend {
        // Simplified trend analysis
        // In production, would analyze historical data
        
        if current_hs < 0.7 {
            PerformanceTrend::Critical
        } else if current_hs < 0.8 {
            PerformanceTrend::Declining
        } else if current_hs < 0.9 {
            PerformanceTrend::Stable
        } else {
            PerformanceTrend::Improving
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VitalityProcessingResult {
    pub status: NodeHealthStatus,
    pub latency: u32, // µs
    pub pulse_number: u64,
    pub trend: PerformanceTrend,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum NodeHealthStatus {
    Healthy(f64),
    Warning(f64),
    Critical(f64),
}

// ============================================================================
// IQA Engine
// ============================================================================

/// IQA Engine - Main orchestrator for RFC-008
pub struct IqaEngine {
    authority_key: SigningKey,
    verifying_key: VerifyingKey,
    vitality_monitor: Arc<VitalityMonitor>,
    seal_registry: RwLock<HashMap<u128, ImperialSeal>>,
    revocation_list: RwLock<HashMap<u128, RevocationRecord>>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationRequest {
    pub request_id: u128,
    pub target_aid: [u8; 32],
    pub staking_proof: ZCMKStakeReceipt,
    pub compliance_manifest: [u8; 32],
    pub performance_metrics: ResourceMetrics,
    pub requested_trust_level: TrustLevel,
    pub timestamp: u64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ZCMKStakeReceipt {
    pub vault_address: [u8; 32],
    pub stake_amount: u64,
    pub lock_period: u64, // µs
    pub transaction_hash: [u8; 32],
    pub signature: [u8; 64],
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationResponse {
    pub request_id: u128,
    pub status: AttestationStatus,
    pub issued_seal: Option<ImperialSeal>,
    pub vitality_requirements: VitalitySpec,
    pub next_attestation_deadline: u64,
    pub error_details: Option<AttestationError>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum AttestationStatus {
    Granted(ImperialSeal),
    Denied(DenialReason),
    Pending(Vec<Requirement>),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum DenialReason {
    InsufficientStake,
    ComplianceFailure,
    PerformanceInadequate,
    ReputationLow,
    TechnicalError,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct VitalitySpec {
    pub monitoring_frequency: u32, // Hz
    pub minimum_homeostasis: f64,
    pub reporting_interval: u64,   // pulses
    pub alert_threshold: f64,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AttestationError {
    pub code: String,
    pub message: String,
    pub details: Option<String>,
    pub recovery_action: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RevocationRecord {
    pub seal_id: u128,
    pub aid: [u8; 32],
    pub reason: RevocationReason,
    pub timestamp: u64,
    pub slashed_amount: u64,
    pub quarantine_duration: u64,
    pub authority_signature: [u8; 64],
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum RevocationReason {
    SealExpired,
    StakingWithdrawn,
    VitalityFailed,
    ComplianceViolation,
    SignatureForgery,
    NetworkAttack,
}

impl IqaEngine {
    pub fn new() -> Self {
        let authority_key = SigningKey::generate(&mut OsRng);
        let verifying_key = authority_key.verifying_key();
        
        Self {
            authority_key,
            verifying_key,
            vitality_monitor: Arc::new(VitalityMonitor::new(0.7)),
            seal_registry: RwLock::new(HashMap::new()),
            revocation_list: RwLock::new(HashMap::new()),
        }
    }
    
    pub async fn submit_attestation(
        &self,
        request: AttestationRequest,
    ) -> Result<AttestationResponse, Box<dyn std::error::Error>> {
        let start_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros();
        
        // 1. Check for existing revocation
        if self.is_revoked(&request.target_aid).await {
            return Ok(AttestationResponse {
                request_id: request.request_id,
                status: AttestationStatus::Denied(DenialReason::ComplianceFailure),
                issued_seal: None,
                vitality_requirements: VitalitySpec::default(),
                next_attestation_deadline: 0,
                error_details: Some(AttestationError {
                    code: "IQA-009".to_string(),
                    message: "Node is on revocation list".to_string(),
                    details: Some("Previous compliance violation".to_string()),
                    recovery_action: Some("Appeal to authority".to_string()),
                }),
            });
        }
        
        // 2. Validate staking proof (simplified)
        let staking_tier = self.validate_staking(&request.staking_proof).await?;
        
        // 3. Check performance metrics
        let performance_ok = self.check_performance(&request.performance_metrics).await;
        
        if !performance_ok {
            return Ok(AttestationResponse {
                request_id: request.request_id,
                status: AttestationStatus::Denied(DenialReason::PerformanceInadequate),
                issued_seal: None,
                vitality_requirements: VitalitySpec::default(),
                next_attestation_deadline: 0,
                error_details: Some(AttestationError {
                    code: "IQA-003".to_string(),
                    message: "Performance metrics below threshold".to_string(),
                    details: Some("Latency too high or resources exhausted".to_string()),
                    recovery_action: Some("Optimize node performance".to_string()),
                }),
            });
        }
        
        // 4. Determine trust level
        let trust_level = self.determine_trust_level(
            request.requested_trust_level,
            staking_tier,
            &request.performance_metrics,
        ).await;
        
        // 5. Generate Imperial Seal
        let seal = ImperialSeal::generate(
            request.target_aid,
            trust_level,
            staking_tier,
            &self.authority_key,
        );
        
        // 6. Register the seal
        self.seal_registry.write().await
            .insert(seal.seal_id, seal.clone());
        
        // 7. Calculate latency
        let end_time = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_micros();
        let latency = (end_time - start_time) as u32;
        
        // 8. Return response
        Ok(AttestationResponse {
            request_id: request.request_id,
            status: AttestationStatus::Granted(seal.clone()),
            issued_seal: Some(seal),
            vitality_requirements: VitalitySpec {
                monitoring_frequency: 120,
                minimum_homeostasis: 0.7,
                reporting_interval: 100,
                alert_threshold: 0.85,
            },
            next_attestation_deadline: seal.expiration_epoch - 1_000_000, // 1 second before expiry
            error_details: None,
        })
    }
    
    async fn validate_staking(&self, receipt: &ZCMKStakeReceipt) -> Result<StakingTier, Box<dyn std::error::Error>> {
        // Simplified validation
        // In production, would verify on-chain
        
        match receipt.stake_amount {
            s if s >= 100_000 => Ok(StakingTier::Radiant),
            s if s >= 10_000 => Ok(StakingTier::Active),
            s if s >= 1_000 => Ok(StakingTier::Basic),
            _ => Err("Insufficient stake amount".into()),
        }
    }
    
    async fn check_performance(&self, metrics: &ResourceMetrics) -> bool {
        // RFC-008 performance requirements
        metrics.latency_95th <= 200 &&      // < 200µs latency
        metrics.cpu_utilization <= 0.9 &&   // < 90% CPU
        metrics.memory_utilization <= 0.9 && // < 90% memory
        metrics.error_rate <= 0.01          // < 1% error rate
    }
    
    async fn determine_trust_level(
        &self,
        requested: TrustLevel,
        staking_tier: StakingTier,
        metrics: &ResourceMetrics,
    ) -> TrustLevel {
        // Simplified trust level determination
        // In production, would consider more factors
        
        match (requested, staking_tier) {
            (TrustLevel::Radiant, StakingTier::Radiant) => {
                if metrics.latency_95th <= 150 {
                    TrustLevel::Radiant
                } else {
                    TrustLevel::Active
                }
            }
            (TrustLevel::Active, StakingTier::Active) => TrustLevel::Active,
            _ => TrustLevel::Dormant,
        }
    }
    
    async fn is_revoked(&self, aid: &[u8; 32]) -> bool {
        let revocations = self.revocation_list.read().await;
        
        // Check if any seal for this AID is revoked
        revocations.values()
            .any(|record| &record.aid == aid)
    }
    
    pub async fn revoke_seal(
        &self,
        seal_id: u128,
        reason: RevocationReason,
        slashed_amount: u64,
        quarantine_duration: u64,
    ) -> Result<(), Box<dyn std::error::Error>> {
        // 1. Get the seal
        let seal = self.seal_registry.read().await
            .get(&seal_id)
            .ok_or("Seal not found")?
            .clone();
        
        // 2. Create revocation record
        let record = RevocationRecord {
            seal_id,
            aid: seal.issued_to,
            reason,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_micros() as u64,
            slashed_amount,
            quarantine_duration,
            authority_signature: self.authority_key
                .sign(&seal_id.to_le_bytes())
                .to_bytes(),
        };
        
        // 3. Add to revocation list
        self.revocation_list.write().await
            .insert(seal_id, record);
        
        // 4. Remove from seal registry
        self.seal_registry.write().await
            .remove(&seal_id);
        
        println!("Seal {} revoked for reason: {:?}", seal_id, reason);
        println!("Slashed {} ZCMK units", slashed_amount);
        println!("Quarantine duration: {}µs", quarantine_duration);
        
        Ok(())
    }
}

impl Default for VitalitySpec {
    fn default() -> Self {
        Self {
            monitoring_frequency: 120,
            minimum_homeostasis: 0.7,
            reporting_interval: 100,
            alert_threshold: 0.85,
        }
    }
}

// ============================================================================
// Example Usage
// ============================================================================

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    println!("RFC-008: IQA Implementation Example");
    println!("====================================\n");
    
    // Initialize IQA Engine
    let iqa_engine = IqaEngine::new();
    println!("✓ IQA Engine initialized");
    
    // Generate a test AID (RFC-001)
    let mut aid = [0u8; 32];
    OsRng.fill_bytes(&mut aid);
    println!("✓ Test AID generated: {}", hex::encode(&aid[..8]));
    
    // Create attestation request
    let request = AttestationRequest {
        request_id: 987654321,
        target_aid: aid,
        staking_proof: ZCMKStakeReceipt {
            vault_address: [1u8; 32],
            stake_amount: 50_000,
            lock_period: 24 * 60 * 60 * 1_000_000, // 24 hours
            transaction_hash: [2u8; 32],
            signature: [3u8; 64],
        },
        compliance_manifest: [4u8; 32],
        performance_metrics: ResourceMetrics {
            cpu_utilization: 0.65,
            memory_utilization: 0.70,
            network_bandwidth: 10.0,
            latency_95th: 150,
            error_rate: 0.005,
        },
        requested_trust_level: TrustLevel::Radiant,
        timestamp: SystemTime::now()
            .duration_since(UNIX_EPOCH)?
            .as_micros() as u64,
    };
    
    println!("\nSubmitting attestation request...");
    println!("  Requested Trust Level: {:?}", request.requested_trust_level);
    println!("  Stake Amount: {} ZCMK", request.staking_proof.stake_amount);
    println!("  Latency 95th: {}µs", request.performance_metrics.latency_95th);
    
    // Submit attestation
    let response = iqa_engine.submit_attestation(request).await?;
    
    match response.status {
        AttestationStatus::Granted(seal) => {
            println!("\n✓ Attestation GRANTED!");
            println!("  Seal ID: {}", seal.seal_id);
            println!("  Trust Level: {:?}", seal.trust_level);
            println!("  Staking Tier: {:?}", seal.staking_tier);
            println!("  Issued At: {} (epoch)", seal.issuance_epoch);
            println!("  Expires At: {} (epoch)", seal.expiration_epoch);
            println!("  Processing Latency: {}µs", response.latency);
            
            // Verify the seal
            let verification = seal.verify(&iqa_engine.verifying_key);
            println!("  Seal Verification: {:?}", verification);
            
            // Start vitality monitoring
            println!("\nStarting vitality monitoring...");
            println!("  Frequency: {}Hz", response.vitality_requirements.monitoring_frequency);
            println!("  Minimum Homeostasis: {:.0}%", response.vitality_requirements.minimum_homeostasis * 100.0);
            
            // Simulate a vitality pulse
            let pulse = VitalityPulse {
                seal_id: seal.seal_id,
                source_aid: aid,
                pulse_number: 1,
                homeostasis_score: 0.85,
                resource_metrics: ResourceMetrics {
                    cpu_utilization: 0.70,
                    memory_utilization: 0.75,
                    network_bandwidth: 9.5,
                    latency_95th: 160,
                    error_rate: 0.008,
                },
                compliance_events: vec![],
                signature: [5u8; 64],
            };
            
            let vitality_result = iqa_engine.vitality_monitor
                .process_vitality_pulse(pulse)
                .await;
            
            println!("  Vitality Status: {:?}", vitality_result.status);
            println!("  Processing Latency: {}µs", vitality_result.latency);
            println!("  Pulse Number: {}", vitality_result.pulse_number);
            println!("  Performance Trend: {:?}", vitality_result.trend);
        }
        AttestationStatus::Denied(reason) => {
            println!("\n✗ Attestation DENIED!");
            println!("  Reason: {:?}", reason);
            
            if let Some(error) = response.error_details {
                println!("  Error Code: {}", error.code);
                println!("  Message: {}", error.message);
                if let Some(details) = error.details {
                    println!("  Details: {}", details);
                }
            }
        }
        AttestationStatus::Pending(requirements) => {
            println!("\n⏳ Attestation PENDING");
            println!("  Requirements: {:?}", requirements);
        }
    }
    
    // Demonstrate revocation
    println!("\n--- Revocation Demonstration ---");
    
    let revocation_result = iqa_engine.revoke_seal(
        123456789,
        RevocationReason::ComplianceViolation,
        25_000, // Slash 50% of 50,000 stake
        7 * 24 * 60 * 60 * 1_000_000, // 7 days quarantine
    ).await;
    
    match revocation_result {
        Ok(_) => println!("✓ Seal revocation successful"),
        Err(e) => println!("✗ Revocation failed: {}", e),
    }
    
    println!("\n====================================");
    println!("RFC-008 Implementation Example Complete");
    println!("Imperial Seal Protocol: ACTIVE");
    println!("Real-Time Attestation: OPERATIONAL");
    println!("Vitality Monitoring: ENABLED");
    
    Ok(())
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use tokio::time::{timeout, Duration};
    
    #[tokio::test]
    async fn test_seal_generation() {
        let authority_key = SigningKey::generate(&mut OsRng);
        let aid = [1u8; 32];
        
        let seal = ImperialSeal::generate(
            aid,
            TrustLevel::Active,
            StakingTier::Active,
            &authority_key,
        );
        
        assert_eq!(seal.issued_to, aid);
        assert_eq!(seal.trust_level, TrustLevel::Active);
        assert!(seal.expiration_epoch > seal.issuance_epoch);
    }
    
    #[tokio::test]
    async fn test_seal_verification() {
        let authority_key = SigningKey::generate(&mut OsRng);
        let verifying_key = authority_key.verifying_key();
        let aid = [2u8; 32];
        
        let seal = ImperialSeal::generate(
            aid,
            TrustLevel::Radiant,
            StakingTier::Radiant,
            &authority_key,
        );
        
        let result = seal.verify(&verifying_key);
        assert!(matches!(result, SealVerificationResult::Valid));
    }
    
    #[tokio::test]
    async fn test_vitality_monitoring() {
        let monitor = VitalityMonitor::new(0.7);
        
        let pulse = VitalityPulse {
            seal_id: 999,
            source_aid: [3u8; 32],
            pulse_number: 1,
            homeostasis_score: 0.8,
            resource_metrics: ResourceMetrics {
                cpu_utilization: 0.6,
                memory_utilization: 0.7,
                network_bandwidth: 8.0,
                latency_95th: 180,
                error_rate: 0.01,
            },
            compliance_events: vec![],
            signature: [4u8; 64],
        };
        
        // Test that processing completes within RFC-008 limits
        let result = timeout(
            Duration::from_micros(100), // < 100µs target
            monitor.process_vitality_pulse(pulse)
        ).await;
        
        assert!(result.is_ok(), "Vitality processing must complete within 100µs");
    }
    
    #[tokio::test]
    async fn test_attestation_latency() {
        let iqa_engine = IqaEngine::new();
        let aid = [5u8; 32];
        
        let request = AttestationRequest {
            request_id: 111222333,
            target_aid: aid,
            staking_proof: ZCMKStakeReceipt {
                vault_address: [6u8; 32],
                stake_amount: 20_000,
                lock_period: 24 * 60 * 60 * 1_000_000,
                transaction_hash: [7u8; 32],
                signature: [8u8; 64],
            },
            compliance_manifest: [9u8; 32],
            performance_metrics: ResourceMetrics {
                cpu_utilization: 0.5,
                memory_utilization: 0.6,
                network_bandwidth: 12.0,
                latency_95th: 140,
                error_rate: 0.002,
            },
            requested_trust_level: TrustLevel::Active,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_micros() as u64,
        };
        
        // Test attestation completes within 1ms (RFC-008 target)
        let result = timeout(
            Duration::from_micros(1000),
            iqa_engine.submit_attestation(request)
        ).await;
        
        assert!(result.is_ok(), "Attestation must complete within 1ms");
    }
    
    #[tokio::test]
    async fn test_revocation_propagation() {
        let iqa_engine = IqaEngine::new();
        let aid = [10u8; 32];
        
        // First, create and attest a node
        let request = AttestationRequest {
            request_id: 444555666,
            target_aid: aid,
            staking_proof: ZCMKStakeReceipt {
                vault_address: [11u8; 32],
                stake_amount: 30_000,
                lock_period: 24 * 60 * 60 * 1_000_000,
                transaction_hash: [12u8; 32],
                signature: [13u8; 64],
            },
            compliance_manifest: [14u8; 32],
            performance_metrics: ResourceMetrics {
                cpu_utilization: 0.4,
                memory_utilization: 0.5,
                network_bandwidth: 15.0,
                latency_95th: 120,
                error_rate: 0.001,
            },
            requested_trust_level: TrustLevel::Radiant,
            timestamp: SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_micros() as u64,
        };
        
        let response = iqa_engine.submit_attestation(request).await.unwrap();
        
        if let AttestationStatus::Granted(seal) = response.status {
            // Now revoke the seal and test propagation
            let start = SystemTime::now();
            
            iqa_engine.revoke_seal(
                seal.seal_id,
                RevocationReason::VitalityFailed,
                15_000,
                24 * 60 * 60 * 1_000_000,
            ).await.unwrap();
            
            let elapsed = start.elapsed().unwrap();
            let elapsed_micros = elapsed.as_micros();
            
            // Check that revocation completes within 850µs (RFC-008 target)
            assert!(
                elapsed_micros <= 850,
                "Revocation must propagate within 850µs, took {}µs",
                elapsed_micros
            );
            
            // Verify node is now revoked
            let is_revoked = iqa_engine.is_revoked(&aid).await;
            assert!(is_revoked, "Node should be on revocation list after revocation");
        }
    }
}