typhoon-protocol 0.1.0

A sample implementation of TYPHOON 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
use std::sync::LazyLock;

use crate::bytes::{ByteBuffer, BytePool};
use crate::flow::config::{FakeBodyMode, FakeHeaderConfig, FieldType, FieldTypeHolder, FlowConfig};
use crate::utils::unix_timestamp_ms;

static TEST_POOL: LazyLock<BytePool> = LazyLock::new(|| BytePool::new(32, 256, 32, 4, 16));

// === FakeBodyMode tests ===

// Test: Empty mode always returns 0 regardless of parameters.
#[test]
fn test_fake_body_empty_returns_zero() {
    let mode = FakeBodyMode::Empty;
    assert_eq!(mode.get_length(1500, 100, false), 0);
    assert_eq!(mode.get_length(1500, 100, true), 0);
    assert_eq!(mode.get_length(0, 0, false), 0);
}

// Test: Constant mode returns packet_length minus taken, clamped to max_packet_size.
#[test]
fn test_fake_body_constant_basic() {
    let mode = FakeBodyMode::Constant {
        packet_length: 500,
    };
    // min(1500, 500) - 100 = 400
    assert_eq!(mode.get_length(1500, 100, false), 400);
    assert_eq!(mode.get_length(1500, 100, true), 400);
}

// Test: Constant mode when taken equals packet_length returns 0.
#[test]
fn test_fake_body_constant_exact_fit() {
    let mode = FakeBodyMode::Constant {
        packet_length: 100,
    };
    assert_eq!(mode.get_length(1500, 100, false), 0);
}

// Test: Constant mode returns 0 when taken exceeds packet_length.
#[test]
fn test_fake_body_constant_returns_zero_when_taken_exceeds() {
    let mode = FakeBodyMode::Constant {
        packet_length: 50,
    };
    assert_eq!(mode.get_length(1500, 100, false), 0);
}

// Test: Random mode with service=true returns 0 for non-service packets.
#[test]
fn test_fake_body_random_service_only_skips_non_service() {
    let mode = FakeBodyMode::Random {
        min_length: 10,
        max_length: 200,
        service: true,
    };
    assert_eq!(mode.get_length(1500, 100, false), 0, "service-only mode should skip non-service packets");
}

// Test: Random mode with service=false pads within [min, min(max, body_space)) range.
#[test]
fn test_fake_body_random_non_service_pads() {
    let mode = FakeBodyMode::Random {
        min_length: 10,
        max_length: 200,
        service: false,
    };
    for _ in 0..20 {
        let len = mode.get_length(1500, 100, false);
        assert!((10..200).contains(&len), "length {len} should be in [10, 200)");
    }
}

// Test: Random mode with service=true pads service packets.
#[test]
fn test_fake_body_random_service_only_pads_service() {
    let mode = FakeBodyMode::Random {
        min_length: 10,
        max_length: 200,
        service: true,
    };
    for _ in 0..20 {
        let len = mode.get_length(1500, 100, true);
        assert!((10..200).contains(&len), "length {len} should be in [10, 200)");
    }
}

// Test: Random mode returns effective_max when body_space is too small for the range.
#[test]
fn test_fake_body_random_tight_space() {
    let mode = FakeBodyMode::Random {
        min_length: 50,
        max_length: 200,
        service: false,
    };
    // body_space = 60 - 50 = 10. effective_max = min(200, 10) = 10 <= min_length=50, returns 10.
    let len = mode.get_length(60, 50, false);
    assert_eq!(len, 10, "should return effective_max when space is tight");
}

// === FieldType tests ===

// Test: Constant field always returns the same value.
#[test]
fn test_field_type_constant() {
    let mut field: FieldType<u32> = FieldType::Constant {
        value: 42,
    };
    for _ in 0..10 {
        assert_eq!(field.apply(), 42);
    }
}

// Test: Incremental field increments by 1 each call.
#[test]
fn test_field_type_incremental() {
    let mut field: FieldType<u16> = FieldType::Incremental {
        value: 0,
    };
    assert_eq!(field.apply(), 1);
    assert_eq!(field.apply(), 2);
    assert_eq!(field.apply(), 3);
}

// Test: Incremental field starts from given initial value.
#[test]
fn test_field_type_incremental_from_offset() {
    let mut field: FieldType<u8> = FieldType::Incremental {
        value: 250,
    };
    assert_eq!(field.apply(), 251);
    assert_eq!(field.apply(), 252);
}

