Skip to main content

aethelgard_avl/
lib.rs

1// Copyright (c) 2026 Ferrolab
2// Licensed under the MIT License or the Apache License, Version 2.0.
3// See LICENSE-MIT or LICENSE-APACHE for details.
4
5//! # Sovereign-AVL
6//! 
7//! **Sovereign-AVL** is a NASA-grade, self-auditing data structure designed for environments where
8//! memory integrity and cryptographic certainty are non-negotiable.
9//! 
10//! It combines three fundamental architectural axioms to achieve "Sovereign" status:
11//! 1. **Generational Arena Storage**: Eliminates Use-After-Free (Zombie Index) vulnerabilities.
12//! 2. **Merkle-Style Integrity**: Every node is cryptographically tied to its children via BLAKE3 hashes.
13//! 3. **AVL Balancing**: Guaranteed $O(\log n)$ performance for all operations.
14//! 
15//! ## Quick Start
16//! 
17//! ```rust
18//! use aethelgard_avl::SovereignMap;
19//! 
20//! let map = SovereignMap::new();
21//! 
22//! // Secure insertion: Hashes are computed and propagated automatically.
23//! map.insert("Aethelgard".to_string(), "Sovereign".to_string()).unwrap();
24//! 
25//! // Integrity-checked retrieval:
26//! if let Ok(Some(val)) = map.get(&"Aethelgard".to_string()) {
27//!     println!("Retrieved: {}", val);
28//! }
29//! 
30//! // Full Recursive Audit:
31//! map.full_audit().expect("Integrity violation detected!");
32//! ```
33//! 
34//! ## Why Sovereign?
35//! 
36//! In mission-critical environments (Space, Medical, Financial), bit-flips and adversarial memory corruption 
37//! are real threats. **Sovereign-AVL** assumes the memory is *not* trusted and verifies every bit on every access.
38//! 
39//! ## ⚖️ Limitations & Trade-offs
40//! 
41//! - **CPU Cost**: BLAKE3 hashing on every update is expensive (~100x slower than `BTreeMap`).
42//! - **Memory Cost**: ~36-40 bytes of overhead per node (plus padding).
43//! - **Write Contention**: Uses a global `RwLock`, which might bottleneck high-frequency parallel writes.
44//! - **Audit Latency**: `full_audit` is $O(n)$ and can take several milliseconds for large trees.
45
46pub mod avl;
47pub mod error;
48pub mod storage;
49
50use avl::SovereignAVL;
51use error::Result;
52use parking_lot::RwLock;
53use std::sync::Arc;
54use std::fmt::Debug;
55
56/// A thread-safe, self-auditing AVL tree with sovereign integrity.
57pub struct SovereignMap<K, V> {
58    inner: Arc<RwLock<SovereignAVL<K, V>>>,
59}
60
61impl<K, V> SovereignMap<K, V>
62where
63    K: Clone + Debug + PartialOrd + AsRef<[u8]> + Send + Sync + 'static,
64    V: Clone + Debug + AsRef<[u8]> + Send + Sync + 'static,
65{
66    /// Creates a new, empty `SovereignMap`.
67    pub fn new() -> Self {
68        Self {
69            inner: Arc::new(RwLock::new(SovereignAVL::new())),
70        }
71    }
72
73    /// Inserts a key-value pair into the map. 
74    /// If the key exists, returns `SovereignError::DuplicateKey`.
75    pub fn insert(&self, key: K, value: V) -> Result<()> {
76        let mut tree = self.inner.write();
77        tree.insert(key, value)
78    }
79
80    /// Removes a key from the map and its associated value.
81    pub fn remove(&self, key: &K) -> Result<()> {
82        let mut tree = self.inner.write();
83        tree.delete(key)
84    }
85
86    /// Retrieves a copy of the value associated with the key.
87    /// Performs an integrity check on every node visited during the search.
88    pub fn get(&self, key: &K) -> Result<Option<V>> {
89        let tree = self.inner.read();
90        tree.get(key)
91    }
92
93    /// Returns an iterator over the map's key-value pairs, in-order.
94    /// This method holds a read lock on the tree for the duration of its existence.
95    pub fn iter(&self) -> SovereignIter<'_, K, V> {
96        let guard = self.inner.read();
97        // Safety: We extend the lifetime of the borrow because the guard is held by the iterator itself.
98        let inner_iter = unsafe {
99            std::mem::transmute::<avl::InOrderIter<'_, K, V>, avl::InOrderIter<'static, K, V>>(
100                guard.iter()
101            )
102        };
103        SovereignIter { _guard: guard, inner_iter }
104    }
105
106    /// Performs a full recursive audit of the entire tree's integrity.
107    /// Returns `Ok(())` if the tree is consistent, or an `IntegrityViolation` error.
108    pub fn full_audit(&self) -> Result<()> {
109        let tree = self.inner.read();
110        tree.full_audit()
111    }
112
113    /// Visualizes the internal tree structure and integrity hashes to stdout.
114    pub fn visualize(&self) -> Result<()> {
115        let tree = self.inner.read();
116        tree.dump_tree()
117    }
118
119    /// Simulates a bit-flip in the memory of a specific node's value.
120    /// **WARNING**: For validation and stress-testing ONLY.
121    pub fn simulate_bit_flip(&self, key: &K) -> Result<()> {
122        let mut tree = self.inner.write();
123        tree.internal_corrupt_node(key)
124    }
125
126    /// Performs a full recursive validation of all tree invariants (BST order, AVL balance, Merkle integrity).
127    /// Returns `Ok(())` if the tree is mathematically and physically certain.
128    pub fn validate_invariants(&self) -> Result<()> {
129        let tree = self.inner.read();
130        tree.validate_invariants().map(|_| ())
131    }
132}
133
134/// An iterator over the entries of a `SovereignMap`.
135pub struct SovereignIter<'a, K: 'static, V: 'static> {
136    _guard: parking_lot::RwLockReadGuard<'a, SovereignAVL<K, V>>,
137    inner_iter: avl::InOrderIter<'static, K, V>,
138}
139
140impl<'a, K, V> Iterator for SovereignIter<'a, K, V>
141where
142    K: Clone + Debug + Send + Sync + 'static,
143    V: Clone + Debug + Send + Sync + 'static,
144{
145    type Item = (K, V); // We return clones to avoid complex lifetime issues with the guard
146
147    fn next(&mut self) -> Option<Self::Item> {
148        self.inner_iter.next().map(|(k, v)| (k.clone(), v.clone()))
149    }
150}
151
152#[cfg(test)]
153mod tests {
154    use super::*;
155
156    #[test]
157    fn test_basic_sovereign_operations() {
158        let map = SovereignMap::new();
159        map.insert("key1".to_string(), "value1".to_string()).unwrap();
160        map.insert("key2".to_string(), "value2".to_string()).unwrap();
161        
162        assert_eq!(map.get(&"key1".to_string()).unwrap(), Some("value1".to_string()));
163        assert_eq!(map.get(&"key2".to_string()).unwrap(), Some("value2".to_string()));
164        assert_eq!(map.get(&"key3".to_string()).unwrap(), None);
165    }
166
167    #[test]
168    fn test_avl_balancing_simple() {
169        let map = SovereignMap::new();
170        // LL Case (Sequential insertion should trigger rotations)
171        map.insert("c".to_string(), "3".to_string()).unwrap();
172        map.insert("b".to_string(), "2".to_string()).unwrap();
173        map.insert("a".to_string(), "1".to_string()).unwrap();
174        
175        assert_eq!(map.get(&"a".to_string()).unwrap(), Some("1".to_string()));
176        assert_eq!(map.get(&"b".to_string()).unwrap(), Some("2".to_string()));
177        assert_eq!(map.get(&"c".to_string()).unwrap(), Some("3".to_string()));
178    }
179}