1#![cfg_attr(not(feature = "std"), no_std)]
43#![cfg_attr(docsrs, feature(doc_cfg))]
44
45#[cfg(all(not(feature = "std"), feature = "serde"))]
46extern crate alloc;
47
48#[cfg(all(not(feature = "std"), feature = "serde"))]
49use alloc::{string::String, vec::Vec};
50
51#[cfg(feature = "serde")]
52use serde::{Deserialize, Serialize};
53
54pub use omwei_atom::trust_hierarchy::{get_trust_level, validate_atom, Atom, TrustLevel, ValidationResult};
56
57use anyhow::Result;
58use chrono::{DateTime, Utc};
59use log::{debug, error, info, warn};
60use std::collections::HashMap;
61use uuid::Uuid;
62
63pub type Metadata = HashMap<String, String>;
65
66#[derive(Debug, Clone)]
68#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
69pub struct LogicGateResult {
70 pub is_valid: bool,
72 pub trust_level: TrustLevel,
74 pub timestamp: DateTime<Utc>,
76 pub latency_ns: u64,
78 pub policy: ValidationPolicy,
80 pub details: ValidationDetails,
82 pub metadata: Metadata,
84}
85
86#[derive(Debug, Clone)]
88#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
89pub struct ValidationDetails {
90 pub sincerity_bit: bool,
92 pub trust_determination_ns: u64,
94 pub pqc_verification_ns: Option<u64>,
96 pub hardware_accelerated: bool,
98 pub validation_steps: Vec<ValidationStep>,
100}
101
102#[derive(Debug, Clone)]
104#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
105pub struct ValidationStep {
106 pub step_id: String,
108 pub step_name: String,
110 pub duration_ns: u64,
112 pub result: StepResult,
114 pub metadata: Metadata,
116}
117
118#[derive(Debug, Clone)]
120pub enum StepResult {
121 Success,
123 Failure,
125 Skipped,
127 Pending,
129}
130
131#[derive(Debug, Clone)]
133#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
134pub struct ValidationPolicy {
135 pub policy_id: Uuid,
137 pub policy_name: String,
139 pub strict_mode: bool,
141 pub allow_community: bool,
143 pub require_pqc_managed: bool,
145 pub max_processing_time_ns: u64,
147 pub hardware_acceleration: HardwareAcceleration,
149}
150
151#[derive(Debug, Clone)]
153pub enum HardwareAcceleration {
154 None,
156 Preferred,
158 Required,
160}
161
162pub struct SamsLogicGate {
167 gate_id: Uuid,
169 policy: ValidationPolicy,
171 metrics: LogicGateMetrics,
173 pipeline: ValidationPipeline,
175 hardware_status: HardwareStatus,
177}
178
179struct ValidationPipeline {
181 steps: Vec<Box<dyn ValidationStepTrait>>,
183 config: PipelineConfig,
185}
186
187#[derive(Debug, Clone)]
189struct PipelineConfig {
190 pub max_depth: usize,
192 pub parallel_processing: bool,
194 pub step_timeout_ns: u64,
196}
197
198#[derive(Debug)]
200struct HardwareStatus {
201 pub silicon_catalyst_available: bool,
203 pub hardware_acceleration_enabled: bool,
205 pub cpu_features: Vec<String>,
207 pub cache_line_size: usize,
209}
210
211#[derive(Debug, Default)]
213pub struct LogicGateMetrics {
214 pub total_processed: u64,
216 pub managed_processed: u64,
218 pub community_processed: u64,
220 pub avg_latency_ns: f64,
222 pub validation_failures: u64,
224 pub hardware_accelerated_ops: u64,
226 pub trust_determinations: u64,
228 pub pqc_verifications: u64,
230}
231
232trait ValidationStepTrait: Send + Sync {
234 fn execute(&self, atom: &Atom, context: &mut ValidationContext) -> Result<StepResult>;
236 fn name(&self) -> &str;
238 fn step_id(&self) -> &str;
240}
241
242#[derive(Debug)]
244struct ValidationContext {
245 trust_level: Option<TrustLevel>,
247 step_results: HashMap<String, StepResult>,
249 metadata: Metadata,
251 start_time: DateTime<Utc>,
253}
254
255struct TrustDeterminationStep {
257 step_id: String,
258 hardware_accelerated: bool,
259}
260
261impl ValidationStepTrait for TrustDeterminationStep {
262 fn execute(&self, atom: &Atom, context: &mut ValidationContext) -> Result<StepResult> {
263 let start_time = std::time::Instant::now();
264
265 let trust_level = get_trust_level(atom.global_id);
267 context.trust_level = Some(trust_level);
268
269 let duration = start_time.elapsed().as_nanos() as u64;
270
271 context.metadata.insert(
272 "trust_determination_ns".to_string(),
273 duration.to_string(),
274 );
275 context.metadata.insert(
276 "sincerity_bit".to_string(),
277 ((atom.global_id & 0x80000000) != 0).to_string(),
278 );
279
280 debug!(
281 "TrustDeterminationStep: Determined trust level {:?} in {} ns",
282 trust_level, duration
283 );
284
285 Ok(StepResult::Success)
286 }
287
288 fn name(&self) -> &str {
289 "Trust Determination"
290 }
291
292 fn step_id(&self) -> &str {
293 &self.step_id
294 }
295}
296
297struct PqcVerificationStep {
299 step_id: String,
300 require_pqc: bool,
301}
302
303impl ValidationStepTrait for PqcVerificationStep {
304 fn execute(&self, atom: &Atom, context: &mut ValidationContext) -> Result<StepResult> {
305 let trust_level = context
306 .trust_level
307 .ok_or_else(|| anyhow::anyhow!("Trust level not determined"))?;
308
309 match trust_level {
310 TrustLevel::Managed => {
311 if self.require_pqc {
312 let start_time = std::time::Instant::now();
314
315 std::thread::sleep(std::time::Duration::from_millis(2));
317
318 let duration = start_time.elapsed().as_nanos() as u64;
319 context.metadata.insert(
320 "pqc_verification_ns".to_string(),
321 duration.to_string(),
322 );
323
324 debug!(
325 "PqcVerificationStep: PQC verification completed in {} ns",
326 duration
327 );
328 Ok(StepResult::Success)
329 } else {
330 debug!("PqcVerificationStep: PQC verification skipped (not required)");
331 Ok(StepResult::Skipped)
332 }
333 }
334 TrustLevel::Community => {
335 debug!("PqcVerificationStep: PQC verification skipped (Community Space)");
336 Ok(StepResult::Skipped)
337 }
338 }
339 }
340
341 fn name(&self) -> &str {
342 "PQC Verification"
343 }
344
345 fn step_id(&self) -> &str {
346 &self.step_id
347 }
348}
349
350struct PolicyEnforcementStep {
352 step_id: String,
353 policy: ValidationPolicy,
354}
355
356impl ValidationStepTrait for PolicyEnforcementStep {
357 fn execute(&self, _atom: &Atom, context: &mut ValidationContext) -> Result<StepResult> {
358 let trust_level = context
359 .trust_level
360 .ok_or_else(|| anyhow::anyhow!("Trust level not determined"))?;
361
362 match trust_level {
364 TrustLevel::Managed => {
365 if self.policy.require_pqc_managed {
366 debug!("PolicyEnforcementStep: Managed atom accepted (PQC required)");
367 Ok(StepResult::Success)
368 } else {
369 debug!("PolicyEnforcementStep: Managed atom accepted (PQC not required)");
370 Ok(StepResult::Success)
371 }
372 }
373 TrustLevel::Community => {
374 if self.policy.allow_community {
375 debug!("PolicyEnforcementStep: Community atom accepted");
376 Ok(StepResult::Success)
377 } else {
378 warn!("PolicyEnforcementStep: Community atom rejected (policy forbids)");
379 Ok(StepResult::Failure)
380 }
381 }
382 }
383 }
384
385 fn name(&self) -> &str {
386 "Policy Enforcement"
387 }
388
389 fn step_id(&self) -> &str {
390 &self.step_id
391 }
392}
393
394impl LogicGateMetrics {
395 fn record_processing(
396 &mut self,
397 trust_level: TrustLevel,
398 latency_ns: u64,
399 hardware_accelerated: bool,
400 ) {
401 self.total_processed += 1;
402
403 match trust_level {
404 TrustLevel::Managed => self.managed_processed += 1,
405 TrustLevel::Community => self.community_processed += 1,
406 }
407
408 let total_latency =
410 self.avg_latency_ns * (self.total_processed - 1) as f64 + latency_ns as f64;
411 self.avg_latency_ns = total_latency / self.total_processed as f64;
412
413 if hardware_accelerated {
414 self.hardware_accelerated_ops += 1;
415 }
416
417 if latency_ns > 100_000 {
419 self.validation_failures += 1;
421 }
422 }
423
424 fn record_trust_determination(&mut self) {
425 self.trust_determinations += 1;
426 }
427
428 fn record_pqc_verification(&mut self) {
429 self.pqc_verifications += 1;
430 }
431}
432
433impl std::fmt::Debug for SamsLogicGate {
434 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
435 f.debug_struct("SamsLogicGate")
436 .field("gate_id", &self.gate_id)
437 .field("policy_name", &self.policy.policy_name)
438 .field("metrics", &self.metrics)
439 .field("hardware_accelerated", &self.hardware_status.hardware_acceleration_enabled)
440 .finish()
441 }
442}
443
444impl SamsLogicGate {
445 pub async fn new(policy: Option<ValidationPolicy>) -> Result<Self> {
464 let gate_id = Uuid::new_v4();
465
466 info!("SAMS Logic Gate: Initializing hardware validation engine");
467 info!("Gate ID: {}", gate_id);
468
469 let policy = policy.unwrap_or_else(|| ValidationPolicy {
470 policy_id: Uuid::new_v4(),
471 policy_name: "Default Policy".to_string(),
472 strict_mode: true,
473 allow_community: true,
474 require_pqc_managed: true,
475 max_processing_time_ns: 100_000,
476 hardware_acceleration: HardwareAcceleration::Preferred,
477 });
478
479 let pipeline = Self::create_pipeline(&policy).await?;
480 let hardware_status = Self::detect_hardware_capabilities().await?;
481
482 info!(
483 "Hardware acceleration: {:?}",
484 hardware_status.hardware_acceleration_enabled
485 );
486
487 Ok(Self {
488 gate_id,
489 policy,
490 metrics: LogicGateMetrics::default(),
491 pipeline,
492 hardware_status,
493 })
494 }
495
496 async fn create_pipeline(policy: &ValidationPolicy) -> Result<ValidationPipeline> {
498 let steps: Vec<Box<dyn ValidationStepTrait>> = vec![
499 Box::new(TrustDeterminationStep {
500 step_id: "trust_determination".to_string(),
501 hardware_accelerated: matches!(
502 policy.hardware_acceleration,
503 HardwareAcceleration::Preferred | HardwareAcceleration::Required
504 ),
505 }),
506 Box::new(PqcVerificationStep {
507 step_id: "pqc_verification".to_string(),
508 require_pqc: policy.require_pqc_managed,
509 }),
510 Box::new(PolicyEnforcementStep {
511 step_id: "policy_enforcement".to_string(),
512 policy: policy.clone(),
513 }),
514 ];
515
516 let config = PipelineConfig {
517 max_depth: 10,
518 parallel_processing: false, step_timeout_ns: policy.max_processing_time_ns,
520 };
521
522 info!("ValidationPipeline: Created with {} steps", steps.len());
523
524 Ok(ValidationPipeline { steps, config })
525 }
526
527 async fn detect_hardware_capabilities() -> Result<HardwareStatus> {
529 let silicon_catalyst_available = false; let hardware_acceleration_enabled = silicon_catalyst_available;
532 let cpu_features = vec!["sse2".to_string(), "avx2".to_string()]; let cache_line_size = 64; info!(
536 "HardwareStatus: Silicon Catalyst: {}, Acceleration: {}",
537 silicon_catalyst_available, hardware_acceleration_enabled
538 );
539
540 Ok(HardwareStatus {
541 silicon_catalyst_available,
542 hardware_acceleration_enabled,
543 cpu_features,
544 cache_line_size,
545 })
546 }
547
548 pub async fn validate_atom(&mut self, atom: Atom) -> Result<LogicGateResult> {
574 let start_time = std::time::Instant::now();
575
576 info!("LogicGate: Validating atom 0x{:08X}", atom.global_id);
577
578 let mut context = ValidationContext {
580 trust_level: None,
581 step_results: HashMap::new(),
582 metadata: HashMap::new(),
583 start_time: Utc::now(),
584 };
585
586 let mut validation_steps = Vec::new();
588 let mut is_valid = true;
589
590 for step in &self.pipeline.steps {
591 let step_start = std::time::Instant::now();
592
593 match step.execute(&atom, &mut context) {
594 Ok(result) => {
595 let duration = step_start.elapsed().as_nanos() as u64;
596
597 validation_steps.push(ValidationStep {
598 step_id: step.step_id().to_string(),
599 step_name: step.name().to_string(),
600 duration_ns: duration,
601 result: result.clone(),
602 metadata: Metadata::new(),
603 });
604
605 context
606 .step_results
607 .insert(step.step_id().to_string(), result.clone());
608
609 if matches!(result, StepResult::Failure) {
611 is_valid = false;
612 break;
613 }
614 }
615 Err(e) => {
616 error!("LogicGate: Step {} failed: {}", step.name(), e);
617 is_valid = false;
618 break;
619 }
620 }
621 }
622
623 let total_latency = start_time.elapsed().as_nanos() as u64;
625
626 let trust_level = context.trust_level.unwrap_or(TrustLevel::Community);
628
629 let details = ValidationDetails {
631 sincerity_bit: (atom.global_id & 0x80000000) != 0,
632 trust_determination_ns: context
633 .metadata
634 .get("trust_determination_ns")
635 .and_then(|v: &String| v.parse::<u64>().ok())
636 .unwrap_or(0),
637 pqc_verification_ns: context
638 .metadata
639 .get("pqc_verification_ns")
640 .and_then(|v: &String| v.parse::<u64>().ok()),
641 hardware_accelerated: self.hardware_status.hardware_acceleration_enabled,
642 validation_steps,
643 };
644
645 self.metrics
647 .record_processing(trust_level, total_latency, details.hardware_accelerated);
648 self.metrics.record_trust_determination();
649 if details.pqc_verification_ns.is_some() {
650 self.metrics.record_pqc_verification();
651 }
652
653 let mut metadata = Metadata::new();
654 metadata.insert("gate_id".to_string(), self.gate_id.to_string());
655 metadata.insert("atom_id".to_string(), atom.global_id.to_string());
656 metadata.insert("payload_size".to_string(), atom.payload.len().to_string());
657
658 let result = LogicGateResult {
659 is_valid,
660 trust_level,
661 timestamp: Utc::now(),
662 latency_ns: total_latency,
663 policy: self.policy.clone(),
664 details,
665 metadata,
666 };
667
668 info!(
669 "✅ LogicGate: Validation complete - valid: {}, trust: {:?}, latency: {} ns",
670 result.is_valid, result.trust_level, result.latency_ns
671 );
672
673 Ok(result)
674 }
675
676 pub fn get_metrics(&self) -> &LogicGateMetrics {
678 &self.metrics
679 }
680
681 pub fn get_hardware_status(&self) -> &HardwareStatus {
683 &self.hardware_status
684 }
685
686 pub async fn update_policy(&mut self, policy: ValidationPolicy) -> Result<()> {
688 info!("LogicGate: Updating validation policy");
689 self.policy = policy.clone();
690 self.pipeline = Self::create_pipeline(&policy).await?;
691 Ok(())
692 }
693
694 pub fn reset_metrics(&mut self) {
696 self.metrics = LogicGateMetrics::default();
697 info!("LogicGate: Metrics reset");
698 }
699}
700
701impl Default for ValidationPolicy {
703 fn default() -> Self {
704 Self {
705 policy_id: Uuid::new_v4(),
706 policy_name: "Default Policy".to_string(),
707 strict_mode: true,
708 allow_community: true,
709 require_pqc_managed: true,
710 max_processing_time_ns: 100_000,
711 hardware_acceleration: HardwareAcceleration::Preferred,
712 }
713 }
714}
715
716#[cfg(test)]
717mod tests {
718 use super::*;
719
720 #[tokio::test]
721 async fn test_logic_gate_creation() {
722 let gate = SamsLogicGate::new(None).await;
723 assert!(gate.is_ok());
724 }
725
726 #[tokio::test]
727 async fn test_managed_atom_validation() {
728 let mut gate = SamsLogicGate::new(None).await.unwrap();
729 let managed_atom = Atom::new(0x12345678, [0x42; 28]);
730 let community_atom = Atom::new(0x80000001, [0x24; 28]);
731
732 let managed_result = gate.validate_atom(managed_atom).await.unwrap();
734 assert_eq!(managed_result.trust_level, TrustLevel::Managed);
735 assert!(managed_result.is_valid);
736
737 let community_result = gate.validate_atom(community_atom).await.unwrap();
739 assert_eq!(community_result.trust_level, TrustLevel::Community);
740 assert!(community_result.is_valid);
741 }
742
743 #[tokio::test]
744 async fn test_trust_determination_performance() {
745 let mut gate = SamsLogicGate::new(None).await.unwrap();
746 let atom = Atom::new(0x12345678, [0x42; 28]);
747
748 for _ in 0..1000 {
750 let _ = gate.validate_atom(atom.clone()).await;
751 }
752
753 let metrics = gate.get_metrics();
754 assert_eq!(metrics.total_processed, 1000);
755 assert!(metrics.avg_latency_ns > 0.0);
756 assert_eq!(metrics.trust_determinations, 1000);
757 }
758
759 #[tokio::test]
760 async fn test_policy_enforcement() {
761 let policy = ValidationPolicy {
762 policy_id: Uuid::new_v4(),
763 policy_name: "Strict Policy".to_string(),
764 strict_mode: true,
765 allow_community: false, require_pqc_managed: true,
767 max_processing_time_ns: 100_000,
768 hardware_acceleration: HardwareAcceleration::None,
769 };
770
771 let mut gate = SamsLogicGate::new(Some(policy)).await.unwrap();
772 let managed_atom = Atom::new(0x12345678, [0x42; 28]);
773 let community_atom = Atom::new(0x80000001, [0x24; 28]);
774
775 let managed_result = gate.validate_atom(managed_atom).await.unwrap();
777 assert!(managed_result.is_valid);
778
779 let community_result = gate.validate_atom(community_atom).await.unwrap();
781 assert!(!community_result.is_valid);
782 }
783}