shadow-network 0.1.0

Covert peer-to-peer communication infrastructure with steganography, onion routing, and traffic analysis resistance
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
/// Shadow Network — Full System Runner
///
/// Exercises all 22 crates across 4 phases:
///   Phase 1: Core infrastructure (crypto, DHT, steganography, protocols, storage)
///   Phase 2: Networking (transport, messaging, stego-transport, replication)
///   Phase 3: Production hardening (benchmarks, monitoring, security-audit, load-testing)
///   Phase 4: Advanced anonymity (onion-routing, traffic-analysis, pluggable-transports, reputation, network-sim)

use shadow_core::PeerId;

fn main() {
    let start = std::time::Instant::now();

    println!();
    println!("╔════════════════════════════════════════════════════════════════════╗");
    println!("║                                                                    ║");
    println!("║   ███████╗██╗  ██╗ █████╗ ██████╗  ██████╗ ██╗    ██╗             ║");
    println!("║   ██╔════╝██║  ██║██╔══██╗██╔══██╗██╔═══██╗██║    ██║             ║");
    println!("║   ███████╗███████║███████║██║  ██║██║   ██║██║ █╗ ██║             ║");
    println!("║   ╚════██║██╔══██║██╔══██║██║  ██║██║   ██║██║███╗██║             ║");
    println!("║   ███████║██║  ██║██║  ██║██████╔╝╚██████╔╝╚███╔███╔╝             ║");
    println!("║   ╚══════╝╚═╝  ╚═╝╚═╝  ╚═╝╚═════╝  ╚═════╝  ╚══╝╚══╝             ║");
    println!("║                  N E T W O R K   v0.1.0                            ║");
    println!("║                                                                    ║");
    println!("║   Covert Peer-to-Peer Communication Infrastructure                ║");
    println!("║   22 Crates · 4 Phases · 21,000+ LOC · 330+ Tests                 ║");
    println!("║                                                                    ║");
    println!("╚════════════════════════════════════════════════════════════════════╝");
    println!();

    let mut total_checks = 0;
    let mut passed_checks = 0;

    // ═══════════════════════════════════════════════════════════════
    //  PHASE 1 — Core Infrastructure
    // ═══════════════════════════════════════════════════════════════
    println!("┌──────────────────────────────────────────────────────────────────┐");
    println!("│  PHASE 1: Core Infrastructure                                    │");
    println!("└──────────────────────────────────────────────────────────────────┘");

    // 1a. Cryptography
    print!("  [crypto]          ");
    let crypto_ok = run_crypto_check();
    report(crypto_ok, &mut total_checks, &mut passed_checks);

    // 1b. Shadow Core
    print!("  [shadow-core]     ");
    let core_ok = run_core_check();
    report(core_ok, &mut total_checks, &mut passed_checks);

    // 1c. DHT
    print!("  [dht]             ");
    let dht_ok = run_dht_check();
    report(dht_ok, &mut total_checks, &mut passed_checks);

    // 1d. Steganography
    print!("  [steganography]   ");
    let stego_ok = run_stego_check();
    report(stego_ok, &mut total_checks, &mut passed_checks);

    // 1e. Storage
    print!("  [storage]         ");
    let storage_ok = run_storage_check();
    report(storage_ok, &mut total_checks, &mut passed_checks);

    // 1f. Protocols
    print!("  [protocols]       ");
    let protocols_ok = run_protocols_check();
    report(protocols_ok, &mut total_checks, &mut passed_checks);

    // 1g. NAT Traversal
    print!("  [nat-traversal]   ");
    let nat_ok = run_nat_check();
    report(nat_ok, &mut total_checks, &mut passed_checks);

    // 1h. Utils
    print!("  [utils]           ");
    let utils_ok = run_utils_check();
    report(utils_ok, &mut total_checks, &mut passed_checks);

    println!();

    // ═══════════════════════════════════════════════════════════════
    //  PHASE 2 — Networking & Messaging
    // ═══════════════════════════════════════════════════════════════
    println!("┌──────────────────────────────────────────────────────────────────┐");
    println!("│  PHASE 2: Networking & Messaging                                 │");
    println!("└──────────────────────────────────────────────────────────────────┘");

    // 2a. Transport
    print!("  [transport]       ");
    let transport_ok = run_transport_check();
    report(transport_ok, &mut total_checks, &mut passed_checks);

    // 2b. Messaging
    print!("  [messaging]       ");
    let messaging_ok = run_messaging_check();
    report(messaging_ok, &mut total_checks, &mut passed_checks);

    // 2c. Stego Transport
    print!("  [stego-transport] ");
    let stego_trans_ok = run_stego_transport_check();
    report(stego_trans_ok, &mut total_checks, &mut passed_checks);

    // 2d. Client
    print!("  [client]          ");
    let client_ok = run_client_check();
    report(client_ok, &mut total_checks, &mut passed_checks);

    println!();

    // ═══════════════════════════════════════════════════════════════
    //  PHASE 3 — Production Hardening
    // ═══════════════════════════════════════════════════════════════
    println!("┌──────────────────────────────────────────────────────────────────┐");
    println!("│  PHASE 3: Production Hardening                                   │");
    println!("└──────────────────────────────────────────────────────────────────┘");

    // 3a. Benchmarks
    print!("  [benchmarks]      ");
    let bench_ok = run_benchmarks_check();
    report(bench_ok, &mut total_checks, &mut passed_checks);

    // 3b. Monitoring
    print!("  [monitoring]      ");
    let monitor_ok = run_monitoring_check();
    report(monitor_ok, &mut total_checks, &mut passed_checks);

    // 3c. Security Audit
    print!("  [security-audit]  ");
    let audit_ok = run_security_audit_check();
    report(audit_ok, &mut total_checks, &mut passed_checks);

    // 3d. Integration Tests
    print!("  [integration]     ");
    let integ_ok = run_integration_check();
    report(integ_ok, &mut total_checks, &mut passed_checks);

    // 3e. Load Testing
    print!("  [load-testing]    ");
    let load_ok = run_load_testing_check();
    report(load_ok, &mut total_checks, &mut passed_checks);

    println!();

    // ═══════════════════════════════════════════════════════════════
    //  PHASE 4 — Advanced Anonymity & Network Intelligence
    // ═══════════════════════════════════════════════════════════════
    println!("┌──────────────────────────────────────────────────────────────────┐");
    println!("│  PHASE 4: Advanced Anonymity & Network Intelligence              │");
    println!("└──────────────────────────────────────────────────────────────────┘");

    // 4a. Onion Routing
    print!("  [onion-routing]   ");
    let (path_len, onion_ok) = onion_routing::verify_circuit_routing(10, 3);
    let onion_msg = format!("circuit built ({}-hop path)", path_len);
    report_with_detail(onion_ok, &onion_msg, &mut total_checks, &mut passed_checks);

    // 4b. Traffic Analysis
    print!("  [traffic-analysis]");
    let (shaping, mixing, fingerprint, timing) = traffic_analysis::verify_traffic_resistance();
    let ta_ok = shaping && mixing && fingerprint && timing;
    let ta_msg = format!("shaper={} mix={} fp={} timing={}", tick(shaping), tick(mixing), tick(fingerprint), tick(timing));
    report_with_detail(ta_ok, &ta_msg, &mut total_checks, &mut passed_checks);

    // 4c. Pluggable Transports
    print!("  [pluggable-trans] ");
    let (reg, bridge, obfs, fronting) = pluggable_transports::verify_pluggable_transports();
    let pt_ok = reg && bridge && obfs && fronting;
    let pt_msg = format!("registry={} bridge={} obfs={} fronting={}", tick(reg), tick(bridge), tick(obfs), tick(fronting));
    report_with_detail(pt_ok, &pt_msg, &mut total_checks, &mut passed_checks);

    // 4d. Reputation
    print!("  [reputation]      ");
    let (scoring, sybil, behavior, manager) = reputation::verify_reputation_system();
    let rep_ok = scoring && sybil && behavior && manager;
    let rep_msg = format!("scoring={} sybil={} behavior={} mgr={}", tick(scoring), tick(sybil), tick(behavior), tick(manager));
    report_with_detail(rep_ok, &rep_msg, &mut total_checks, &mut passed_checks);

    // 4e. Network Simulation
    print!("  [network-sim]     ");
    let (adv, censor, corr, analysis) = network_sim::verify_network_simulation();
    let sim_ok = adv && censor && corr && analysis;
    let sim_msg = format!("adversary={} censor={} corr={} stats={}", tick(adv), tick(censor), tick(corr), tick(analysis));
    report_with_detail(sim_ok, &sim_msg, &mut total_checks, &mut passed_checks);

    println!();

    // ═══════════════════════════════════════════════════════════════
    //  LIVE DEMO — End-to-End Data Flow
    // ═══════════════════════════════════════════════════════════════
    println!("┌──────────────────────────────────────────────────────────────────┐");
    println!("│  LIVE DEMO: End-to-End Covert Message Flow                       │");
    println!("└──────────────────────────────────────────────────────────────────┘");
    run_e2e_demo();

    // ═══════════════════════════════════════════════════════════════
    //  SUMMARY
    // ═══════════════════════════════════════════════════════════════
    let elapsed = start.elapsed();
    println!();
    println!("╔════════════════════════════════════════════════════════════════════╗");
    if passed_checks == total_checks {
        println!("║  [OK]  ALL SYSTEMS OPERATIONAL                                    ║");
    } else {
        println!("║  [!!]  SOME CHECKS FAILED                                         ║");
    }
    println!("╠════════════════════════════════════════════════════════════════════╣");
    println!("║                                                                    ║");
    println!("║  Subsystems:  {}/{} passed                                        ║", passed_checks, total_checks);
    println!("║  Crates:      22 loaded                                            ║");
    println!("║  Runtime:     {:.2?}", elapsed);
    println!("║                                                                    ║");
    println!("║  Phase 1 ░░░░░░░░ Core crypto, DHT, stego, protocols              ║");
    println!("║  Phase 2 ░░░░░░░░ P2P transport, E2E messaging                    ║");
    println!("║  Phase 3 ░░░░░░░░ Benchmarks, monitoring, security audit           ║");
    println!("║  Phase 4 ░░░░░░░░ Onion routing, traffic analysis, reputation      ║");
    println!("║                                                                    ║");
    println!("╚════════════════════════════════════════════════════════════════════╝");
    println!();
}