// Test: Random field produces values without panicking.
#[test]
fn test_field_type_random_runs() {
    let mut field: FieldType<u64> = FieldType::Random;
    for _ in 0..20 {
        let _ = field.apply();
    }
}

// Test: Volatile field with change_probability > 1.0 never changes (condition: rng > prob is never true).
#[test]
fn test_field_type_volatile_never_changes() {
    let mut field: FieldType<u32> = FieldType::Volatile {
        value: 99,
        change_probability: 2.0,
    };
    for _ in 0..50 {
        assert_eq!(field.apply(), 99);
    }
}

// Test: Switching field returns current value when switch time hasn't passed.
#[test]
fn test_field_type_switching_before_timeout() {
    let far_future = unix_timestamp_ms() + 1_000_000;
    let mut field: FieldType<u32> = FieldType::Switching {
        value: 7,
        next_switch: far_future,
        switch_timeout: 60_000,
    };
    assert_eq!(field.apply(), 7, "should return current value before timeout");
}

// Test: Switching field switches value after timeout.
#[test]
fn test_field_type_switching_after_timeout() {
    let mut field: FieldType<u32> = FieldType::Switching {
        value: 7,
        next_switch: 0, // Already in the past
        switch_timeout: 60_000,
    };
    // After timeout, value is regenerated - just verify it doesn't panic.
    let _ = field.apply();
}

// === FakeHeaderConfig tests ===

// Test: len() correctly sums field sizes.
#[test]
fn test_fake_header_config_len() {
    let config = FakeHeaderConfig {
        pattern: vec![
            FieldTypeHolder::U8(FieldType::Constant {
                value: 0,
            }),
            FieldTypeHolder::U16(FieldType::Constant {
                value: 0,
            }),
            FieldTypeHolder::U32(FieldType::Constant {
                value: 0,
            }),
            FieldTypeHolder::U64(FieldType::Constant {
                value: 0,
            }),
        ],
    };
    assert_eq!(config.len(), 1 + 2 + 4 + 8, "total header length should be 15 bytes");
}

// Test: len() with empty pattern returns 0.
#[test]
fn test_fake_header_config_len_empty() {
    let config = FakeHeaderConfig {
        pattern: vec![],
    };
    assert_eq!(config.is_empty(), true, "empty pattern should be considered empty");
}

// Test: fill() writes constant values into buffer correctly.
#[test]
fn test_fake_header_config_fill_constants() {
    let mut config = FakeHeaderConfig {
        pattern: vec![
            FieldTypeHolder::U8(FieldType::Constant {
                value: 0xAB,
            }),
            FieldTypeHolder::U16(FieldType::Constant {
                value: 0x1234,
            }),
            FieldTypeHolder::U32(FieldType::Constant {
                value: 0xDEAD_BEEF,
            }),
        ],
    };

    let total_len = config.len(); // 1 + 2 + 4 = 7
    let buffer = TEST_POOL.allocate(Some(total_len));

    config.fill(buffer.clone());

    let data = buffer.slice();
    assert_eq!(data[0], 0xAB, "u8 field should be written at offset 0");
    assert_eq!(&data[1..3], &0x1234u16.to_be_bytes(), "u16 field should be big-endian at offset 1");
    assert_eq!(&data[3..7], &0xDEAD_BEEFu32.to_be_bytes(), "u32 field should be big-endian at offset 3");
}

// Test: fill() with incremental field writes incrementing values across calls.
#[test]
fn test_fake_header_config_fill_incremental() {
    let mut config = FakeHeaderConfig {
        pattern: vec![FieldTypeHolder::U8(FieldType::Incremental {
            value: 0,
        })],
    };

    let buffer = TEST_POOL.allocate(Some(1));

    config.fill(buffer.clone());
    assert_eq!(buffer.slice()[0], 1);

    config.fill(buffer.clone());
    assert_eq!(buffer.slice()[0], 2);
}

// === FlowConfig assertion tests ===

// Test: valid FlowConfig with Empty body passes assertion.
#[test]
fn test_flow_config_assert_empty_body_ok() {
    let config = FlowConfig::new(FakeBodyMode::Empty, FakeHeaderConfig::new(vec![]));
    assert!(config.assert(1500).is_ok());
}

// Test: valid FlowConfig with Constant body passes assertion.
#[test]
fn test_flow_config_assert_constant_body_ok() {
    let config = FlowConfig::new(
        FakeBodyMode::Constant {
            packet_length: 1000,
        },
        FakeHeaderConfig::new(vec![]),
    );
    assert!(config.assert(1500).is_ok());
}

