blvm-node 0.1.76

Bitcoin Commons BLVM: Minimal Bitcoin node implementation using blvm-protocol and blvm-consensus
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
//! Block and transaction relay
//!
//! Handles relaying blocks and transactions to peers, managing relay policies,
//! and preventing duplicate relay.
//!
//! Includes Dandelion++ integration for privacy-preserving transaction relay.

#[cfg(feature = "dandelion")]
use super::dandelion::DandelionRelay;
use crate::utils::current_timestamp;
use blvm_protocol::Hash;
use std::collections::HashMap;
use tracing::debug;
#[cfg(feature = "dandelion")]
use tracing::info;

/// Relay manager
pub struct RelayManager {
    /// Recently relayed blocks
    recently_relayed_blocks: HashMap<Hash, u64>,
    /// Recently relayed transactions
    recently_relayed_txs: HashMap<Hash, u64>,
    /// Relay policies
    policies: RelayPolicies,
    /// Dandelion++ privacy relay (only when compiled with feature)
    #[cfg(feature = "dandelion")]
    dandelion: Option<DandelionRelay>,
    /// Enable Dandelion++ (runtime toggle)
    enable_dandelion: bool,
}

/// Relay policies
#[derive(Debug, Clone)]
pub struct RelayPolicies {
    /// Maximum age for relayed items (seconds)
    pub max_relay_age: u64,
    /// Maximum number of items to track
    pub max_tracked_items: usize,
    /// Enable block relay
    pub enable_block_relay: bool,
    /// Enable transaction relay
    pub enable_tx_relay: bool,
    /// Enable Dandelion++ privacy relay
    pub enable_dandelion: bool,
}

impl Default for RelayPolicies {
    fn default() -> Self {
        Self {
            max_relay_age: 3600, // 1 hour
            max_tracked_items: 10000,
            enable_block_relay: true,
            enable_tx_relay: true,
            enable_dandelion: false, // Default OFF (requires feature flag)
        }
    }
}

impl RelayPolicies {
    /// Policies from the node relay section. Absent section uses [`RelayPolicies::default`].
    pub fn from_relay_config(cfg: &crate::config::RelayConfig) -> Self {
        Self {
            max_relay_age: cfg.max_relay_age,
            max_tracked_items: cfg.max_tracked_items,
            enable_block_relay: cfg.enable_block_relay,
            enable_tx_relay: cfg.enable_tx_relay,
            enable_dandelion: cfg.enable_dandelion,
        }
    }
}

impl Default for RelayManager {
    fn default() -> Self {
        Self::new()
    }
}

impl RelayManager {
    /// Create a new relay manager
    pub fn new() -> Self {
        let policies = RelayPolicies::default();
        Self {
            recently_relayed_blocks: HashMap::new(),
            recently_relayed_txs: HashMap::new(),
            #[cfg(feature = "dandelion")]
            dandelion: if policies.enable_dandelion {
                Some(DandelionRelay::new())
            } else {
                None
            },
            enable_dandelion: policies.enable_dandelion,
            policies,
        }
    }

    /// Configure Dandelion stem timeout (testing/integration)
    #[cfg(feature = "dandelion")]
    pub fn set_dandelion_stem_timeout(&mut self, timeout: std::time::Duration) {
        if let Some(ref mut d) = self.dandelion {
            d.set_stem_timeout(timeout);
        }
    }
    #[cfg(not(feature = "dandelion"))]
    pub fn set_dandelion_stem_timeout(&mut self, _timeout: std::time::Duration) {}

    /// Configure Dandelion fluff probability (testing/integration)
    #[cfg(feature = "dandelion")]
    pub fn set_dandelion_fluff_probability(&mut self, p: f64) {
        if let Some(ref mut d) = self.dandelion {
            d.set_fluff_probability(p);
        }
    }
    #[cfg(not(feature = "dandelion"))]
    pub fn set_dandelion_fluff_probability(&mut self, _p: f64) {}

    /// Configure Dandelion max stem hops (testing/integration)
    #[cfg(feature = "dandelion")]
    pub fn set_dandelion_max_stem_hops(&mut self, hops: u8) {
        if let Some(ref mut d) = self.dandelion {
            d.set_max_stem_hops(hops);
        }
    }
    #[cfg(not(feature = "dandelion"))]
    pub fn set_dandelion_max_stem_hops(&mut self, _hops: u8) {}