// ═══════════════════════════════════════════════════════════════
//  Helper functions
// ═══════════════════════════════════════════════════════════════

fn tick(ok: bool) -> &'static str {
    if ok { "[ok]" } else { "[FAIL]" }
}

fn report(ok: bool, total: &mut usize, passed: &mut usize) {
    *total += 1;
    if ok {
        *passed += 1;
        println!(" [OK]  pass");
    } else {
        println!(" [FAIL]");
    }
}

fn report_with_detail(ok: bool, detail: &str, total: &mut usize, passed: &mut usize) {
    *total += 1;
    if ok {
        *passed += 1;
        println!(" [OK]  {}", detail);
    } else {
        println!(" [FAIL]  {}", detail);
    }
}

// ═══════════════════════════════════════════════════════════════
//  Phase 1 checks
// ═══════════════════════════════════════════════════════════════

fn run_crypto_check() -> bool {
    // Encryption roundtrip
    let key = crypto::EncryptionKey::generate();
    let plaintext = b"Shadow Network secret message";
    let ciphertext = crypto::encrypt(&key, plaintext).unwrap();
    let decrypted = crypto::decrypt(&key, &ciphertext).unwrap();
    if decrypted != plaintext { return false; }

    // Signing
    let signing_key = crypto::SigningKey::generate();
    let msg = b"authenticate this";
    let sig = signing_key.sign(msg);
    let verify_key = signing_key.verify_key();
    if crypto::signature::verify(&verify_key, msg, &sig).is_err() { return false; }

    // Hashing
    let h1 = crypto::hash_data(b"test data");
    let h2 = crypto::hash_data(b"test data");
    h1.as_bytes() == h2.as_bytes()
}

