nomad-protocol 0.2.0

NOMAD Protocol - Network-Optimized Mobile Application Datagram. A secure UDP-based state synchronization protocol.
Documentation
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
//! Connection state management for NOMAD transport layer.
//!
//! Implements the connection state machine from 2-TRANSPORT.md.

use std::net::SocketAddr;
use std::time::Instant;

use super::frame::SessionId;
use super::migration::MigrationState;
use super::pacing::{FramePacer, RetransmitController};
use super::timing::{RttEstimator, TimestampTracker};

/// Connection lifecycle state.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConnectionPhase {
    /// Handshake in progress.
    Handshaking,
    /// Connection established, data transfer active.
    Established,
    /// Connection closing gracefully.
    Closing,
    /// Connection closed.
    Closed,
    /// Connection failed (timeout, too many retransmits, etc).
    Failed,
}

/// Anti-replay window using a bitfield.
///
/// Tracks received nonces to detect and reject replayed frames.
/// Uses a sliding window of 2048+ bits as recommended by the spec.
#[derive(Debug, Clone)]
pub struct NonceWindow {
    /// The highest nonce we've seen.
    highest: u64,
    /// Bitfield for nonces below highest (bit i = highest - 1 - i).
    /// We track 2048 nonces below the highest.
    window: [u64; 32], // 32 * 64 = 2048 bits
}

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

impl NonceWindow {
    /// Window size in bits.
    pub const WINDOW_SIZE: usize = 2048;

    /// Create a new nonce window.
    pub fn new() -> Self {
        Self {
            highest: 0,
            window: [0; 32],
        }
    }

    /// Check if a nonce is valid (not replayed) and mark it as seen.
    ///
    /// Returns `true` if the nonce is valid and should be accepted,
    /// `false` if it's a replay or too old.
    pub fn check_and_mark(&mut self, nonce: u64) -> bool {
        // First nonce ever
        if self.highest == 0 && nonce > 0 {
            self.highest = nonce;
            return true;
        }

        if nonce > self.highest {
            // New highest nonce - shift window
            let shift = (nonce - self.highest) as usize;
            self.shift_window(shift);
            self.highest = nonce;
            true
        } else if nonce == self.highest {
            // Duplicate of the highest
            false
        } else {
            // Nonce below highest - check window
            let offset = (self.highest - nonce) as usize;
            if offset > Self::WINDOW_SIZE {
                // Too old, outside our window
                return false;
            }

            let offset = offset - 1; // Convert to 0-indexed
            let word_idx = offset / 64;
            let bit_idx = offset % 64;
            let mask = 1u64 << bit_idx;

            if self.window[word_idx] & mask != 0 {
                // Already seen
                false
            } else {
                // Mark as seen
                self.window[word_idx] |= mask;
                true
            }
        }
    }

    /// Shift the window by the given amount.
    fn shift_window(&mut self, shift: usize) {
        if shift >= Self::WINDOW_SIZE {
            // Complete reset
            self.window = [0; 32];
            return;
        }

        let word_shift = shift / 64;
        let bit_shift = shift % 64;

        if word_shift > 0 {
            // Shift words
            for i in (word_shift..32).rev() {
                self.window[i] = self.window[i - word_shift];
            }
            for i in 0..word_shift {
                self.window[i] = 0;
            }
        }

        if bit_shift > 0 {
            // Shift bits within words
            let mut carry = 0u64;
            for i in (0..32).rev() {
                let new_carry = self.window[i] << (64 - bit_shift);
                self.window[i] = (self.window[i] >> bit_shift) | carry;
                carry = new_carry;
            }
        }

        // Mark the old highest as seen (it's now at offset 'shift - 1')
        if shift > 0 {
            let offset = shift - 1;
            if offset < Self::WINDOW_SIZE {
                let word_idx = offset / 64;
                let bit_idx = offset % 64;
                self.window[word_idx] |= 1u64 << bit_idx;
            }
        }
    }
}