// Test: Constant body packet_length exceeding max_packet_size fails assertion.
#[test]
fn test_flow_config_assert_constant_body_exceeds_max() {
    let config = FlowConfig::new(
        FakeBodyMode::Constant {
            packet_length: 2000,
        },
        FakeHeaderConfig::new(vec![]),
    );
    assert!(config.assert(1500).is_err());
}

// Test: valid Random body passes assertion.
#[test]
fn test_flow_config_assert_random_body_ok() {
    let config = FlowConfig::new(
        FakeBodyMode::Random {
            min_length: 10,
            max_length: 200,
            service: false,
        },
        FakeHeaderConfig::new(vec![]),
    );
    assert!(config.assert(1500).is_ok());
}

// Test: Random body min_length > max_length fails assertion.
#[test]
fn test_flow_config_assert_random_body_min_exceeds_max() {
    let config = FlowConfig::new(
        FakeBodyMode::Random {
            min_length: 300,
            max_length: 100,
            service: false,
        },
        FakeHeaderConfig::new(vec![]),
    );
    assert!(config.assert(1500).is_err());
}

// Test: fake header length exceeding max_packet_size fails assertion.
#[test]
fn test_flow_config_assert_header_exceeds_max() {
    let large_pattern: Vec<FieldTypeHolder> = (0..200)
        .map(|_| {
            FieldTypeHolder::U64(FieldType::Constant {
                value: 0,
            })
        })
        .collect();
    let config = FlowConfig::new(FakeBodyMode::Empty, FakeHeaderConfig::new(large_pattern));
    // 200 * 8 = 1600 > 1500
    assert!(config.assert(1500).is_err());
}

// Test: Constant body packet_length exactly at max_packet_size passes assertion.
#[test]
fn test_flow_config_assert_constant_body_at_max() {
    let config = FlowConfig::new(
        FakeBodyMode::Constant {
            packet_length: 1500,
        },
        FakeHeaderConfig::new(vec![]),
    );
    assert!(config.assert(1500).is_ok());
}

// Test: Random body with min_length == max_length passes assertion.
#[test]
fn test_flow_config_assert_random_body_equal_bounds() {
    let config = FlowConfig::new(
        FakeBodyMode::Random {
            min_length: 100,
            max_length: 100,
            service: false,
        },
        FakeHeaderConfig::new(vec![]),
    );
    assert!(config.assert(1500).is_ok());
}

// Test: after the first switch triggers, the field must NOT switch again on the very next call.
// Regression for: `*next_switch = *switch_timeout` instead of `unix_timestamp_ms() + switch_timeout`,
// which set next_switch far in the past, causing a switch on every subsequent apply().
#[test]
fn test_field_type_switching_no_thrash_after_first_switch() {
    let switch_timeout_ms: u64 = 500;
    // Set next_switch in the past so the first apply() triggers a switch.
    let mut field: FieldType<u8> = FieldType::Switching {
        value: 0u8,
        next_switch: unix_timestamp_ms() - 1,
        switch_timeout: switch_timeout_ms,
    };

    // First apply: timer has expired → switch fires, next_switch reset to now + timeout.
    let first = field.apply();
    // Second apply immediately: timer should NOT have expired yet.
    let second = field.apply();

    assert_eq!(first, second, "field switched twice within a single millisecond — next_switch reset is broken");
}

// Test: after the timeout elapses the field switches again (positive case).
#[test]
fn test_field_type_switching_switches_again_after_timeout() {
    let switch_timeout_ms: u64 = 50; // 50 ms — short enough for a test
    let mut field: FieldType<u8> = FieldType::Switching {
        value: 0u8,
        next_switch: unix_timestamp_ms() - 1,
        switch_timeout: switch_timeout_ms,
    };

    // First apply fires the switch, next_switch now = now + 50ms.
    let _ = field.apply();

    // Wait past the timeout.
    std::thread::sleep(std::time::Duration::from_millis(switch_timeout_ms + 10));

    // A switch can now occur — call apply() once (may or may not switch depending on rng).
    let _after = field.apply();
    // Immediately applying again must NOT switch a second time in the same call.
    let immediate = field.apply();
    let immediate2 = field.apply();
    assert_eq!(immediate, immediate2, "double switch within 1ms — timer reset broken after second trigger");
}