summaryrefslogtreecommitdiffstats
path: root/examples/timing_demo.rs
blob: b2dfdff16d6cdc0b70abc69caf75709986ec05b4 (plain) (blame)
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
/// Demonstration of OnionCoin's unique timing obfuscation features
///
/// This example shows how OnionCoin uses Tor latency as a privacy feature
/// to make transaction timing analysis impossible.

use chrono::Utc;
use onioncoin_timing::*;
use onioncoin_timing::delay::DelaySequence;
use std::time::Instant;

#[tokio::main]
async fn main() {
    println!("=== OnionCoin Timing Obfuscation Demo ===\n");

    // 1. Fuzzy Timestamps
    demo_fuzzy_timestamps();
    println!();

    // 2. Time Range Proofs
    demo_time_proofs();
    println!();

    // 3. Delay Strategies
    demo_delays().await;
    println!();

    // 4. Mixing Pool
    demo_mixing_pool();
    println!();

    // 5. Complete Transaction Flow
    demo_complete_flow().await;
}

fn demo_fuzzy_timestamps() {
    println!("šŸ“… FUZZY TIMESTAMPS");
    println!("------------------");

    let real_time = Utc::now();
    println!("Real creation time: {}", real_time.format("%Y-%m-%d %H:%M:%S"));

    // Create fuzzy time range
    let range = TimeRange::new_fuzzy(real_time);

    println!("Timestamp range:    {} to {}",
        chrono::DateTime::from_timestamp(range.earliest, 0).unwrap().format("%Y-%m-%d %H:%M:%S"),
        chrono::DateTime::from_timestamp(range.latest, 0).unwrap().format("%Y-%m-%d %H:%M:%S"),
    );

    println!("Range duration:     {} hours", range.duration_seconds() / 3600);
    println!("\nāœ… Observer cannot determine exact creation time!");
}

fn demo_time_proofs() {
    println!("šŸ” ZERO-KNOWLEDGE TIME PROOFS");
    println!("-----------------------------");

    let real_time = Utc::now();
    let seed = [42u8; 32];
    let range = TimeRange::new_fuzzy(real_time);

    let proof = TimeRangeProof::generate(&seed, real_time, &range)
        .expect("Proof generation failed");

    println!("Generated ZK proof:");
    println!("  - Earliest hash: {:x?}...", &proof.earliest_hash[..4]);
    println!("  - Latest hash:   {:x?}...", &proof.latest_hash[..4]);
    println!("  - Time commit:   {:x?}...", &proof.time_commitment[..4]);

    let is_valid = proof.verify(&range);
    println!("\nProof verification: {}", if is_valid { "āœ… VALID" } else { "āŒ INVALID" });
    println!("Real time is hidden but provably within range!");
}

async fn demo_delays() {
    println!("ā±ļø  STRATEGIC DELAYS");
    println!("-------------------");

    // Wallet broadcast delay
    println!("1. Wallet broadcast delay (5-60 min):");
    let strategy = DelayStrategy::wallet_broadcast();
    let delay = strategy.calculate();
    println!("   Random delay: {} seconds ({:.1} minutes)", delay.as_secs(), delay.as_secs() as f64 / 60.0);

    // Dandelion STEM delays
    println!("\n2. Dandelion STEM sequence (1-4 hops):");
    let mut sequence = DelaySequence::dandelion_stem();
    println!("   Hops: {}", sequence.len());

    let mut hop = 1;
    while let Some(strategy) = sequence.next() {
        let delay = strategy.calculate();
        println!("   Hop {}: {} seconds", hop, delay.as_secs());
        hop += 1;
    }

    // Node rebroadcast delay
    println!("\n3. Node rebroadcast delay (10s-2min):");
    let strategy = DelayStrategy::node_rebroadcast();
    let delay = strategy.calculate();
    println!("   Random delay: {} seconds", delay.as_secs());

    println!("\nāœ… Multiple layers of random delays obscure transaction origin!");
}

fn demo_mixing_pool() {
    println!("šŸ”€ MIXING POOL");
    println!("-------------");

    let mut pool = MixingPool::<u32>::new(
        std::time::Duration::from_secs(10),  // 10s min (demo)
        std::time::Duration::from_secs(30),  // 30s max (demo)
        100,
    );

    println!("Adding transactions to mixing pool...");
    for i in 1..=10 {
        pool.add(i);
        println!("  Added tx #{}", i);
    }

    println!("\nPool size: {} transactions", pool.len());
    println!("Waiting for minimum batch duration...");

    std::thread::sleep(std::time::Duration::from_secs(11));

    if pool.should_release() {
        let batch = pool.release_batch();
        println!("\nāœ… Released shuffled batch:");
        println!("  Original order: 1, 2, 3, 4, 5, 6, 7, 8, 9, 10");
        println!("  Shuffled order: {:?}", batch);
        println!("\nTemporal ordering destroyed!");
    }
}

async fn demo_complete_flow() {
    println!("🌊 COMPLETE TRANSACTION FLOW");
    println!("============================");

    let real_time = Utc::now();
    println!("T+0:00  User creates transaction");
    println!("        Real time: {}", real_time.format("%H:%M:%S"));

    // Step 1: Fuzzy timestamp
    let seed = [42u8; 32];
    let timing = TimingMetadata::new(real_time, &seed)
        .expect("Failed to create timing metadata");

    println!("        Timestamp range: ±{} hours", timing.time_range.duration_seconds() / 3600 / 2);

    // Step 2: Wallet delay
    println!("\nT+0:00  Wallet applies random delay...");
    let wallet_delay = DelayStrategy::Random {
        min: std::time::Duration::from_secs(2),  // Shortened for demo
        max: std::time::Duration::from_secs(5),
    };
    let actual_delay = wallet_delay.calculate();
    println!("        Waiting {} seconds", actual_delay.as_secs());

    let start = Instant::now();
    tokio::time::sleep(actual_delay).await;

    println!("T+{:04}  Transaction broadcast to Tor", start.elapsed().as_secs());

    // Step 3: Dandelion STEM
    println!("\nT+{:04}  Entering STEM phase...", start.elapsed().as_secs());
    let mut sequence = DelaySequence::new(vec![
        DelayStrategy::Fixed(std::time::Duration::from_secs(1)),
        DelayStrategy::Fixed(std::time::Duration::from_secs(1)),
    ]);

    let mut hop = 1;
    while let Some(strategy) = sequence.next() {
        strategy.sleep().await;
        println!("T+{:04}  STEM hop {} complete", start.elapsed().as_secs(), hop);
        hop += 1;
    }

    // Step 4: Transition to FLUFF
    println!("\nT+{:04}  Transitioning to FLUFF phase", start.elapsed().as_secs());
    println!("        Broadcasting to network...");

    tokio::time::sleep(std::time::Duration::from_secs(1)).await;

    println!("\nT+{:04}  āœ… Transaction propagated!", start.elapsed().as_secs());
    println!("\nšŸŽÆ PRIVACY ACHIEVED:");
    println!("   - Real creation time: HIDDEN (±{} hours ambiguity)", timing.time_range.duration_seconds() / 3600 / 2);
    println!("   - Origin node: UNKNOWN (Dandelion++ + Tor)");
    println!("   - Propagation path: UNTRACEABLE (random delays)");
    println!("   - Transaction correlation: VERY DIFFICULT (mixing pool)");
}