    /// Create a relay manager with custom policies
    pub fn with_policies(policies: RelayPolicies) -> Self {
        #[cfg(feature = "dandelion")]
        {
            Self::with_policies_and_dandelion(policies, None)
        }
        #[cfg(not(feature = "dandelion"))]
        {
            Self::with_policies_and_dandelion(policies)
        }
    }

    /// Policies plus the `[dandelion]` stem timeout, fluff probability, and hop cap.
    #[cfg(feature = "dandelion")]
    pub fn with_policies_and_dandelion(
        policies: RelayPolicies,
        dandelion: Option<&crate::config::DandelionConfig>,
    ) -> Self {
        let dandelion = if policies.enable_dandelion {
            Some(match dandelion {
                Some(cfg) => DandelionRelay::with_params(
                    std::time::Duration::from_secs(cfg.stem_timeout_seconds),
                    cfg.fluff_probability,
                    cfg.max_stem_hops,
                ),
                None => DandelionRelay::new(),
            })
        } else {
            None
        };
        Self {
            recently_relayed_blocks: HashMap::new(),
            recently_relayed_txs: HashMap::new(),
            dandelion,
            enable_dandelion: policies.enable_dandelion,
            policies,
        }
    }

    #[cfg(not(feature = "dandelion"))]
    fn with_policies_and_dandelion(policies: RelayPolicies) -> Self {
        Self {
            recently_relayed_blocks: HashMap::new(),
            recently_relayed_txs: HashMap::new(),
            enable_dandelion: policies.enable_dandelion,
            policies,
        }
    }

    /// Check if a block should be relayed
    pub fn should_relay_block(&self, block_hash: &Hash) -> bool {
        if !self.policies.enable_block_relay {
            return false;
        }

        if self.recently_relayed_blocks.contains_key(block_hash) {
            return false;
        }

        true
    }

    /// Check if a transaction should be relayed
    pub fn should_relay_transaction(&self, tx_hash: &Hash) -> bool {
        if !self.policies.enable_tx_relay {
            return false;
        }

        if self.recently_relayed_txs.contains_key(tx_hash) {
            return false;
        }

        true
    }

    /// Mark a block as relayed
    pub fn mark_block_relayed(&mut self, block_hash: Hash) {
        let now = current_timestamp();

        self.recently_relayed_blocks.insert(block_hash, now);
        self.cleanup_old_items();

        debug!("Marked block {} as relayed", hex::encode(block_hash));
    }

    /// Mark a transaction as relayed
    pub fn mark_transaction_relayed(&mut self, tx_hash: Hash) {
        let now = current_timestamp();

        self.recently_relayed_txs.insert(tx_hash, now);

        // Clean up Dandelion state if transitioning to fluff
        #[cfg(feature = "dandelion")]
        {
            if let Some(ref mut dandelion) = self.dandelion {
                if dandelion.should_fluff(&tx_hash) {
                    dandelion.transition_to_fluff(tx_hash);
                }
            }
        }

        self.cleanup_old_items();

        debug!("Marked transaction {} as relayed", hex::encode(tx_hash));
    }

    /// Relay transaction with Dandelion++ privacy (if enabled)
    /// Returns the peer ID to relay to (if stem phase) or None (if fluff phase - broadcast to all)
    #[cfg(feature = "dandelion")]
    pub fn relay_transaction_dandelion(
        &mut self,
        tx_hash: Hash,
        current_peer: String,
        available_peers: &[String],
    ) -> Option<String> {
        if !self.enable_dandelion || self.dandelion.is_none() {
            return None; // Normal relay (broadcast to all)
        }

        let dandelion = self.dandelion.as_mut().unwrap();

        // Check if already in stem phase
        if let Some(_next_peer) = dandelion.get_stem_peer(&tx_hash) {
            // Already in stem phase, advance
            if dandelion.should_fluff(&tx_hash) {
                dandelion.transition_to_fluff(tx_hash);
                info!(
                    "Transaction {} transitioned to fluff phase",
                    hex::encode(tx_hash)
                );
                None // Broadcast to all
            } else {
                // Advance stem phase
                dandelion.advance_stem(tx_hash, available_peers)
            }
        } else {
            // Start stem phase
            if available_peers.is_empty() {
                return None; // No peers available, skip Dandelion
            }

            let next_peer = dandelion.start_stem_phase(tx_hash, current_peer, available_peers);
            if next_peer.is_some() {
                info!(
                    "Transaction {} started Dandelion stem phase",
                    hex::encode(tx_hash)
                );
            }
            next_peer
        }
    }
    #[cfg(not(feature = "dandelion"))]
    pub fn relay_transaction_dandelion(
        &mut self,
        _tx_hash: Hash,
        _current_peer: String,
        _available_peers: &[String],
    ) -> Option<String> {
        None
    }

