1use serde::{Deserialize, Serialize};
16use ed25519_dalek::{SigningKey, VerifyingKey, Signature, Signer, Verifier};
17use rand::{SeedableRng, RngCore};
18use sha2::{Sha256, Digest};
19use rand::rngs::OsRng;
20use std::time::{SystemTime, UNIX_EPOCH};
21
22#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct DigitalDNA {
25 pub sequence: Vec<u8>,
27 pub generation: u64,
29 pub mutations: Vec<Mutation>,
31 pub fitness: f64,
33 pub parent_hash: Option<String>,
35 pub created_at: u64,
37 pub keypair: DNAKeypair,
39 pub metadata: DNAMetadata,
41}
42
43#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct DNAKeypair {
46 pub public_key: [u8; 32],
48 #[serde(skip_serializing)]
50 pub secret_key: [u8; 32],
51 pub key_generation: u64,
53 pub derivation_path: Vec<u32>,
55}
56
57#[derive(Debug, Clone, Serialize, Deserialize)]
59pub struct DNAMetadata {
60 pub species: String,
62 pub biological_age: u64,
64 pub mutation_rate: f64,
66 pub crossover_compatibility: f64,
68 pub adaptation_score: f64,
70 pub reproductive_success: f64,
72 pub neural_complexity: f64,
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize)]
78pub enum Mutation {
79 PointMutation {
81 position: usize,
82 old_value: u8,
83 new_value: u8,
84 timestamp: u64,
85 },
86 Insertion {
88 position: usize,
89 sequence: Vec<u8>,
90 timestamp: u64,
91 },
92 Deletion {
94 position: usize,
95 length: usize,
96 timestamp: u64,
97 },
98 Duplication {
100 start: usize,
101 end: usize,
102 insert_at: usize,
103 timestamp: u64,
104 },
105 Inversion {
107 start: usize,
108 end: usize,
109 timestamp: u64,
110 },
111 Translocation {
113 from_start: usize,
114 from_end: usize,
115 to_position: usize,
116 timestamp: u64,
117 },
118 KeyEvolution {
120 old_generation: u64,
121 new_generation: u64,
122 timestamp: u64,
123 },
124}
125
126impl DigitalDNA {
127 pub fn generate_new() -> Result<Self, DNAError> {
129 let mut csprng = OsRng{};
130 let mut secret_bytes = [0u8; 32];
131 csprng.fill_bytes(&mut secret_bytes);
132 let signing_key = SigningKey::from_bytes(&secret_bytes);
133 let verifying_key = signing_key.verifying_key();
134
135 let mut hasher = Sha256::new();
137 hasher.update(verifying_key.to_bytes());
138 hasher.update(&SystemTime::now()
139 .duration_since(UNIX_EPOCH)
140 .unwrap()
141 .as_nanos()
142 .to_le_bytes());
143 hasher.update(&rand::random::<u64>().to_le_bytes());
144
145 let sequence = hasher.finalize().to_vec();
146
147 let mut extended_sequence = sequence.clone();
149 for _ in 0..8 {
150 let mut hasher = Sha256::new();
151 hasher.update(&extended_sequence);
152 hasher.update(&rand::random::<u64>().to_le_bytes());
153 extended_sequence.extend_from_slice(&hasher.finalize()[..4]);
154 }
155
156 Ok(DigitalDNA {
157 sequence: extended_sequence,
158 generation: 0,
159 mutations: Vec::new(),
160 fitness: 1.0,
161 parent_hash: None,
162 created_at: SystemTime::now()
163 .duration_since(UNIX_EPOCH)
164 .unwrap()
165 .as_secs(),
166 keypair: DNAKeypair {
167 public_key: verifying_key.to_bytes(),
168 secret_key: signing_key.to_bytes(),
169 key_generation: 0,
170 derivation_path: vec![0],
171 },
172 metadata: DNAMetadata {
173 species: "TRON".to_string(),
174 biological_age: 0,
175 mutation_rate: 0.01, crossover_compatibility: 0.8,
177 adaptation_score: 0.5,
178 reproductive_success: 0.0,
179 neural_complexity: 0.1,
180 },
181 })
182 }
183
184 pub fn from_signing_key(signing_key: SigningKey) -> Result<Self, DNAError> {
186 let verifying_key = signing_key.verifying_key();
187 let mut dna = Self::generate_new()?;
188 dna.keypair = DNAKeypair {
189 public_key: verifying_key.to_bytes(),
190 secret_key: signing_key.to_bytes(),
191 key_generation: 0,
192 derivation_path: vec![0],
193 };
194 Ok(dna)
195 }
196
197 pub fn mutate(&mut self, mutation: Mutation) -> Result<(), DNAError> {
199 match &mutation {
200 Mutation::PointMutation { position, new_value, .. } => {
201 if *position < self.sequence.len() {
202 self.sequence[*position] = *new_value;
203 } else {
204 return Err(DNAError::InvalidMutationPosition(*position));
205 }
206 },
207 Mutation::Insertion { position, sequence, .. } => {
208 if *position <= self.sequence.len() {
209 self.sequence.splice(*position..*position, sequence.iter().cloned());
210 } else {
211 return Err(DNAError::InvalidMutationPosition(*position));
212 }
213 },
214 Mutation::Deletion { position, length, .. } => {
215 if *position < self.sequence.len() && *position + *length <= self.sequence.len() {
216 self.sequence.drain(*position..*position + *length);
217 } else {
218 return Err(DNAError::InvalidMutationPosition(*position));
219 }
220 },
221 Mutation::Duplication { start, end, insert_at, .. } => {
222 if *start < self.sequence.len() && *end <= self.sequence.len() && *start < *end {
223 let duplicated = self.sequence[*start..*end].to_vec();
224 let insert_pos = (*insert_at).min(self.sequence.len());
225 self.sequence.splice(insert_pos..insert_pos, duplicated);
226 } else {
227 return Err(DNAError::InvalidMutationRange(*start, *end));
228 }
229 },
230 Mutation::Inversion { start, end, .. } => {
231 if *start < self.sequence.len() && *end <= self.sequence.len() && *start < *end {
232 self.sequence[*start..*end].reverse();
233 } else {
234 return Err(DNAError::InvalidMutationRange(*start, *end));
235 }
236 },
237 Mutation::Translocation { from_start, from_end, to_position, .. } => {
238 if *from_start < self.sequence.len() && *from_end <= self.sequence.len() && *from_start < *from_end {
239 let translocated = self.sequence.drain(*from_start..*from_end).collect::<Vec<_>>();
240 let insert_pos = (*to_position).min(self.sequence.len());
241 self.sequence.splice(insert_pos..insert_pos, translocated);
242 } else {
243 return Err(DNAError::InvalidMutationRange(*from_start, *from_end));
244 }
245 },
246 Mutation::KeyEvolution { new_generation, .. } => {
247 self.evolve_keys(*new_generation)?;
248 }
249 }
250
251 self.mutations.push(mutation);
252 self.generation += 1;
253 self.metadata.biological_age += 1;
254
255 self.fitness *= 0.98;
257
258 self.metadata.mutation_rate = (self.metadata.mutation_rate * 0.9) + (0.1 * 0.01);
260 self.metadata.adaptation_score *= 0.95;
261
262 Ok(())
263 }
264
265 pub fn generate_random_mutation(&self) -> Mutation {
267 let mutation_type = rand::random::<u8>() % 7;
268 let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
269
270 match mutation_type {
271 0 => Mutation::PointMutation {
272 position: rand::random::<usize>() % self.sequence.len(),
273 old_value: 0, new_value: rand::random::<u8>(),
275 timestamp,
276 },
277 1 => Mutation::Insertion {
278 position: rand::random::<usize>() % (self.sequence.len() + 1),
279 sequence: (0..rand::random::<usize>() % 8 + 1)
280 .map(|_| rand::random::<u8>())
281 .collect(),
282 timestamp,
283 },
284 2 => Mutation::Deletion {
285 position: rand::random::<usize>() % self.sequence.len(),
286 length: rand::random::<usize>() % 4 + 1,
287 timestamp,
288 },
289 3 => {
290 let start = rand::random::<usize>() % self.sequence.len();
291 let end = start + rand::random::<usize>() % 8 + 1;
292 Mutation::Duplication {
293 start,
294 end: end.min(self.sequence.len()),
295 insert_at: rand::random::<usize>() % (self.sequence.len() + 1),
296 timestamp,
297 }
298 },
299 4 => {
300 let start = rand::random::<usize>() % self.sequence.len();
301 let end = start + rand::random::<usize>() % 8 + 1;
302 Mutation::Inversion {
303 start,
304 end: end.min(self.sequence.len()),
305 timestamp,
306 }
307 },
308 5 => {
309 let from_start = rand::random::<usize>() % self.sequence.len();
310 let from_end = from_start + rand::random::<usize>() % 4 + 1;
311 Mutation::Translocation {
312 from_start,
313 from_end: from_end.min(self.sequence.len()),
314 to_position: rand::random::<usize>() % (self.sequence.len() + 1),
315 timestamp,
316 }
317 },
318 _ => Mutation::KeyEvolution {
319 old_generation: self.keypair.key_generation,
320 new_generation: self.keypair.key_generation + 1,
321 timestamp,
322 },
323 }
324 }
325
326 pub fn crossover(&self, other: &DigitalDNA) -> Result<DigitalDNA, DNAError> {
328 if self.metadata.crossover_compatibility < 0.5 || other.metadata.crossover_compatibility < 0.5 {
330 return Err(DNAError::CrossoverIncompatible);
331 }
332
333 let min_len = self.sequence.len().min(other.sequence.len());
335 if min_len < 4 {
336 return Err(DNAError::SequenceTooShort);
337 }
338
339 let crossover_point1 = rand::random::<usize>() % (min_len / 2);
340 let crossover_point2 = (min_len / 2) + rand::random::<usize>() % (min_len / 2);
341
342 let mut new_sequence = Vec::new();
344 new_sequence.extend_from_slice(&self.sequence[..crossover_point1]);
345 new_sequence.extend_from_slice(&other.sequence[crossover_point1..crossover_point2]);
346 new_sequence.extend_from_slice(&self.sequence[crossover_point2..]);
347
348 let mut child = DigitalDNA::generate_new()?;
350 child.sequence = new_sequence;
351 child.generation = self.generation.max(other.generation) + 1;
352 child.parent_hash = Some(self.get_hash());
353
354 child.metadata.species = if rand::random::<bool>() {
356 self.metadata.species.clone()
357 } else {
358 other.metadata.species.clone()
359 };
360 child.metadata.mutation_rate = (self.metadata.mutation_rate + other.metadata.mutation_rate) / 2.0;
361 child.metadata.crossover_compatibility = (self.metadata.crossover_compatibility + other.metadata.crossover_compatibility) / 2.0;
362 child.metadata.adaptation_score = (self.metadata.adaptation_score + other.metadata.adaptation_score) / 2.0;
363 child.metadata.neural_complexity = (self.metadata.neural_complexity + other.metadata.neural_complexity) / 2.0;
364
365 child.fitness = self.fitness.max(other.fitness) * 0.95; Ok(child)
369 }
370
371 pub fn evolve_keys(&mut self, new_generation: u64) -> Result<(), DNAError> {
373 let mut seed = [0u8; 32];
375 let mut hasher = Sha256::new();
376 hasher.update(&self.keypair.secret_key);
377 hasher.update(&new_generation.to_le_bytes());
378 hasher.update(&self.sequence);
379 seed.copy_from_slice(&hasher.finalize());
380
381 let mut csprng = rand::rngs::StdRng::from_seed(seed);
382 let mut secret_bytes = [0u8; 32];
383 csprng.fill_bytes(&mut secret_bytes);
384 let new_signing_key = SigningKey::from_bytes(&secret_bytes);
385 let new_verifying_key = new_signing_key.verifying_key();
386
387 self.keypair = DNAKeypair {
388 public_key: new_verifying_key.to_bytes(),
389 secret_key: new_signing_key.to_bytes(),
390 key_generation: new_generation,
391 derivation_path: {
392 let mut path = self.keypair.derivation_path.clone();
393 path.push(new_generation as u32);
394 path
395 },
396 };
397
398 Ok(())
399 }
400
401 pub fn get_hash(&self) -> String {
403 let mut hasher = Sha256::new();
404 hasher.update(&self.sequence);
405 hasher.update(&self.generation.to_le_bytes());
406 hasher.update(&self.keypair.public_key);
407 format!("{:x}", hasher.finalize())
408 }
409
410 pub fn sign_data(&self, data: &[u8]) -> Result<Vec<u8>, DNAError> {
412 let signing_key = SigningKey::from_bytes(&self.keypair.secret_key);
413
414 Ok(signing_key.sign(data).to_bytes().to_vec())
415 }
416
417 pub fn verify_signature(&self, data: &[u8], signature: &[u8]) -> bool {
419 if let Ok(verifying_key) = VerifyingKey::from_bytes(&self.keypair.public_key) {
420 if signature.len() == 64 {
421 let sig_bytes: [u8; 64] = signature.try_into().unwrap();
422 let sig = Signature::from_bytes(&sig_bytes);
423 return verifying_key.verify(data, &sig).is_ok();
424 }
425 }
426 false
427 }
428
429 pub fn genetic_distance(&self, other: &DigitalDNA) -> f64 {
431 let min_len = self.sequence.len().min(other.sequence.len());
432 let max_len = self.sequence.len().max(other.sequence.len());
433
434 if max_len == 0 {
435 return 0.0;
436 }
437
438 let mut differences = 0;
439 for i in 0..min_len {
440 if self.sequence[i] != other.sequence[i] {
441 differences += 1;
442 }
443 }
444
445 differences += max_len - min_len;
447
448 differences as f64 / max_len as f64
449 }
450
451 pub fn update_fitness(&mut self, performance_score: f64) {
453 self.fitness = (self.fitness * 0.9) + (performance_score * 0.1);
455
456 self.metadata.adaptation_score = (self.metadata.adaptation_score * 0.8) + (performance_score * 0.2);
458
459 self.fitness = self.fitness.max(0.0).min(2.0);
461 }
462
463 pub fn get_info(&self) -> DNAInfo {
465 DNAInfo {
466 hash: self.get_hash(),
467 generation: self.generation,
468 sequence_length: self.sequence.len(),
469 fitness: self.fitness,
470 mutation_count: self.mutations.len(),
471 biological_age: self.metadata.biological_age,
472 species: self.metadata.species.clone(),
473 mutation_rate: self.metadata.mutation_rate,
474 adaptation_score: self.metadata.adaptation_score,
475 neural_complexity: self.metadata.neural_complexity,
476 created_at: self.created_at,
477 key_generation: self.keypair.key_generation,
478 }
479 }
480}
481
482#[derive(Debug, Clone, Serialize, Deserialize)]
484pub struct DNAInfo {
485 pub hash: String,
486 pub generation: u64,
487 pub sequence_length: usize,
488 pub fitness: f64,
489 pub mutation_count: usize,
490 pub biological_age: u64,
491 pub species: String,
492 pub mutation_rate: f64,
493 pub adaptation_score: f64,
494 pub neural_complexity: f64,
495 pub created_at: u64,
496 pub key_generation: u64,
497}
498
499#[derive(Debug, thiserror::Error)]
501pub enum DNAError {
502 #[error("Invalid secret key format")]
503 InvalidSecretKey,
504 #[error("Invalid public key format")]
505 InvalidPublicKey,
506 #[error("Invalid mutation position: {0}")]
507 InvalidMutationPosition(usize),
508 #[error("Invalid mutation range: {0} to {1}")]
509 InvalidMutationRange(usize, usize),
510 #[error("Crossover incompatible - compatibility too low")]
511 CrossoverIncompatible,
512 #[error("Sequence too short for crossover")]
513 SequenceTooShort,
514 #[error("Key evolution failed")]
515 KeyEvolutionFailed,
516 #[error("Cryptographic operation failed: {0}")]
517 CryptographicError(String),
518}
519
520#[cfg(test)]
521mod tests {
522 use super::*;
523
524 #[test]
525 fn test_dna_generation() {
526 let dna = DigitalDNA::generate_new().unwrap();
527 assert!(!dna.sequence.is_empty());
528 assert_eq!(dna.generation, 0);
529 assert_eq!(dna.fitness, 1.0);
530 assert!(dna.mutations.is_empty());
531 }
532
533 #[test]
534 fn test_dna_hash() {
535 let dna = DigitalDNA::generate_new().unwrap();
536 let hash1 = dna.get_hash();
537 let hash2 = dna.get_hash();
538 assert_eq!(hash1, hash2);
539 assert_eq!(hash1.len(), 64); }
541
542 #[test]
543 fn test_dna_signing() {
544 let dna = DigitalDNA::generate_new().unwrap();
545 let message = b"Hello, digital world!";
546
547 let signature = dna.sign_data(message).unwrap();
548 assert!(dna.verify_signature(message, &signature));
549
550 let wrong_message = b"Hello, analog world!";
552 assert!(!dna.verify_signature(wrong_message, &signature));
553 }
554
555 #[test]
556 fn test_point_mutation() {
557 let mut dna = DigitalDNA::generate_new().unwrap();
558 let original_sequence = dna.sequence.clone();
559
560 let mutation = Mutation::PointMutation {
561 position: 0,
562 old_value: original_sequence[0],
563 new_value: 255,
564 timestamp: 0,
565 };
566
567 dna.mutate(mutation).unwrap();
568
569 assert_eq!(dna.sequence[0], 255);
570 assert_eq!(dna.generation, 1);
571 assert_eq!(dna.mutations.len(), 1);
572 assert!(dna.fitness < 1.0);
573 }
574
575 #[test]
576 fn test_insertion_mutation() {
577 let mut dna = DigitalDNA::generate_new().unwrap();
578 let original_len = dna.sequence.len();
579
580 let mutation = Mutation::Insertion {
581 position: 0,
582 sequence: vec![1, 2, 3],
583 timestamp: 0,
584 };
585
586 dna.mutate(mutation).unwrap();
587
588 assert_eq!(dna.sequence.len(), original_len + 3);
589 assert_eq!(dna.sequence[0], 1);
590 assert_eq!(dna.sequence[1], 2);
591 assert_eq!(dna.sequence[2], 3);
592 }
593
594 #[test]
595 fn test_deletion_mutation() {
596 let mut dna = DigitalDNA::generate_new().unwrap();
597 let original_len = dna.sequence.len();
598
599 let mutation = Mutation::Deletion {
600 position: 0,
601 length: 2,
602 timestamp: 0,
603 };
604
605 dna.mutate(mutation).unwrap();
606
607 assert_eq!(dna.sequence.len(), original_len - 2);
608 }
609
610 #[test]
611 fn test_dna_crossover() {
612 let dna1 = DigitalDNA::generate_new().unwrap();
613 let dna2 = DigitalDNA::generate_new().unwrap();
614
615 let child = dna1.crossover(&dna2).unwrap();
616
617 assert_eq!(child.generation, dna1.generation.max(dna2.generation) + 1);
618 assert!(child.parent_hash.is_some());
619 assert!(!child.sequence.is_empty());
620 assert!(child.fitness <= dna1.fitness.max(dna2.fitness));
621 }
622
623 #[test]
624 fn test_genetic_distance() {
625 let dna1 = DigitalDNA::generate_new().unwrap();
626 let dna2 = DigitalDNA::generate_new().unwrap();
627
628 let distance = dna1.genetic_distance(&dna2);
629 assert!(distance >= 0.0 && distance <= 1.0);
630
631 let self_distance = dna1.genetic_distance(&dna1);
633 assert_eq!(self_distance, 0.0);
634 }
635
636 #[test]
637 fn test_fitness_update() {
638 let mut dna = DigitalDNA::generate_new().unwrap();
639 let initial_fitness = dna.fitness;
640
641 dna.update_fitness(0.8);
642 assert_ne!(dna.fitness, initial_fitness);
643
644 dna.update_fitness(1.2);
645 assert!(dna.fitness <= 2.0); }
647
648 #[test]
649 fn test_key_evolution() {
650 let mut dna = DigitalDNA::generate_new().unwrap();
651 let _original_generation = dna.keypair.key_generation;
652 let original_public_key = dna.keypair.public_key;
653
654 dna.evolve_keys(1).unwrap();
655
656 assert_eq!(dna.keypair.key_generation, 1);
657 assert_ne!(dna.keypair.public_key, original_public_key);
658 assert_eq!(dna.keypair.derivation_path.len(), 2);
659 }
660
661 #[test]
662 fn test_random_mutation_generation() {
663 let dna = DigitalDNA::generate_new().unwrap();
664
665 for _ in 0..10 {
667 let mutation = dna.generate_random_mutation();
668 match mutation {
670 Mutation::PointMutation { position, .. } => {
671 assert!(position < dna.sequence.len());
672 },
673 Mutation::Insertion { position, .. } => {
674 assert!(position <= dna.sequence.len());
675 },
676 Mutation::Deletion { position, length, .. } => {
677 assert!(position < dna.sequence.len());
678 assert!(length > 0);
679 },
680 _ => {
681 }
683 }
684 }
685 }
686
687 #[test]
688 fn test_dna_info() {
689 let dna = DigitalDNA::generate_new().unwrap();
690 let info = dna.get_info();
691
692 assert_eq!(info.hash, dna.get_hash());
693 assert_eq!(info.generation, dna.generation);
694 assert_eq!(info.sequence_length, dna.sequence.len());
695 assert_eq!(info.fitness, dna.fitness);
696 assert_eq!(info.species, "TRON");
697 }
698}