/// Full connection state as specified in 2-TRANSPORT.md.
#[derive(Debug)]
pub struct ConnectionState {
    /// Session identifier from handshake.
    pub session_id: SessionId,
    /// Current connection phase.
    pub phase: ConnectionPhase,
    /// Remote peer address (may change during migration).
    pub remote_endpoint: SocketAddr,
    /// When we last received an authenticated frame.
    pub last_received: Instant,
    /// Current epoch (increments on rekey).
    pub epoch: u32,

    /// Outbound nonce counter (monotonically increasing).
    pub send_nonce: u64,
    /// Inbound anti-replay window.
    pub recv_nonce_window: NonceWindow,

    /// RTT estimation.
    pub rtt: RttEstimator,
    /// Timestamp tracking for RTT measurement.
    pub timestamps: TimestampTracker,
    /// Frame pacing.
    pub pacer: FramePacer,
    /// Retransmission control.
    pub retransmit: RetransmitController,
    /// Migration state.
    pub migration: MigrationState,

    /// Highest state version we've sent.
    pub local_state_version: u64,
    /// Highest state version we've acknowledged from peer.
    pub remote_state_version: u64,
    /// Highest state version the peer has acknowledged from us.
    pub acked_state_version: u64,
}

impl ConnectionState {
    /// Create a new connection state for an established session.
    pub fn new(session_id: SessionId, remote_endpoint: SocketAddr) -> Self {
        let now = Instant::now();
        Self {
            session_id,
            phase: ConnectionPhase::Established,
            remote_endpoint,
            last_received: now,
            epoch: 0,

            send_nonce: 0,
            recv_nonce_window: NonceWindow::new(),

            rtt: RttEstimator::new(),
            timestamps: TimestampTracker::new(),
            pacer: FramePacer::new(),
            retransmit: RetransmitController::new(super::timing::constants::INITIAL_RTO),
            migration: MigrationState::new(remote_endpoint),

            local_state_version: 0,
            remote_state_version: 0,
            acked_state_version: 0,
        }
    }

    /// Create a connection state in handshaking phase.
    pub fn handshaking(remote_endpoint: SocketAddr) -> Self {
        let now = Instant::now();
        Self {
            session_id: SessionId::zero(),
            phase: ConnectionPhase::Handshaking,
            remote_endpoint,
            last_received: now,
            epoch: 0,

            send_nonce: 0,
            recv_nonce_window: NonceWindow::new(),

            rtt: RttEstimator::new(),
            timestamps: TimestampTracker::new(),
            pacer: FramePacer::new(),
            retransmit: RetransmitController::new(super::timing::constants::INITIAL_RTO),
            migration: MigrationState::new(remote_endpoint),

            local_state_version: 0,
            remote_state_version: 0,
            acked_state_version: 0,
        }
    }

    /// Get the next nonce for sending and increment the counter.
    pub fn next_send_nonce(&mut self) -> u64 {
        let nonce = self.send_nonce;
        self.send_nonce = self.send_nonce.saturating_add(1);
        nonce
    }

    /// Check if a received nonce is valid (not replayed).
    pub fn check_recv_nonce(&mut self, nonce: u64) -> bool {
        self.recv_nonce_window.check_and_mark(nonce)
    }

    /// Update state after receiving an authenticated frame.
    pub fn on_authenticated_frame(&mut self, from: SocketAddr) {
        self.last_received = Instant::now();

        // Handle potential migration
        if from != self.remote_endpoint && self.migration.validate_address(from) {
            self.remote_endpoint = from;
        }
    }

    /// Check if the connection is still alive.
    pub fn is_alive(&self) -> bool {
        !self.pacer.is_connection_dead(self.last_received) && !self.retransmit.is_failed()
    }

    /// Check if the connection has failed.
    pub fn is_failed(&self) -> bool {
        self.phase == ConnectionPhase::Failed
            || self.pacer.is_connection_dead(self.last_received)
            || self.retransmit.is_failed()
    }

    /// Check if there's unacknowledged data.
    pub fn has_unacked_data(&self) -> bool {
        self.local_state_version > self.acked_state_version
    }

    /// Update the acked state version.
    pub fn on_ack(&mut self, acked_version: u64) {
        if acked_version > self.acked_state_version {
            self.acked_state_version = acked_version;
            self.retransmit.on_ack();
        }
    }