    /// Initialize Dandelion stem path for a peer
    #[cfg(feature = "dandelion")]
    pub fn initialize_dandelion_path(&mut self, peer_id: String, available_peers: &[String]) {
        if let Some(ref mut dandelion) = self.dandelion {
            dandelion.initialize_stem_path(peer_id, available_peers);
        }
    }
    #[cfg(not(feature = "dandelion"))]
    pub fn initialize_dandelion_path(&mut self, _peer_id: String, _available_peers: &[String]) {}

    /// Clean up expired Dandelion paths
    #[cfg(feature = "dandelion")]
    pub fn cleanup_dandelion(&mut self) {
        if let Some(ref mut dandelion) = self.dandelion {
            dandelion.cleanup_expired();
        }
    }
    #[cfg(not(feature = "dandelion"))]
    pub fn cleanup_dandelion(&mut self) {}

    /// Get relay statistics
    pub fn get_stats(&self) -> RelayStats {
        RelayStats {
            relayed_blocks: self.recently_relayed_blocks.len(),
            relayed_transactions: self.recently_relayed_txs.len(),
            policies: self.policies.clone(),
        }
    }

    /// Clean up old relayed items
    fn cleanup_old_items(&mut self) {
        let now = current_timestamp();

        // Clean up old blocks
        let old_blocks: Vec<Hash> = self
            .recently_relayed_blocks
            .iter()
            .filter(|&(_, timestamp)| {
                relay_entry_expired(now, *timestamp, self.policies.max_relay_age)
            })
            .map(|(hash, _)| *hash)
            .collect();

        for hash in old_blocks {
            self.recently_relayed_blocks.remove(&hash);
        }

        // Clean up old transactions
        let old_txs: Vec<Hash> = self
            .recently_relayed_txs
            .iter()
            .filter(|&(_, timestamp)| {
                relay_entry_expired(now, *timestamp, self.policies.max_relay_age)
            })
            .map(|(hash, _)| *hash)
            .collect();

        for hash in old_txs {
            self.recently_relayed_txs.remove(&hash);
        }

        // Limit total items
        if self.recently_relayed_blocks.len() > self.policies.max_tracked_items {
            let excess = self.recently_relayed_blocks.len() - self.policies.max_tracked_items;
            let oldest_blocks: Vec<Hash> = self
                .recently_relayed_blocks
                .iter()
                .min_by_key(|&(_, timestamp)| timestamp)
                .map(|(hash, _)| *hash)
                .into_iter()
                .take(excess)
                .collect();

            for hash in oldest_blocks {
                self.recently_relayed_blocks.remove(&hash);
            }
        }

        if self.recently_relayed_txs.len() > self.policies.max_tracked_items {
            let excess = self.recently_relayed_txs.len() - self.policies.max_tracked_items;
            let oldest_txs: Vec<Hash> = self
                .recently_relayed_txs
                .iter()
                .min_by_key(|&(_, timestamp)| timestamp)
                .map(|(hash, _)| *hash)
                .into_iter()
                .take(excess)
                .collect();

            for hash in oldest_txs {
                self.recently_relayed_txs.remove(&hash);
            }
        }
    }
}

fn relay_entry_expired(now: u64, timestamp: u64, max_relay_age: u64) -> bool {
    now.saturating_sub(timestamp) > max_relay_age
}

/// Relay statistics
#[derive(Debug, Clone)]
pub struct RelayStats {
    pub relayed_blocks: usize,
    pub relayed_transactions: usize,
    pub policies: RelayPolicies,
}

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

    #[test]
    fn future_relay_timestamp_is_kept() {
        let mut relay = RelayManager::new();
        let now = current_timestamp();
        let future = [1u8; 32];
        let expired = [2u8; 32];
        relay
            .recently_relayed_txs
            .insert(future, now.saturating_add(3_600));
        relay.recently_relayed_txs.insert(
            expired,
            now.saturating_sub(relay.policies.max_relay_age + 1),
        );
        relay.cleanup_old_items();
        assert!(relay.recently_relayed_txs.contains_key(&future));
        assert!(!relay.recently_relayed_txs.contains_key(&expired));
    }
}