summaryrefslogtreecommitdiffstats
path: root/network/src/dandelion.rs
blob: daca85f82bab06e906ac3d04ed360436f29cfc08 (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
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
use onioncoin_timing::{DelayStrategy, delay::DelaySequence};
use rand::Rng;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;

/// Dandelion++ phases for transaction propagation
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum DandelionPhase {
    /// STEM phase: forward to single peer with delays
    Stem,
    /// FLUFF phase: broadcast to all peers
    Fluff,
}

/// Router for Dandelion++ protocol
#[derive(Debug)]
pub struct DandelionRouter<TxId> {
    /// Current phase for each transaction
    phases: HashMap<TxId, DandelionPhase>,

    /// Hop count for STEM phase
    stem_hops: HashMap<TxId, u32>,

    /// Configuration
    config: DandelionConfig,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DandelionConfig {
    /// Minimum STEM hops before transitioning to FLUFF
    pub min_stem_hops: u32,

    /// Maximum STEM hops before forcing FLUFF
    pub max_stem_hops: u32,

    /// Probability of transitioning to FLUFF at each hop (0.0 - 1.0)
    pub fluff_probability: f64,

    /// Enable delays between hops
    pub use_delays: bool,
}

impl Default for DandelionConfig {
    fn default() -> Self {
        Self {
            min_stem_hops: 1,
            max_stem_hops: 4,
            fluff_probability: 0.25, // 25% chance per hop after min
            use_delays: true,
        }
    }
}

impl<TxId: std::hash::Hash + Eq + Clone> DandelionRouter<TxId> {
    pub fn new(config: DandelionConfig) -> Self {
        Self {
            phases: HashMap::new(),
            stem_hops: HashMap::new(),
            config,
        }
    }

    /// Register a new transaction (starts in STEM phase)
    pub fn register_transaction(&mut self, tx_id: TxId) {
        self.phases.insert(tx_id.clone(), DandelionPhase::Stem);
        self.stem_hops.insert(tx_id, 0);
    }

    /// Process a hop and determine if should transition to FLUFF
    pub fn process_hop(&mut self, tx_id: &TxId) -> DandelionPhase {
        let current_phase = self.phases.get(tx_id).copied().unwrap_or(DandelionPhase::Stem);

        if current_phase == DandelionPhase::Fluff {
            return DandelionPhase::Fluff;
        }

        // Increment hop count
        let hops = self.stem_hops.entry(tx_id.clone()).or_insert(0);
        *hops += 1;

        // Force FLUFF if max hops reached
        if *hops >= self.config.max_stem_hops {
            self.phases.insert(tx_id.clone(), DandelionPhase::Fluff);
            return DandelionPhase::Fluff;
        }

        // If past min hops, randomly transition to FLUFF
        if *hops >= self.config.min_stem_hops {
            let mut rng = rand::thread_rng();
            if rng.gen_bool(self.config.fluff_probability) {
                self.phases.insert(tx_id.clone(), DandelionPhase::Fluff);
                return DandelionPhase::Fluff;
            }
        }

        DandelionPhase::Stem
    }

    /// Get current phase for a transaction
    pub fn get_phase(&self, tx_id: &TxId) -> Option<DandelionPhase> {
        self.phases.get(tx_id).copied()
    }

    /// Force transition to FLUFF phase
    pub fn force_fluff(&mut self, tx_id: &TxId) {
        self.phases.insert(tx_id.clone(), DandelionPhase::Fluff);
    }

    /// Get number of STEM hops for a transaction
    pub fn get_stem_hops(&self, tx_id: &TxId) -> u32 {
        self.stem_hops.get(tx_id).copied().unwrap_or(0)
    }

    /// Clean up old transactions
    pub fn cleanup(&mut self, tx_ids: &[TxId]) {
        for tx_id in tx_ids {
            self.phases.remove(tx_id);
            self.stem_hops.remove(tx_id);
        }
    }

    /// Generate delay sequence for STEM phase
    pub fn create_stem_delays(&self) -> DelaySequence {
        DelaySequence::dandelion_stem()
    }
}

/// Represents a routing decision for Dandelion++
#[derive(Debug, Clone)]
pub struct RoutingDecision {
    /// Phase to use
    pub phase: DandelionPhase,

    /// Target peers (1 for STEM, multiple for FLUFF)
    pub target_peers: TargetPeers,

    /// Delay before forwarding
    pub delay: Option<DelayStrategy>,
}

#[derive(Debug, Clone)]
pub enum TargetPeers {
    /// Single peer (for STEM)
    Single(PeerId),

    /// Multiple peers (for FLUFF broadcast)
    Multiple(Vec<PeerId>),

    /// Random subset of peers
    RandomSubset { count: usize },
}

/// Placeholder for peer identifier
pub type PeerId = String;

impl RoutingDecision {
    /// Create STEM routing decision
    pub fn stem(peer: PeerId, delay: DelayStrategy) -> Self {
        Self {
            phase: DandelionPhase::Stem,
            target_peers: TargetPeers::Single(peer),
            delay: Some(delay),
        }
    }

    /// Create FLUFF routing decision
    pub fn fluff(peers: Vec<PeerId>, delay: Option<DelayStrategy>) -> Self {
        Self {
            phase: DandelionPhase::Fluff,
            target_peers: TargetPeers::Multiple(peers),
            delay,
        }
    }

    /// Create random subset FLUFF
    pub fn fluff_random(count: usize) -> Self {
        Self {
            phase: DandelionPhase::Fluff,
            target_peers: TargetPeers::RandomSubset { count },
            delay: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_dandelion_registration() {
        let mut router = DandelionRouter::<u64>::new(DandelionConfig::default());
        router.register_transaction(1);

        assert_eq!(router.get_phase(&1), Some(DandelionPhase::Stem));
        assert_eq!(router.get_stem_hops(&1), 0);
    }

    #[test]
    fn test_dandelion_hop_progression() {
        let mut router = DandelionRouter::<u64>::new(DandelionConfig::default());
        router.register_transaction(1);

        // Process hops
        for _ in 0..3 {
            router.process_hop(&1);
        }

        assert!(router.get_stem_hops(&1) >= 3);
    }

    #[test]
    fn test_dandelion_force_fluff() {
        let config = DandelionConfig {
            min_stem_hops: 1,
            max_stem_hops: 10,
            fluff_probability: 0.0, // Never random transition
            use_delays: true,
        };

        let mut router = DandelionRouter::<u64>::new(config);
        router.register_transaction(1);

        // Should stay in STEM
        router.process_hop(&1);
        assert_eq!(router.get_phase(&1), Some(DandelionPhase::Stem));

        // Force FLUFF
        router.force_fluff(&1);
        assert_eq!(router.get_phase(&1), Some(DandelionPhase::Fluff));
    }

    #[test]
    fn test_dandelion_max_hops() {
        let config = DandelionConfig {
            min_stem_hops: 1,
            max_stem_hops: 3,
            fluff_probability: 0.0,
            use_delays: true,
        };

        let mut router = DandelionRouter::<u64>::new(config);
        router.register_transaction(1);

        // Process max hops
        for _ in 0..3 {
            router.process_hop(&1);
        }

        // Should transition to FLUFF at max hops
        assert_eq!(router.get_phase(&1), Some(DandelionPhase::Fluff));
    }

    #[test]
    fn test_routing_decision() {
        let stem_decision = RoutingDecision::stem(
            "peer1".to_string(),
            DelayStrategy::dandelion_stem(),
        );

        assert_eq!(stem_decision.phase, DandelionPhase::Stem);
        assert!(stem_decision.delay.is_some());

        let fluff_decision = RoutingDecision::fluff(
            vec!["peer1".to_string(), "peer2".to_string()],
            None,
        );

        assert_eq!(fluff_decision.phase, DandelionPhase::Fluff);
    }
}