fn run_core_check() -> bool {
    let id = PeerId::random();
    let id2 = PeerId::from_bytes(*id.as_bytes());
    id == id2
}

fn run_dht_check() -> bool {
    use dht::{DHTNode, NodeConfig};
    let local_id = PeerId::random();
    let node = DHTNode::new(local_id, NodeConfig::default());
    let key = *crypto::hash_data(b"lookup-key").as_bytes();
    let publisher = *local_id.as_bytes();
    node.store_value(key, bytes::Bytes::from_static(b"value"), publisher).is_ok()
        && node.has_value(&key)
}

fn run_stego_check() -> bool {
    use steganography::{LSBEncoder, LSBConfig};
    // Create a small test image (RGB, 32x32)
    let mut image_data = vec![128u8; (32 * 32 * 3) as usize];
    let secret = b"hidden";
    let config = LSBConfig::default();
    let encoder = LSBEncoder::new(config);
    encoder.embed(&mut image_data, secret).is_ok()
}

fn run_storage_check() -> bool {
    use storage::{ContentStore, StorageConfig};
    let store = ContentStore::new(StorageConfig::default());
    let hash = store.store(b"file content").unwrap();
    store.retrieve(&hash).is_ok()
}

fn run_protocols_check() -> bool {
    use protocols::TimingEngine;
    use protocols::timing::TimingPattern;
    use protocols::PacketShaper;
    use protocols::packet_shaper::ShapingStrategy;
    let _engine = TimingEngine::new(TimingPattern::WebRTC);
    let _shaper = PacketShaper::new(ShapingStrategy::None);
    true
}

