Skip to main content

omwei_atom/
trust_hierarchy.rs

1/*!
2# OMWEI 32BSA Trust Hierarchy Implementation
3
4This module implements the Trust Hierarchy system for the OMWEI 32-bit Semantic Atom (32BSA) protocol.
5The Trust Hierarchy is based on Bit 31 (MSB) of the GlobalID, providing zero-latency trust level determination.
6
7## Trust Levels:
8
9### Managed Space (Bit 31 = 0)
10- Range: 0x00000000 to 0x7FFFFFFF
11- IDs are "Sincere" and issued by OMWEI
12- MUST be verified via PQC signature
13- Global trust guarantee
14
15### Community Space (Bit 31 = 1)
16- Range: 0x80000000 to 0xFFFFFFFF
17- Unmanaged, sequential/arbitrary IDs for prototyping
18- NO global trust guarantee
19- Local/experimental use only
20
21## Hardware Efficiency:
22- Single bit-mask operation for trust level determination
23- Zero latency - suitable for real-time embedded systems
24- Optimized for 32-bit architectures
25
26## Security Considerations:
27- Managed IDs use sparse generation to prevent enumeration attacks
28- PQC signature verification required for Managed Space
29- Community Space explicitly marked as untrusted
30*/
31
32use core::fmt;
33
34/// Bit mask for the Sincerity Bit (MSB - Bit 31)
35pub const SINCERITY_BIT_MASK: u32 = 0x80000000;
36
37/// Maximum value for Managed Space (Bit 31 = 0)
38const MANAGED_SPACE_MAX: u32 = 0x7FFFFFFF;
39
40/// Maximum value for Community Space (Bit 31 = 1)
41#[allow(dead_code)]
42const COMMUNITY_SPACE_MAX: u32 = 0xFFFFFFFF;
43
44/// Trust Level enumeration for OMWEI 32BSA
45#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
46#[repr(u8)]
47pub enum TrustLevel {
48    /// Managed Space - Sincere IDs requiring PQC verification
49    Managed = 0,
50    /// Community Space - Unverified experimental IDs
51    Community = 1,
52}
53
54impl fmt::Display for TrustLevel {
55    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56        match self {
57            TrustLevel::Managed => write!(f, "Managed (Sincere)"),
58            TrustLevel::Community => write!(f, "Community (Unverified)"),
59        }
60    }
61}
62
63/// Validation result for atom processing
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum ValidationResult {
66    /// Atom is valid and trusted
67    Trusted,
68    /// Atom is from Community Space - use with caution
69    Unverified,
70    /// Atom failed PQC signature verification
71    InvalidSignature,
72    /// Atom ID is out of valid range
73    InvalidId,
74}
75
76impl fmt::Display for ValidationResult {
77    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
78        match self {
79            ValidationResult::Trusted => write!(f, "Trusted"),
80            ValidationResult::Unverified => write!(f, "Warning: Unverified"),
81            ValidationResult::InvalidSignature => write!(f, "Error: Invalid PQC Signature"),
82            ValidationResult::InvalidId => write!(f, "Error: Invalid ID Range"),
83        }
84    }
85}
86
87/// OMWEI 32BSA Atom structure
88#[derive(Debug, Clone, Copy)]
89#[repr(C)]
90pub struct Atom {
91    /// 32-bit Global ID with embedded trust level
92    pub global_id: u32,
93    /// Atom payload data
94    pub payload: [u8; 28], // 32 bytes total - 4 for ID, 28 for payload
95}
96
97impl Atom {
98    /// Create a new atom with the given ID and payload
99    #[inline]
100    pub fn new(global_id: u32, payload: [u8; 28]) -> Self {
101        Self { global_id, payload }
102    }
103
104    /// Create an atom with empty payload
105    #[inline]
106    pub fn with_id(global_id: u32) -> Self {
107        Self {
108            global_id,
109            payload: [0; 28],
110        }
111    }
112}
113
114/// Get trust level from a 32-bit Global ID
115///
116/// This is the core trust determination function using a single bit-mask operation.
117/// Zero latency - suitable for hardware-level execution.
118///
119/// # Arguments
120/// * `id` - 32-bit Global ID
121///
122/// # Returns
123/// * `TrustLevel::Managed` if Bit 31 = 0 (range 0x00000000 to 0x7FFFFFFF)
124/// * `TrustLevel::Community` if Bit 31 = 1 (range 0x80000000 to 0xFFFFFFFF)
125///
126/// # Examples
127/// ```
128/// use omwei_atom::trust_hierarchy::{get_trust_level, TrustLevel};
129///
130/// let managed_id = 0x12345678; // Bit 31 = 0
131/// let community_id = 0x80000001; // Bit 31 = 1
132///
133/// assert_eq!(get_trust_level(managed_id), TrustLevel::Managed);
134/// assert_eq!(get_trust_level(community_id), TrustLevel::Community);
135/// ```
136#[inline]
137pub fn get_trust_level(id: u32) -> TrustLevel {
138    // Single bit-mask operation - hardware efficient
139    if (id & SINCERITY_BIT_MASK) == 0 {
140        TrustLevel::Managed
141    } else {
142        TrustLevel::Community
143    }
144}
145
146/// Check if an ID is in the Managed Space range
147#[inline]
148pub fn is_managed_id(id: u32) -> bool {
149    id <= MANAGED_SPACE_MAX
150}
151
152/// Check if an ID is in the Community Space range
153#[inline]
154pub fn is_community_id(id: u32) -> bool {
155    id > MANAGED_SPACE_MAX
156}
157
158/// Placeholder for Post-Quantum Cryptography signature verification
159///
160/// In a production implementation, this would interface with a PQC library
161/// such as CRYSTALS-Kyber, CRYSTALS-Dilithium, or similar.
162///
163/// # Arguments
164/// * `atom` - The atom to verify
165///
166/// # Returns
167/// * `true` if signature is valid (placeholder - always returns false)
168/// * `false` if signature is invalid
169pub fn verify_pqc_signature(_atom: &Atom) -> bool {
170    // TODO: Implement actual PQC signature verification
171    // This should integrate with a PQC library like:
172    // - CRYSTALS-Dilithium for signatures
173    // - SPHINCS+ for stateless signatures
174    // - Falcon for lattice-based signatures
175
176    false // Placeholder - always return false for now
177}
178
179/// Validate an atom according to the Trust Hierarchy rules
180///
181/// This function simulates an AX (Accelerator eXchange) Buffer Filter that
182/// immediately checks the Sincerity Bit and routes the atom accordingly.
183///
184/// # Arguments
185/// * `atom` - The atom to validate
186///
187/// # Returns
188/// * `ValidationResult::Trusted` - Managed ID with valid PQC signature
189/// * `ValidationResult::Unverified` - Community ID (warning)
190/// * `ValidationResult::InvalidSignature` - Managed ID with invalid PQC signature
191/// * `ValidationResult::InvalidId` - ID out of valid range
192///
193/// # Examples
194/// ```
195/// use omwei_atom::trust_hierarchy::{validate_atom, Atom};
196///
197/// let managed_atom = Atom::with_id(0x12345678);
198/// let community_atom = Atom::with_id(0x80000001);
199///
200/// let result_managed = validate_atom(&managed_atom);
201/// let result_community = validate_atom(&community_atom);
202/// ```
203pub fn validate_atom(atom: &Atom) -> ValidationResult {
204    let trust_level = get_trust_level(atom.global_id);
205
206    match trust_level {
207        TrustLevel::Managed => {
208            // Managed Space - require PQC verification
209            if verify_pqc_signature(atom) {
210                ValidationResult::Trusted
211            } else {
212                ValidationResult::InvalidSignature
213            }
214        }
215        TrustLevel::Community => {
216            // Community Space - mark as unverified
217            ValidationResult::Unverified
218        }
219    }
220}
221
222/// Sparse ID Generator for Managed Space
223///
224/// Generates cryptographically sparse IDs to prevent enumeration attacks.
225/// Uses a cryptographically secure pseudo-random number generator with
226/// a sparse distribution algorithm.
227pub struct SparseIdGenerator {
228    /// Internal state for the CSPRNG
229    state: u64,
230    /// Counter to ensure uniqueness
231    counter: u64,
232}
233
234impl SparseIdGenerator {
235    /// Create a new sparse ID generator
236    ///
237    /// # Arguments
238    /// * `seed` - Optional seed for the CSPRNG (defaults to current time)
239    pub fn new(seed: Option<u64>) -> Self {
240        Self {
241            state: seed.unwrap_or({
242                // In a real implementation, use hardware RNG or secure source
243                0x123456789ABCDEF0 // Placeholder seed
244            }),
245            counter: 0,
246        }
247    }
248
249    /// Generate a sparse ID in Managed Space
250    ///
251    /// This function creates IDs that are:
252    /// 1. Within Managed Space range (0x00000000 to 0x7FFFFFFF)
253    /// 2. Cryptographically sparse to prevent enumeration
254    /// 3. Unique within the generator instance
255    ///
256    /// # Returns
257    /// A 32-bit ID suitable for Managed Space
258    pub fn generate_sparse_id(&mut self) -> u32 {
259        // Simple xorshift-based CSPRNG (replace with proper CSPRNG in production)
260        self.state ^= self.state << 13;
261        self.state ^= self.state >> 7;
262        self.state ^= self.state << 17;
263
264        // Incorporate counter to ensure uniqueness
265        self.counter += 1;
266        let combined = self.state.wrapping_add(self.counter);
267
268        // Map to Managed Space range using sparse distribution
269        // This creates gaps in the ID space to prevent enumeration
270        let sparse_value =
271            ((combined & 0x7FFFFFFF) | ((combined & 0x0000FFFF) << 16) & 0x7FFFFFFF) as u32;
272
273        // Ensure we're in Managed Space
274        sparse_value & MANAGED_SPACE_MAX
275    }
276
277    /// Generate a batch of sparse IDs
278    ///
279    /// # Arguments
280    /// * `count` - Number of IDs to generate
281    ///
282    /// # Returns
283    /// Vector of unique sparse IDs in Managed Space
284    pub fn generate_sparse_batch(&mut self, count: usize) -> Vec<u32> {
285        let mut ids = Vec::with_capacity(count);
286        for _ in 0..count {
287            ids.push(self.generate_sparse_id());
288        }
289        ids
290    }
291}
292
293impl Default for SparseIdGenerator {
294    fn default() -> Self {
295        Self::new(None)
296    }
297}
298
299#[cfg(test)]
300mod tests {
301    use super::*;
302
303    #[test]
304    fn test_trust_level_determination() {
305        // Test Managed Space (Bit 31 = 0)
306        assert_eq!(get_trust_level(0x00000000), TrustLevel::Managed);
307        assert_eq!(get_trust_level(0x12345678), TrustLevel::Managed);
308        assert_eq!(get_trust_level(0x7FFFFFFF), TrustLevel::Managed);
309
310        // Test Community Space (Bit 31 = 1)
311        assert_eq!(get_trust_level(0x80000000), TrustLevel::Community);
312        assert_eq!(get_trust_level(0x80000001), TrustLevel::Community);
313        assert_eq!(get_trust_level(0xFFFFFFFF), TrustLevel::Community);
314    }
315
316    #[test]
317    fn test_space_validation() {
318        // Managed Space
319        assert!(is_managed_id(0x00000000));
320        assert!(is_managed_id(0x12345678));
321        assert!(is_managed_id(0x7FFFFFFF));
322        assert!(!is_managed_id(0x80000000));
323
324        // Community Space
325        assert!(!is_community_id(0x7FFFFFFF));
326        assert!(is_community_id(0x80000000));
327        assert!(is_community_id(0xFFFFFFFF));
328    }
329
330    #[test]
331    fn test_atom_validation() {
332        let managed_atom = Atom::with_id(0x12345678);
333        let community_atom = Atom::with_id(0x80000001);
334
335        // Community atoms should return Unverified
336        assert_eq!(validate_atom(&community_atom), ValidationResult::Unverified);
337
338        // Managed atoms should return InvalidSignature (placeholder PQC verification)
339        assert_eq!(
340            validate_atom(&managed_atom),
341            ValidationResult::InvalidSignature
342        );
343    }
344
345    #[test]
346    fn test_sparse_id_generation() {
347        let mut generator = SparseIdGenerator::new(Some(12345));
348
349        // Generate multiple IDs
350        let id1 = generator.generate_sparse_id();
351        let id2 = generator.generate_sparse_id();
352        let id3 = generator.generate_sparse_id();
353
354        // All should be in Managed Space
355        assert!(is_managed_id(id1));
356        assert!(is_managed_id(id2));
357        assert!(is_managed_id(id3));
358
359        // All should be unique
360        assert_ne!(id1, id2);
361        assert_ne!(id2, id3);
362        assert_ne!(id1, id3);
363
364        // Should be sparse (not sequential)
365        assert!(id2.abs_diff(id1) > 1);
366        assert!(id3.abs_diff(id2) > 1);
367    }
368
369    #[test]
370    fn test_batch_generation() {
371        let mut generator = SparseIdGenerator::new(Some(54321));
372        let batch = generator.generate_sparse_batch(100);
373
374        assert_eq!(batch.len(), 100);
375
376        // All should be in Managed Space
377        for id in &batch {
378            assert!(is_managed_id(*id));
379        }
380
381        // All should be unique
382        let mut unique_ids = batch.clone();
383        unique_ids.sort();
384        unique_ids.dedup();
385        assert_eq!(unique_ids.len(), 100);
386    }
387}