1pub mod dna;
46pub mod tron;
47pub mod neural;
48pub mod evolution;
49pub mod collective;
50pub mod network;
51pub mod error;
52
53pub use dna::{DigitalDNA, DNAKeypair, Mutation, DNAError};
55pub use tron::{TRON, OrganismState, OrganismMemory, VitalSigns, TRONError};
56pub use neural::{
57 NeuralMessage, NeuralProtocol, Synapse, MessageType, NeurotransmitterType,
58 NeuralStatus, SynapseError
59};
60pub use evolution::{EvolutionEngine, MutationType, SelectionPressure, EvolutionError};
61pub use collective::{CollectiveIntelligence, SwarmBehavior, CollectiveMemory};
62pub use network::{NetworkDiscovery, NetworkTopology};
63pub use error::GenesisError;
64
65pub const VERSION: &str = env!("CARGO_PKG_VERSION");
67pub const PROTOCOL_VERSION: &str = "1.0.0";
68
69pub const MAX_ORGANISMS_PER_NETWORK: usize = 1_000_000;
71pub const MAX_SYNAPSES_PER_ORGANISM: usize = 100_000;
72pub const TARGET_NEURAL_LATENCY_NS: u64 = 10_000; pub const MAX_EVOLUTION_TIME_MS: u64 = 1000; const DEFAULT_ORGANISM_ENERGY: f64 = 1.0;
75const DEFAULT_ORGANISM_HEALTH: f64 = 1.0;
76
77pub struct GenesisProtocol {
79 pub organisms: std::collections::HashMap<String, TRON>,
80 pub network: NetworkDiscovery,
81 pub collective: CollectiveIntelligence,
82 pub evolution_engine: EvolutionEngine,
83}
84
85impl GenesisProtocol {
86 pub fn new() -> Result<Self, GenesisError> {
88 Ok(GenesisProtocol {
89 organisms: std::collections::HashMap::new(),
90 network: NetworkDiscovery::new()?,
91 collective: CollectiveIntelligence::new()?,
92 evolution_engine: EvolutionEngine::new()?,
93 })
94 }
95
96 pub fn create_organism(&mut self, dna: Option<DigitalDNA>) -> Result<String, GenesisError> {
98 let organism = match dna {
99 Some(dna) => TRON::create_with_dna(dna)?,
100 None => TRON::create_new()?,
101 };
102
103 let organism_id = organism.id.clone();
104 self.organisms.insert(organism_id.clone(), organism);
105
106 Ok(organism_id)
107 }
108
109 pub fn get_organism(&self, organism_id: &str) -> Option<&TRON> {
111 self.organisms.get(organism_id)
112 }
113
114 pub fn get_organism_mut(&mut self, organism_id: &str) -> Option<&mut TRON> {
116 self.organisms.get_mut(organism_id)
117 }
118
119 pub async fn establish_neural_connection(&mut self, from_id: &str, to_id: &str) -> Result<String, GenesisError> {
121 if let Some(organism) = self.organisms.get_mut(from_id) {
122 let synapse_id = organism.neural_connect(to_id).await?;
123 Ok(synapse_id)
124 } else {
125 Err(GenesisError::OrganismNotFound(from_id.to_string()))
126 }
127 }
128
129 pub async fn send_neural_message(&self, from_id: &str, to_id: &str, message_type: MessageType, payload: Vec<u8>) -> Result<(), GenesisError> {
131 if let Some(organism) = self.organisms.get(from_id) {
132 organism.send_neural_message(to_id, message_type, payload).await?;
133 Ok(())
134 } else {
135 Err(GenesisError::OrganismNotFound(from_id.to_string()))
136 }
137 }
138
139 pub fn evolve_organism(&mut self, organism_id: &str, selection_pressure: f64) -> Result<(), GenesisError> {
141 if let Some(organism) = self.organisms.get_mut(organism_id) {
142 organism.begin_evolution(selection_pressure)?;
143 Ok(())
144 } else {
145 Err(GenesisError::OrganismNotFound(organism_id.to_string()))
146 }
147 }
148
149 pub fn get_network_stats(&self) -> NetworkStats {
151 NetworkStats {
152 total_organisms: self.organisms.len(),
153 active_organisms: self.organisms.values().filter(|o| o.state != OrganismState::Dead).count(),
154 total_synapses: self.organisms.values().map(|o| o.synapses.len()).sum(),
155 average_fitness: self.organisms.values().map(|o| o.dna.fitness).sum::<f64>() / self.organisms.len() as f64,
156 network_health: self.calculate_network_health(),
157 }
158 }
159
160 fn calculate_network_health(&self) -> f64 {
162 if self.organisms.is_empty() {
163 return 0.0;
164 }
165
166 let total_health: f64 = self.organisms.values().map(|o| o.health).sum();
167 let total_energy: f64 = self.organisms.values().map(|o| o.energy).sum();
168 let total_fitness: f64 = self.organisms.values().map(|o| o.dna.fitness).sum();
169
170 let avg_health = total_health / self.organisms.len() as f64;
171 let avg_energy = total_energy / self.organisms.len() as f64;
172 let avg_fitness = total_fitness / self.organisms.len() as f64;
173
174 (avg_health + avg_energy + avg_fitness) / 3.0
175 }
176
177 pub fn get_all_vital_signs(&self) -> Vec<VitalSigns> {
179 self.organisms.values().map(|o| o.get_vital_signs()).collect()
180 }
181
182 pub fn cleanup_dead_organisms(&mut self) -> usize {
184 let initial_count = self.organisms.len();
185 self.organisms.retain(|_, organism| organism.state != OrganismState::Dead);
186 initial_count - self.organisms.len()
187 }
188}
189
190impl Default for GenesisProtocol {
191 fn default() -> Self {
192 Self::new().expect("Failed to create default Genesis Protocol")
193 }
194}
195
196#[derive(Debug, Clone)]
198pub struct NetworkStats {
199 pub total_organisms: usize,
200 pub active_organisms: usize,
201 pub total_synapses: usize,
202 pub average_fitness: f64,
203 pub network_health: f64,
204}
205
206#[derive(Debug, Clone)]
208pub struct ProtocolInfo {
209 pub version: String,
210 pub protocol_version: String,
211 pub max_organisms: usize,
212 pub max_synapses: usize,
213 pub target_latency_ns: u64,
214 pub max_evolution_time_ms: u64,
215}
216
217impl ProtocolInfo {
218 pub fn new() -> Self {
219 ProtocolInfo {
220 version: VERSION.to_string(),
221 protocol_version: PROTOCOL_VERSION.to_string(),
222 max_organisms: MAX_ORGANISMS_PER_NETWORK,
223 max_synapses: MAX_SYNAPSES_PER_ORGANISM,
224 target_latency_ns: TARGET_NEURAL_LATENCY_NS,
225 max_evolution_time_ms: MAX_EVOLUTION_TIME_MS,
226 }
227 }
228}
229
230pub fn get_protocol_info() -> ProtocolInfo {
232 ProtocolInfo::new()
233}
234
235pub fn init_genesis_protocol() -> Result<(), GenesisError> {
237 tracing_subscriber::fmt()
238 .with_env_filter("genesis_protocol=debug")
239 .with_target(false)
240 .with_thread_ids(true)
241 .with_file(true)
242 .with_line_number(true)
243 .init();
244
245 tracing::info!("🧬 Genesis Protocol v{} initialized", VERSION);
246 tracing::info!("🚀 Protocol version: {}", PROTOCOL_VERSION);
247 tracing::info!("🎯 Target neural latency: {}ns", TARGET_NEURAL_LATENCY_NS);
248 tracing::info!("âš¡ Max evolution time: {}ms", MAX_EVOLUTION_TIME_MS);
249
250 Ok(())
251}
252
253#[cfg(feature = "python-bindings")]
255use pyo3::prelude::*;
256
257#[cfg(feature = "python-bindings")]
258#[pymodule]
259fn genesis_protocol(_py: Python, m: &PyModule) -> PyResult<()> {
260 m.add_class::<PyGenesisProtocol>()?;
261 m.add_class::<PyTRON>()?;
262 m.add_class::<PyDigitalDNA>()?;
263 m.add_class::<PyNetworkStats>()?;
264 m.add_class::<PyProtocolInfo>()?;
265
266 m.add("VERSION", VERSION)?;
268 m.add("PROTOCOL_VERSION", PROTOCOL_VERSION)?;
269 m.add("MAX_ORGANISMS_PER_NETWORK", MAX_ORGANISMS_PER_NETWORK)?;
270 m.add("MAX_SYNAPSES_PER_ORGANISM", MAX_SYNAPSES_PER_ORGANISM)?;
271 m.add("TARGET_NEURAL_LATENCY_NS", TARGET_NEURAL_LATENCY_NS)?;
272 m.add("MAX_EVOLUTION_TIME_MS", MAX_EVOLUTION_TIME_MS)?;
273
274 m.add_function(wrap_pyfunction!(py_get_protocol_info, m)?)?;
276 m.add_function(wrap_pyfunction!(py_init_genesis_protocol, m)?)?;
277
278 Ok(())
279}
280
281#[cfg(feature = "python-bindings")]
282#[pyclass]
283#[derive(Clone)]
284pub struct PyGenesisProtocol {
285 inner: std::sync::Arc<std::sync::Mutex<GenesisProtocol>>,
286}
287
288#[cfg(feature = "python-bindings")]
289#[pymethods]
290impl PyGenesisProtocol {
291 #[new]
292 fn new() -> PyResult<Self> {
293 let protocol = GenesisProtocol::new()
294 .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to create Genesis Protocol: {}", e)))?;
295
296 Ok(PyGenesisProtocol {
297 inner: std::sync::Arc::new(std::sync::Mutex::new(protocol)),
298 })
299 }
300
301 fn create_organism(&self, dna: Option<PyDigitalDNA>) -> PyResult<String> {
302 let mut protocol = self.inner.lock().unwrap();
303 let rust_dna = dna.map(|d| d.inner.clone());
304
305 protocol.create_organism(rust_dna)
306 .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to create organism: {}", e)))
307 }
308
309 fn evolve_organism(&self, organism_id: &str, factor: f64) -> PyResult<()> {
310 let mut protocol = self.inner.lock().unwrap();
311 protocol.evolve_organism(organism_id, factor)
312 .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to evolve organism: {}", e)))?;
313 Ok(())
314 }
315
316 fn get_network_stats(&self) -> PyResult<PyNetworkStats> {
317 let protocol = self.inner.lock().unwrap();
318 let stats = protocol.get_network_stats();
319 Ok(PyNetworkStats { inner: stats })
320 }
321}
322
323#[cfg(feature = "python-bindings")]
324#[pyclass]
325#[derive(Clone)]
326pub struct PyTRON {
327 inner: TRON,
328}
329
330#[cfg(feature = "python-bindings")]
331#[pymethods]
332impl PyTRON {
333 #[new]
334 fn new() -> PyResult<Self> {
335 let tron = TRON::create_new()
336 .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to create TRON: {}", e)))?;
337
338 Ok(PyTRON { inner: tron })
339 }
340
341 #[getter]
342 fn id(&self) -> String {
343 self.inner.id.clone()
344 }
345
346 #[getter]
347 fn health(&self) -> f64 {
348 self.inner.health
349 }
350
351 #[getter]
352 fn energy(&self) -> f64 {
353 self.inner.energy
354 }
355}
356
357#[cfg(feature = "python-bindings")]
358#[pyclass]
359#[derive(Clone)]
360pub struct PyDigitalDNA {
361 inner: DigitalDNA,
362}
363
364#[cfg(feature = "python-bindings")]
365#[pymethods]
366impl PyDigitalDNA {
367 #[new]
368 fn new() -> PyResult<Self> {
369 let dna = DigitalDNA::generate_new()
370 .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to generate DNA: {}", e)))?;
371
372 Ok(PyDigitalDNA { inner: dna })
373 }
374
375 #[getter]
376 fn fitness(&self) -> f64 {
377 self.inner.fitness
378 }
379
380 #[getter]
381 fn generation(&self) -> u64 {
382 self.inner.generation
383 }
384}
385
386#[cfg(feature = "python-bindings")]
387#[pyclass]
388#[derive(Clone)]
389pub struct PyNetworkStats {
390 inner: NetworkStats,
391}
392
393#[cfg(feature = "python-bindings")]
394#[pymethods]
395impl PyNetworkStats {
396 #[getter]
397 fn total_organisms(&self) -> usize {
398 self.inner.total_organisms
399 }
400
401 #[getter]
402 fn active_organisms(&self) -> usize {
403 self.inner.active_organisms
404 }
405
406 #[getter]
407 fn total_synapses(&self) -> usize {
408 self.inner.total_synapses
409 }
410
411 #[getter]
412 fn average_fitness(&self) -> f64 {
413 self.inner.average_fitness
414 }
415
416 #[getter]
417 fn network_health(&self) -> f64 {
418 self.inner.network_health
419 }
420}
421
422#[cfg(feature = "python-bindings")]
423#[pyclass]
424#[derive(Clone)]
425pub struct PyProtocolInfo {
426 inner: ProtocolInfo,
427}
428
429#[cfg(feature = "python-bindings")]
430#[pymethods]
431impl PyProtocolInfo {
432 #[getter]
433 fn version(&self) -> String {
434 self.inner.version.clone()
435 }
436
437 #[getter]
438 fn protocol_version(&self) -> String {
439 self.inner.protocol_version.clone()
440 }
441
442 #[getter]
443 fn max_organisms(&self) -> usize {
444 self.inner.max_organisms
445 }
446
447 #[getter]
448 fn max_synapses(&self) -> usize {
449 self.inner.max_synapses
450 }
451
452 #[getter]
453 fn target_latency_ns(&self) -> u64 {
454 self.inner.target_latency_ns
455 }
456
457 #[getter]
458 fn max_evolution_time_ms(&self) -> u64 {
459 self.inner.max_evolution_time_ms
460 }
461}
462
463#[cfg(feature = "python-bindings")]
464#[pyfunction]
465fn py_get_protocol_info() -> PyResult<PyProtocolInfo> {
466 let info = get_protocol_info();
467 Ok(PyProtocolInfo { inner: info })
468}
469
470#[cfg(feature = "python-bindings")]
471#[pyfunction]
472fn py_init_genesis_protocol() -> PyResult<()> {
473 init_genesis_protocol()
474 .map_err(|e| pyo3::exceptions::PyRuntimeError::new_err(format!("Failed to init Genesis Protocol: {}", e)))
475}
476
477#[cfg(test)]
478mod tests {
479 use super::*;
480
481 #[test]
482 fn test_protocol_creation() {
483 let protocol = GenesisProtocol::new();
484 assert!(protocol.is_ok());
485 }
486
487 #[test]
488 fn test_protocol_info() {
489 let info = get_protocol_info();
490 assert_eq!(info.version, VERSION);
491 assert_eq!(info.protocol_version, PROTOCOL_VERSION);
492 assert_eq!(info.max_organisms, MAX_ORGANISMS_PER_NETWORK);
493 }
494
495 #[tokio::test]
496 async fn test_organism_creation() {
497 let mut protocol = GenesisProtocol::new().unwrap();
498 let organism_id = protocol.create_organism(None).unwrap();
499
500 assert!(!organism_id.is_empty());
501 assert!(protocol.get_organism(&organism_id).is_some());
502 }
503
504 #[tokio::test]
505 async fn test_neural_connection() {
506 let mut protocol = GenesisProtocol::new().unwrap();
507
508 let organism1_id = protocol.create_organism(None).unwrap();
509 let organism2_id = protocol.create_organism(None).unwrap();
510
511 let synapse_id = protocol.establish_neural_connection(&organism1_id, &organism2_id).await.unwrap();
512 assert!(!synapse_id.is_empty());
513 }
514
515 #[tokio::test]
516 async fn test_neural_message() {
517 let mut protocol = GenesisProtocol::new().unwrap();
518
519 let organism1_id = protocol.create_organism(None).unwrap();
520 let organism2_id = protocol.create_organism(None).unwrap();
521
522 protocol.establish_neural_connection(&organism1_id, &organism2_id).await.unwrap();
523
524 let result = protocol.send_neural_message(
525 &organism1_id,
526 &organism2_id,
527 MessageType::Consciousness,
528 b"Hello, digital mind!".to_vec()
529 ).await;
530
531 assert!(result.is_ok());
532 }
533
534 #[test]
535 fn test_evolution() {
536 let mut protocol = GenesisProtocol::new().unwrap();
537 let organism_id = protocol.create_organism(None).unwrap();
538
539 let result = protocol.evolve_organism(&organism_id, 0.5);
540 assert!(result.is_ok());
541 }
542
543 #[test]
544 fn test_network_stats() {
545 let mut protocol = GenesisProtocol::new().unwrap();
546
547 for _ in 0..5 {
549 protocol.create_organism(None).unwrap();
550 }
551
552 let stats = protocol.get_network_stats();
553 assert_eq!(stats.total_organisms, 5);
554 assert_eq!(stats.active_organisms, 5);
555 assert!(stats.average_fitness > 0.0);
556 assert!(stats.network_health > 0.0);
557 }
558
559 #[test]
560 fn test_cleanup_dead_organisms() {
561 let mut protocol = GenesisProtocol::new().unwrap();
562 let organism_id = protocol.create_organism(None).unwrap();
563
564 if let Some(organism) = protocol.get_organism_mut(&organism_id) {
566 organism.state = OrganismState::Dead;
567 }
568
569 let cleaned = protocol.cleanup_dead_organisms();
570 assert_eq!(cleaned, 1);
571 assert_eq!(protocol.organisms.len(), 0);
572 }
573}