    /// Transition to closed state.
    pub fn close(&mut self) {
        self.phase = ConnectionPhase::Closing;
    }

    /// Mark as fully closed.
    pub fn mark_closed(&mut self) {
        self.phase = ConnectionPhase::Closed;
    }

    /// Mark as failed.
    pub fn mark_failed(&mut self) {
        self.phase = ConnectionPhase::Failed;
    }

    /// Complete handshake and transition to established.
    pub fn complete_handshake(&mut self, session_id: SessionId) {
        self.session_id = session_id;
        self.phase = ConnectionPhase::Established;
        self.timestamps = TimestampTracker::new(); // Reset timestamps
    }

    /// Increment epoch (on rekey).
    pub fn on_rekey(&mut self) {
        self.epoch = self.epoch.saturating_add(1);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::net::{IpAddr, Ipv4Addr};

    fn test_addr(port: u16) -> SocketAddr {
        SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), port)
    }

    #[test]
    fn test_nonce_window_new() {
        let mut window = NonceWindow::new();

        // First nonce should be accepted
        assert!(window.check_and_mark(1));

        // Same nonce should be rejected
        assert!(!window.check_and_mark(1));

        // Next nonce should be accepted
        assert!(window.check_and_mark(2));
    }

    #[test]
    fn test_nonce_window_gap() {
        let mut window = NonceWindow::new();

        // Accept nonce 1
        assert!(window.check_and_mark(1));

        // Skip to nonce 100
        assert!(window.check_and_mark(100));

        // Nonces in between should still be valid (not seen)
        assert!(window.check_and_mark(50));
        assert!(window.check_and_mark(75));

        // But duplicates should be rejected
        assert!(!window.check_and_mark(50));
        assert!(!window.check_and_mark(100));
    }

    #[test]
    fn test_nonce_window_too_old() {
        let mut window = NonceWindow::new();

        // Accept high nonce
        assert!(window.check_and_mark(3000));

        // Very old nonce should be rejected (outside window)
        assert!(!window.check_and_mark(1));
        assert!(!window.check_and_mark(500)); // 3000 - 500 = 2500 > 2048
    }

    #[test]
    fn test_connection_state_nonces() {
        let mut conn = ConnectionState::new(SessionId::zero(), test_addr(8080));

        // Get sequential nonces
        assert_eq!(conn.next_send_nonce(), 0);
        assert_eq!(conn.next_send_nonce(), 1);
        assert_eq!(conn.next_send_nonce(), 2);

        // Verify nonce counter
        assert_eq!(conn.send_nonce, 3);
    }

    #[test]
    fn test_connection_state_lifecycle() {
        let addr = test_addr(8080);
        let mut conn = ConnectionState::handshaking(addr);

        assert_eq!(conn.phase, ConnectionPhase::Handshaking);

        // Complete handshake
        let session_id = SessionId::from_bytes([1, 2, 3, 4, 5, 6]);
        conn.complete_handshake(session_id);
        assert_eq!(conn.phase, ConnectionPhase::Established);
        assert_eq!(conn.session_id, session_id);

        // Close
        conn.close();
        assert_eq!(conn.phase, ConnectionPhase::Closing);

        conn.mark_closed();
        assert_eq!(conn.phase, ConnectionPhase::Closed);
    }

    #[test]
    fn test_connection_state_ack() {
        let mut conn = ConnectionState::new(SessionId::zero(), test_addr(8080));

        conn.local_state_version = 10;
        assert!(conn.has_unacked_data());

        conn.on_ack(5);
        assert_eq!(conn.acked_state_version, 5);
        assert!(conn.has_unacked_data());

        conn.on_ack(10);
        assert_eq!(conn.acked_state_version, 10);
        assert!(!conn.has_unacked_data());
    }

    #[test]
    fn test_connection_alive_check() {
        let conn = ConnectionState::new(SessionId::zero(), test_addr(8080));
        assert!(conn.is_alive());
        assert!(!conn.is_failed());
    }
}