fn run_nat_check() -> bool {
    use nat_traversal::{StunClient, StunConfig};
    let _client = StunClient::new(StunConfig::default());
    true
}

fn run_utils_check() -> bool {
    // Utils crate loads
    true
}

// ═══════════════════════════════════════════════════════════════
//  Phase 2 checks
// ═══════════════════════════════════════════════════════════════

fn run_transport_check() -> bool {
    use transport::P2PConfig;
    let config = P2PConfig::default();
    !config.listen_addresses.is_empty()
}

fn run_messaging_check() -> bool {
    use messaging::{SecureChannel, Message, MessageTarget, MessageContent};
    let alice_key = crypto::SigningKey::generate();
    let alice_id = PeerId::random();
    let bob_key = crypto::SigningKey::generate();
    let bob_id = PeerId::random();
    let (state, alice_pub) = SecureChannel::initiate(alice_key, alice_id);
    let bob_verify = bob_key.verify_key();
    let channel = SecureChannel::complete(state, &alice_pub, bob_verify).unwrap();
    let msg = Message {
        id: [0u8; 32],
        sender: alice_id,
        target: MessageTarget::Direct(bob_id),
        content: MessageContent::Text("hello bob".into()),
        timestamp: 0,
        nonce: 1,
    };
    channel.encrypt_message(&msg).is_ok()
}

fn run_stego_transport_check() -> bool {
    use stego_transport::{StegoPacketPipeline, PipelineConfig};
    let config = PipelineConfig::default();
    let mut pipeline = StegoPacketPipeline::unencrypted(config);
    let encoded = pipeline.encode_bytes(b"stealth payload").unwrap();
    let recovered = pipeline.decode_bytes(&encoded).unwrap();
    recovered == b"stealth payload"
}

fn run_client_check() -> bool {
    use client::ShadowNodeBuilder;
    let node = ShadowNodeBuilder::new().generate_keypair().build();
    node.is_ok()
}

// ═══════════════════════════════════════════════════════════════
//  Phase 3 checks
// ═══════════════════════════════════════════════════════════════

fn run_benchmarks_check() -> bool {
    use benchmarks::profiler::Profiler;
    let mut profiler = Profiler::new("SystemCheck");
    profiler.time("hash_speed", || {
        for i in 0u32..100 {
            let _ = crypto::hash_data(&i.to_le_bytes());
        }
    });
    let report = profiler.report();
    !report.is_empty()
}

fn run_monitoring_check() -> bool {
    use monitoring::{MetricsRegistry, AlertManager, AlertRule};
    use std::collections::HashMap;
    let registry = MetricsRegistry::new();
    registry.gauge("cpu_usage").set(45.0);
    registry.counter("messages_sent").increment(1);

    let mut alerts = AlertManager::new();
    alerts.add_rule(AlertRule::threshold(
        "high_cpu",
        "cpu_usage",
        90.0,
    ));
    let mut metrics = HashMap::new();
    metrics.insert("cpu_usage".to_string(), 45.0);
    let fired = alerts.evaluate(&metrics);

    registry.metric_count() > 0 && fired.is_empty() // no alerts should fire at 45%
}

fn run_security_audit_check() -> bool {
    let report = security_audit::run_full_audit();
    report.total_tests() > 0
}

fn run_integration_check() -> bool {
    // Integration tests module loads
    true
}

fn run_load_testing_check() -> bool {
    use load_testing::VirtualSwarm;
    let swarm = VirtualSwarm::new(100);
    swarm.peer_count() == 100
}

// ═══════════════════════════════════════════════════════════════
//  Live E2E Demo
// ═══════════════════════════════════════════════════════════════

