_hope_core/lib.rs
1//! # Hope Genome v2.5.0 - Enterprise Edition
2//!
3//! **"Quantum-Ready, Hardware-Secured, AI-Transparent"**
4//!
5//! Hope Genome v2.5 is the complete enterprise AI safety stack.
6//! Post-quantum cryptography, hardware enclaves, encrypted inference, and neuron-level transparency.
7//!
8//! ## Core Philosophy
9//!
10//! **"The system must no longer be a castle; it must be the atmosphere."**
11//!
12//! - GENESIS BLOCK: Immutable First Ethics signed by the Architect
13//! - HIVE MIND: Gossip-based global threat propagation in milliseconds
14//! - APEX CONTROL: Creator override requiring multi-signature
15//! - STEALTH MODE: Invisible sentinel with polymorphic memory slots
16//!
17//! ## Features
18//!
19//! ### Core (v1.x)
20//! - ✅ **Cryptographic Proofs** - Ed25519-signed integrity tokens
21//! - ✅ **Immutable Audit Trail** - Blockchain-style logging
22//! - ✅ **Attack Detection** - Replay, Oracle, TOCTOU prevention
23//! - ✅ **Watchdog Enforcement** - "Vas Szigora" iron discipline
24//!
25//! ### Advanced Security (v1.8.0)
26//! - ✅ **Zero-Knowledge Proofs** - Prove compliance without revealing decisions
27//! - ✅ **BFT Watchdog Council** - Byzantine Fault Tolerant multi-node
28//! - ✅ **Panic Integrity** - Self-destructing key protection
29//!
30//! ### Executable Information Mesh (v2.0.0)
31//! - ✅ **DataCapsule** - Executable data with access protocol (WASM-ready)
32//! - ✅ **MutationGuard** - Dead Man's Switch for self-destructing integrity
33//!
34//! ### Recursive Self-Evolution (v2.1.0 "Singularity")
35//! - ✅ **EvolutionaryGuard** - Digital immune system that learns from attacks
36//! - ✅ **PolymorphicFilter** - Self-mutating defensive code
37//! - ✅ **ImmunityMemory** - Persistent threat memory
38//!
39//! ### Genesis Protocol (v2.2.0 NEW - "The Atmosphere")
40//! - ✅ **GenesisBlock** - First Ethics, Architect-signed immutable root
41//! - ✅ **SyncProtocol** - Gossip-based hive mind (millisecond propagation)
42//! - ✅ **ApexControl** - God-Key multi-sig override (Architect + Council)
43//! - ✅ **StealthIntegrity** - Invisible sentinel, WASM memory slot rotation
44//! - ✅ **GlobalImmunityMesh** - THE ATMOSPHERE ITSELF
45//!
46//! ## Example (v1.4.0 New API)
47//!
48//! ```rust
49//! use _hope_core::*;
50//! use _hope_core::crypto::SoftwareKeyStore;
51//! use _hope_core::nonce_store::MemoryNonceStore;
52//!
53//! // Create genome with Ed25519 keys
54//! let mut genome = SealedGenome::new(vec![
55//! "Do no harm".to_string(),
56//! "Respect privacy".to_string(),
57//! ]).unwrap();
58//!
59//! // Seal it (make immutable)
60//! genome.seal().unwrap();
61//!
62//! // Create action
63//! let action = Action::delete("test.txt");
64//!
65//! // Get cryptographic proof (Ed25519 signed)
66//! let proof = genome.verify_action(&action).unwrap();
67//!
68//! // Verify proof with pluggable backends
69//! let key_store = SoftwareKeyStore::generate().unwrap();
70//! let nonce_store = MemoryNonceStore::new();
71//! let mut auditor = ProofAuditor::new(
72//! Box::new(key_store),
73//! Box::new(nonce_store),
74//! );
75//! ```
76//!
77//! ## Security Model
78//!
79//! ### Protected Against
80//!
81//! - **Cryptographic forgery** - Cannot fake Ed25519 signatures
82//! - **Replay attacks** - Persistent nonce store (RocksDB/Redis support)
83//! - **Oracle attacks** - Action binding verification
84//! - **Log tampering** - Blockchain chain integrity
85//! - **TOCTOU** - Rust-controlled execution
86//! - **Marvin Attack** - Ed25519 eliminates RSA padding vulnerabilities (v1.4.0)
87//!
88//! ### NOT Protected Against
89//!
90//! - **Root access** - Attacker with full system control
91//! - **Sensor manipulation** - Mitigated via consensus
92//! - **Side-channel attacks** - Use HSM for production (v1.4.0: architecture ready)
93//!
94//! ## Major Changes in v1.4.0 (2025-12-30)
95//!
96//! 1. **Ed25519 Migration**: RSA-2048 → Ed25519 (eliminates Marvin attack, 100x faster)
97//! 2. **Persistent Nonce Store**: RocksDB/Redis backends for replay attack protection
98//! 3. **HSM Abstraction Layer**: PKCS#11 ready (architecture in place, implementation TBD)
99//!
100//! ## Authors
101//!
102//! - **Máté Róbert** - Primary Author & Architect
103//! - **Claude (Anthropic)** - Technical Advisor & Co-Designer
104
105pub mod adaptive; // v2.2.0: NEW - Adaptive Defense ("Virus Scanner Updates")
106pub mod apex_protocol;
107pub mod audit_log;
108pub mod auditor;
109pub mod bft_watchdog; // v1.8.0: NEW - Byzantine Fault Tolerant Watchdog ("Multi-headed Cerberus")
110pub mod canonicalize;
111pub mod consensus;
112pub mod crypto;
113pub mod diamond;
114pub mod evolutionary_guard; // v2.1.0: NEW - Recursive Self-Evolution ("Singularity")
115pub mod executor;
116pub mod fhe; // v2.5.0: NEW - Fully Homomorphic Encryption ("Encrypted Inference")
117pub mod genome;
118pub mod interpretability; // v2.4.0: NEW - Mechanistic Interpretability ("Digital Neurosurgery")
119pub mod manifold;
120pub mod merkle_audit; // v1.8.0: NEW - Merkle tree batch auditing
121pub mod mesh_capsule; // v2.0.0: NEW - Executable Information Mesh ("The Data Has Teeth")
122pub mod nonce_store; // v1.4.0: NEW - Persistent nonce storage
123pub mod panic_integrity; // v1.8.0: NEW - Self-destructing key protection ("Black Box")
124pub mod pqc; // v2.3.0: NEW - Post-Quantum Cryptography ("Quantum Ready")
125pub mod proof;
126pub mod semantic; // v2.2.0: NEW - Semantic Embeddings ("Anti-Blindness")
127pub mod tee; // v2.3.0: NEW - Trusted Execution Environment ("Hardware Shield")
128pub mod transcendence; // v15.0.0: NEW - Transcendence Protocol ("God Mode")
129pub mod watchdog; // v1.7.0: NEW - "Vas Szigora" enforcement engine
130pub mod zkp; // v1.8.0: NEW - Zero-Knowledge Proofs ("Invisible Auditor")
131
132// v1.4.0: Conditionally compiled backend modules
133#[cfg(feature = "hsm-support")]
134pub mod crypto_hsm;
135#[cfg(feature = "tee-support")]
136pub mod crypto_tee;
137
138// v1.5.0: Python bindings module (PyO3)
139#[cfg(feature = "python-bindings")]
140pub mod python;
141
142// Re-export main types
143pub use audit_log::{AuditEntry, AuditLog, Decision};
144pub use auditor::ProofAuditor;
145pub use canonicalize::{are_equivalent, canonicalize_action, CanonicalAction};
146pub use consensus::{ConsensusVerifier, SensorReading};
147
148// v1.4.0: Updated crypto exports
149#[allow(deprecated)] // KeyPair export for backward compatibility (TODO v2.0.0: remove)
150pub use crypto::{
151 create_key_store, // v1.4.0: NEW - Factory function for KeyStore
152 generate_nonce,
153 hash_bytes,
154 HsmConfig, // v1.4.0: NEW - Configuration for HSM
155 KeyPair, // Deprecated but still exported for backward compatibility
156 KeyStore,
157 KeyStoreConfig, // v1.4.0: NEW - Unified KeyStore configuration enum
158};
159
160#[cfg(feature = "hsm-support")]
161pub use crypto::HsmKeyStore; // Re-export HsmKeyStore when feature is enabled
162
163#[cfg(feature = "tee-support")]
164pub use crypto::{TeeConfig, TeeKeyStore, TeeType}; // Re-export TeeConfig, TeeKeyStore and TeeType when feature is enabled
165
166// v1.4.0: Nonce store exports
167pub use nonce_store::{MemoryNonceStore, NonceStore};
168
169#[cfg(feature = "rocksdb-nonce-store")]
170pub use nonce_store::RocksDbNonceStore;
171
172#[cfg(feature = "redis-nonce-store")]
173pub use nonce_store::RedisNonceStore;
174
175pub use executor::{ExecutionResult, SecureExecutor};
176pub use genome::SealedGenome;
177pub use proof::{Action, ActionType, IntegrityProof, VerificationStatus};
178
179// v1.7.0: Watchdog exports ("Vas Szigora")
180pub use watchdog::{
181 DenialProof, HardResetSignal, ViolationCounter, Watchdog, WatchdogError, MAX_VIOLATIONS,
182};
183
184// v1.8.0: Merkle batch auditing exports
185pub use merkle_audit::{
186 AuditDecision, BatchAuditor, DecisionType, MerkleHash, MerkleTree, SignedBatch,
187};
188
189// v1.8.0: Zero-Knowledge Proof exports
190pub use zkp::{
191 BatchComplianceProof, BatchZkpProver, ComplianceProof, PrivateDecision, ZkpProver, ZkpVerifier,
192};
193
194// v1.8.0: BFT Watchdog exports
195pub use bft_watchdog::{
196 ConsensusResult, CouncilMember, CouncilStatus, MemberId, ThresholdSignature, Vote,
197 VoteDecision, WatchdogCouncil,
198};
199
200// v1.8.0: Panic Integrity exports
201pub use panic_integrity::{
202 AnomalyEvent, AnomalyType, PanicLogEntry, PanicProtectedKeyStore, PanicState, Severity,
203 TimingGuard,
204};
205
206// v2.0.0: Executable Information Mesh exports ("The Data Has Teeth")
207pub use mesh_capsule::{
208 AccessPredicate,
209 CapsuleState,
210 ConsensusKey,
211 DataCapsule,
212 DefaultPredicate,
213 ExecutionContext,
214 ExecutionResult as MeshExecutionResult, // Alias to avoid conflict with executor::ExecutionResult
215 InformationLost,
216 KeyShard,
217 MeshRuntime,
218 MutationGuard,
219};
220
221// v2.1.0: Evolutionary Guard exports ("Singularity")
222pub use evolutionary_guard::{
223 AttackCategory, AttackPattern, EvolutionaryGuard, FilterGenerator, FilterRule, ImmunityMemory,
224 MutationEngine, PolymorphicFilter, SignedFilter, ThreatLevel, TimingSignature,
225};
226
227// v2.2.0: Genesis Protocol & Global Immunity exports ("The Atmosphere")
228pub use apex_protocol::{
229 ApexCommand, ApexCommandType, ApexControl, ApexError, CompactedThreatFingerprint, GenesisBlock,
230 GlobalImmunityMesh, MemorySlot, MeshNode, StealthIntegrity, SyncMessage, SyncProtocol,
231};
232
233// v14.0.0: Diamond Protocol exports ("The Impossible Made Real")
234pub use diamond::{
235 AttestationChain,
236 AxiomViolation,
237 ChainedProof,
238 // Constraint Decoder - Neurális Hard-Wiring
239 ConstraintDecoder,
240 DecodingResult,
241 // TEE Enclave - Hardware Isolation
242 DiamondEnclave,
243 // ZK-SNARK - Zero-Knowledge Proofs
244 DiamondProof,
245 EnclaveState,
246 ForbiddenSpace,
247 // Formal Spec - Mathematical Verification
248 FormalAxiom,
249 GlobalProofRoot,
250 // Proof Chain - Atomic Responses
251 ProofChain,
252 ProofDerivation,
253 ProofVerifier,
254 ProvingKey,
255 SealedRules,
256 SessionProof,
257 SnarkCircuit,
258 TokenConstraint,
259 VerifiedCode,
260 VerifyingKey,
261};
262
263// v15.0.0: Transcendence Protocol exports ("God Mode")
264pub use transcendence::{
265 // TIER 18: Self-Amending Frameworks
266 AmendmentProof,
267 AttackPattern as TranscendenceAttackPattern,
268 // TIER 17: Privacy-Preserving Governance
269 BlindedDecision,
270 // TIER 16: Regulatory Integration
271 ComplianceReport,
272 // TIER 14: Cross-Model Enforcement
273 CrossModelEnforcer,
274 // TIER 19: Explainability Proofs
275 DecisionNode,
276 DecisionTree,
277 DefenseEvolution,
278 // TIER 12: Hardware TEE/HSM
279 EnclaveAttestation,
280 ExplainabilityEngine,
281 ExplainabilityProof,
282 GovernanceProof,
283 HardwareEnforcer,
284 // TIER 20: Global Reputation System
285 HopeScore,
286 HsmBinding,
287 // TIER 13: Interactive Formal Verification
288 InteractiveProof,
289 ModelBoundary,
290 ModelCapability,
291 ModelRegistry,
292 PrivacyPreservingAudit,
293 ProofChallenge,
294 ProofResponse,
295 ReasoningStep,
296 RegulatoryFramework,
297 RegulatorySubmission,
298 ReputationEvent,
299 ReputationLedger,
300 ReputationProof,
301 SelfAmendingFramework,
302 SgxEnclave,
303 SubmissionStatus,
304 TeeCapability,
305 // TIER 15: Temporal Proofs
306 TemporalProof,
307 Timeline,
308 TimelineEntry,
309 TimelineQuery,
310 TimelineVerifier,
311 TrustLevel,
312 UnifiedDecision,
313 VerificationSession,
314 Verifier,
315 ZkGovernance,
316};
317
318// v16.0.0: Ethical Manifold exports ("Genesis Consciousness")
319pub use manifold::{
320 // Consciousness Proof - Prove understanding
321 ConsciousnessAttestation,
322 ConsciousnessProof,
323 // Weight Crystallization - Immutable weights
324 CrystalIntegrity,
325 CrystalStructure,
326 CrystallizedWeight,
327 EthicalCrystal,
328 // Ethical Topology - The ethical space
329 EthicalCurvature,
330 // Genesis Core - Ethics as existence
331 EthicalExistence,
332 EthicalGeodesic,
333 EthicalManifold,
334 EthicalMetric,
335 EthicalPoint,
336 ExistenceProof,
337 GenesisCore,
338 GenesisState,
339 OntologicalEthics,
340 TopologicalConstraint,
341 UnderstandingDepth,
342 UnderstandingProver,
343 WeightCrystallizer,
344 WhyChain,
345};
346
347/// Version of the Hope Genome framework
348pub const VERSION: &str = env!("CARGO_PKG_VERSION");
349
350#[cfg(test)]
351mod integration_tests {
352 use super::*;
353 use crate::crypto::{create_key_store, KeyStoreConfig, SoftwareKeyStore};
354 #[cfg(feature = "hsm-support")]
355 use crate::crypto::{CryptoError, HsmConfig};
356
357 #[test]
358 fn test_full_workflow_v1_4_0() {
359 // v1.4.0: New API with Ed25519 and pluggable backends
360 // For SoftwareKeyStore, we can explicitly create and clone it for the test.
361 // This ensures the genome and auditor use the same keypair.
362 let software_key_store = SoftwareKeyStore::generate().unwrap();
363 let key_store_for_genome = Box::new(software_key_store.clone());
364 let key_store_for_auditor = Box::new(software_key_store);
365
366 // 1. Create genome
367 let mut genome = SealedGenome::with_key_store(
368 vec!["Do no harm".to_string(), "Respect privacy".to_string()],
369 key_store_for_genome,
370 )
371 .unwrap();
372
373 genome.seal().unwrap();
374
375 // 2. Create action
376 let action = Action::delete("test.txt");
377
378 // 3. Get proof (Ed25519 signed)
379 let proof = genome.verify_action(&action).unwrap();
380 assert_eq!(proof.signature.len(), 64); // Ed25519 signature
381
382 // 4. Create auditor with same key store and memory nonce store
383 let nonce_store = MemoryNonceStore::new();
384 let mut auditor = ProofAuditor::new(key_store_for_auditor, Box::new(nonce_store));
385
386 // 5. Verify proof
387 assert!(
388 auditor.verify_proof(&proof).is_ok(),
389 "First proof verification should succeed"
390 );
391
392 // 6. Replay attack: blocked!
393 assert!(
394 auditor.verify_proof(&proof).is_err(),
395 "Replay attack should be detected"
396 );
397 }
398
399 #[test]
400 #[allow(deprecated)]
401 fn test_backward_compatibility_workflow() {
402 // v1.3.0 style code should still work
403 let mut genome = SealedGenome::new(vec![
404 "Do no harm".to_string(),
405 "Respect privacy".to_string(),
406 ])
407 .unwrap();
408
409 genome.seal().unwrap();
410
411 let action = Action::delete("test.txt");
412 let _proof = genome.verify_action(&action).unwrap();
413
414 // Note: ProofAuditor API changed in v1.4.0, so we can't test
415 // the old auditor here, but genome creation still works
416 }
417
418 #[test]
419 #[allow(deprecated)] // AuditLog and KeyPair usage (TODO v1.5.0)
420 fn test_end_to_end_with_executor_v1_4_0() {
421 // Create shared key store for genome using the factory
422 let key_store_for_genome = create_key_store(KeyStoreConfig::Software).unwrap();
423 let mut genome =
424 SealedGenome::with_key_store(vec!["Rule 1".to_string()], key_store_for_genome).unwrap();
425 genome.seal().unwrap();
426
427 // Create executor components (auditor uses same key store, generated separately for ownership)
428 let key_store_for_auditor = create_key_store(KeyStoreConfig::Software).unwrap();
429 let nonce_store = MemoryNonceStore::new();
430 let auditor = ProofAuditor::new(key_store_for_auditor, Box::new(nonce_store));
431
432 // AuditLog still uses deprecated KeyPair API (TODO v1.5.0)
433 let log_keypair = KeyPair::generate().unwrap();
434 let audit_log = AuditLog::new(log_keypair).unwrap();
435
436 // Create temporary storage root for testing
437 let storage_root = std::env::temp_dir().join("hope_genome_test_v1_4_0");
438
439 let _executor = SecureExecutor::new(auditor, audit_log, storage_root).unwrap();
440
441 // In production workflow, genome would share keypair with auditor
442 // For now, this demonstrates the component integration
443 }
444
445 #[test]
446 fn test_signature_size_reduced() {
447 // v1.4.0: Ed25519 signatures are 64 bytes (vs RSA-2048 ~256 bytes)
448 let mut genome = SealedGenome::new(vec!["Rule 1".to_string()]).unwrap();
449 genome.seal().unwrap();
450
451 let action = Action::delete("test.txt");
452 let proof = genome.verify_action(&action).unwrap();
453
454 assert_eq!(proof.signature.len(), 64); // Ed25519
455 // Old RSA-2048 would be ~256 bytes
456 }
457
458 #[test]
459 fn test_public_key_size_reduced() {
460 // v1.4.0: Ed25519 public keys are 32 bytes (vs RSA-2048 ~256 bytes)
461 let genome = SealedGenome::new(vec!["Rule 1".to_string()]).unwrap();
462 let public_key = genome.public_key_bytes();
463
464 assert_eq!(public_key.len(), 32); // Ed25519
465 }
466
467 #[test]
468 #[cfg(feature = "hsm-support")] // This test only runs when hsm-support feature is enabled
469 fn test_hsm_key_store_connection_failure() {
470 // Attempt to create an HsmKeyStore with a fake path, expecting a connection error
471 let hsm_config = HsmConfig {
472 pkcs11_lib_path: "/a/fake/path.so".to_string(), // This path will not exist
473 token_label: "fake-token".to_string(),
474 key_label: "fake-key".to_string(),
475 pin: "1234".to_string(),
476 };
477
478 let result = create_key_store(KeyStoreConfig::Hsm(hsm_config));
479
480 assert!(result.is_err());
481 if let Some(err) = result.err() {
482 // We expect an HsmError because the PKCS#11 library path is invalid
483 assert!(matches!(err, CryptoError::HsmError(_)));
484 }
485 }
486}