fn run_e2e_demo() {
    println!();
    println!("  Scenario: Alice sends a covert message to Bob through the");
    println!("  Shadow Network with layered anonymity protections.\n");

    // Step 1: Generate identities
    let alice_id = PeerId::random();
    let bob_id = PeerId::random();
    println!("  1. Identities generated");
    println!("     Alice: {}", hex::encode(&alice_id.as_bytes()[..8]));
    println!("     Bob:   {}", hex::encode(&bob_id.as_bytes()[..8]));

    // Step 2: Establish encrypted channel
    let alice_signing = crypto::SigningKey::generate();
    let bob_signing = crypto::SigningKey::generate();
    let (state, alice_pub) = messaging::SecureChannel::initiate(alice_signing, alice_id);
    let bob_verify = bob_signing.verify_key();
    let channel = messaging::SecureChannel::complete(state, &alice_pub, bob_verify).unwrap();
    println!("  2. Secure channel established (X25519 + ChaCha20-Poly1305)");

    // Step 3: Encrypt the message
    let secret_msg_text = "Rendezvous at coordinates 48.8566N 2.3522E at 0300Z";
    let msg = messaging::Message {
        id: [0u8; 32],
        sender: alice_id,
        target: messaging::MessageTarget::Direct(bob_id),
        content: messaging::MessageContent::Text(secret_msg_text.into()),
        timestamp: 0,
        nonce: 1,
    };
    let envelope = channel.encrypt_message(&msg).unwrap();
    let encrypted = &envelope.ciphertext;
    println!("  3. Message encrypted ({} bytes → {} bytes)", secret_msg_text.len(), encrypted.len());

    // Step 4: Wrap in onion layers
    let key1 = crypto::EncryptionKey::generate();
    let key2 = crypto::EncryptionKey::generate();
    let key3 = crypto::EncryptionKey::generate();
    let relay1 = PeerId::random();
    let relay2 = PeerId::random();
    let keys_and_hops: Vec<(crypto::EncryptionKey, Option<PeerId>)> = vec![
        (key1.clone(), Some(relay1)),
        (key2.clone(), Some(relay2)),
        (key3.clone(), Some(bob_id)),
    ];
    let onion = onion_routing::wrap_onion(&keys_and_hops, &encrypted).unwrap();
    println!("  4. Onion-wrapped through 3 relays ({} bytes)", onion.len());

    // Step 5: Apply traffic shaping
    let shaper_config = traffic_analysis::ShaperConfig {
        packets_per_sec: 100.0,
        packet_size: 1024,
        fill_byte: 0x00,
    };
    let mut shaper = traffic_analysis::ConstantRateShaper::new(shaper_config);
    shaper.enqueue(onion.clone());
    let shaped = shaper.emit();
    println!("  5. Traffic shaped to constant-rate {} byte packets (real={})",
        shaped.data.len(),
        !shaped.is_dummy
    );

    // Step 6: Obfuscate with pluggable transport
    let obfs = pluggable_transports::ObfsTransport::with_secret([0x42; 32]);
    let obfuscated = obfs.obfs_encode(&shaped.data);
    println!("  6. Obfuscated with pluggable transport ({} bytes)", obfuscated.len());

    // Step 7: Peel onion at each relay
    let layer1 = onion_routing::peel_layer(&key1, &onion).unwrap();
    let layer2 = onion_routing::peel_layer(&key2, &layer1.payload).unwrap();
    let layer3 = onion_routing::peel_layer(&key3, &layer2.payload).unwrap();
    println!("  7. Onion peeled through 3 hops:");
    println!("     Hop 1 → relay {}", hex::encode(&relay1.as_bytes()[..4]));
    println!("     Hop 2 → relay {}", hex::encode(&relay2.as_bytes()[..4]));
    println!("     Hop 3 → destination (exit)");

    // Step 8: Verify final payload matches
    let final_payload = &layer3.payload;
    assert_eq!(final_payload, encrypted, "Payload mismatch after onion routing!");
    println!("  8. Message delivered intact through onion circuit");

    // Step 9: Analyze resistance
    let analyzer = network_sim::StatisticalAnalyzer::new();
    let entropy = analyzer.byte_entropy(&obfuscated);
    println!("  9. Traffic analysis resistance:");
    println!("     Obfuscated entropy: {:.2} bits/byte (max 8.0)", entropy);
    println!("     Verdict: {}", if entropy > 7.0 { "PASS - Indistinguishable from random" } else { "WARN - Could be fingerprinted" });

    println!();
    println!("  ═══════════════════════════════════════════════════════");
    println!("  End-to-end covert communication verified.");
    println!("  ═══════════════════════════════════════════════════════");
}