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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
|
//! Integration tests: multi-node scenarios over real
//! UDP sockets on loopback.
use std::time::Duration;
use tesseras_dht::Node;
use tesseras_dht::nat::NatState;
/// Poll all nodes once each (non-blocking best-effort).
fn poll_all(nodes: &mut [Node], rounds: usize) {
let fast = Duration::from_millis(1);
for _ in 0..rounds {
for n in nodes.iter_mut() {
n.poll_timeout(fast).ok();
}
}
}
/// Create N nodes, join them to the first.
fn make_network(n: usize) -> Vec<Node> {
let mut nodes = Vec::with_capacity(n);
let bootstrap = Node::bind(0).unwrap();
let bp = bootstrap.local_addr().unwrap().port();
nodes.push(bootstrap);
nodes[0].set_nat_state(NatState::Global);
for _ in 1..n {
let mut node = Node::bind(0).unwrap();
node.set_nat_state(NatState::Global);
node.join("127.0.0.1", bp).unwrap();
nodes.push(node);
}
// Small sleep to let packets arrive, then poll
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
nodes
}
// ── Bootstrap tests ─────────────────────────────────
#[test]
fn two_nodes_discover_each_other() {
let nodes = make_network(2);
assert!(
nodes[0].routing_table_size() >= 1,
"Node 0 should have at least 1 peer in routing table"
);
assert!(
nodes[1].routing_table_size() >= 1,
"Node 1 should have at least 1 peer in routing table"
);
}
#[test]
fn three_nodes_form_network() {
let nodes = make_network(3);
// All nodes should know at least 1 other node
for (i, node) in nodes.iter().enumerate() {
assert!(
node.routing_table_size() >= 1,
"Node {i} routing table empty"
);
}
}
#[test]
fn five_nodes_routing_tables() {
let nodes = make_network(5);
// With 5 nodes, most should know 2+ peers
let total_peers: usize = nodes.iter().map(|n| n.routing_table_size()).sum();
assert!(
total_peers >= 5,
"Total routing entries ({total_peers}) too low"
);
}
// ── Put/Get tests ───────────────────────────────────
#[test]
fn put_get_local() {
let mut node = Node::bind(0).unwrap();
node.put(b"key1", b"value1", 300, false);
let vals = node.get(b"key1");
assert_eq!(vals.len(), 1);
assert_eq!(vals[0], b"value1");
}
#[test]
fn put_get_across_two_nodes() {
let mut nodes = make_network(2);
// Node 0 stores
nodes[0].put(b"hello", b"world", 300, false);
// Poll to deliver STORE
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
// Node 1 should have the value (received via STORE)
let vals = nodes[1].get(b"hello");
assert_eq!(vals.len(), 1, "Node 1 should have received the value");
assert_eq!(vals[0], b"world");
}
#[test]
fn put_multiple_values() {
let mut nodes = make_network(3);
// Store 10 key-value pairs from node 0
for i in 0..10u32 {
let key = format!("k{i}");
let val = format!("v{i}");
nodes[0].put(key.as_bytes(), val.as_bytes(), 300, false);
}
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
// Node 0 should have all 10
let mut found = 0;
for i in 0..10u32 {
let key = format!("k{i}");
if !nodes[0].get(key.as_bytes()).is_empty() {
found += 1;
}
}
assert_eq!(found, 10, "Node 0 should have all 10 values");
}
#[test]
fn put_unique_replaces() {
let mut node = Node::bind(0).unwrap();
node.put(b"uk", b"first", 300, true);
node.put(b"uk", b"second", 300, true);
let vals = node.get(b"uk");
assert_eq!(vals.len(), 1);
assert_eq!(vals[0], b"second");
}
#[test]
fn put_get_distributed() {
let mut nodes = make_network(5);
// Each node stores one value
for i in 0..5u32 {
let key = format!("node{i}-key");
let val = format!("node{i}-val");
nodes[i as usize].put(key.as_bytes(), val.as_bytes(), 300, false);
}
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
// Each node should have its own value at minimum
for i in 0..5u32 {
let key = format!("node{i}-key");
let vals = nodes[i as usize].get(key.as_bytes());
assert!(!vals.is_empty(), "Node {i} should have its own value");
}
}
// ── Identity tests ──────────────────────────────────
#[test]
fn set_id_deterministic() {
let mut n1 = Node::bind(0).unwrap();
let mut n2 = Node::bind(0).unwrap();
n1.set_id(b"same-seed");
n2.set_id(b"same-seed");
assert_eq!(n1.id(), n2.id());
}
#[test]
fn node_id_is_unique() {
let n1 = Node::bind(0).unwrap();
let n2 = Node::bind(0).unwrap();
assert_ne!(n1.id(), n2.id());
}
// ── NAT state tests ────────────────────────────────
#[test]
fn nat_state_transitions() {
let mut node = Node::bind(0).unwrap();
assert_eq!(node.nat_state(), NatState::Unknown);
node.set_nat_state(NatState::Global);
assert_eq!(node.nat_state(), NatState::Global);
node.set_nat_state(NatState::ConeNat);
assert_eq!(node.nat_state(), NatState::ConeNat);
node.set_nat_state(NatState::SymmetricNat);
assert_eq!(node.nat_state(), NatState::SymmetricNat);
}
// ── RDP tests ───────────────────────────────────────
#[test]
fn rdp_listen_connect_close() {
let mut node = Node::bind(0).unwrap();
let desc = node.rdp_listen(5000).unwrap();
node.rdp_close(desc);
// Should be able to re-listen
let desc2 = node.rdp_listen(5000).unwrap();
node.rdp_close(desc2);
}
#[test]
fn rdp_connect_state() {
use tesseras_dht::rdp::RdpState;
let mut node = Node::bind(0).unwrap();
let dst = tesseras_dht::NodeId::from_bytes([0x01; 32]);
let desc = node.rdp_connect(0, &dst, 5000).unwrap();
assert_eq!(node.rdp_state(desc).unwrap(), RdpState::SynSent);
node.rdp_close(desc);
}
// ── Resilience tests ────────────────────────────────
#[test]
fn poll_with_no_peers() {
let mut node = Node::bind(0).unwrap();
// Should not panic or block
node.poll().unwrap();
}
#[test]
fn join_invalid_address() {
let mut node = Node::bind(0).unwrap();
let result = node.join("this-does-not-exist.invalid", 9999);
assert!(result.is_err());
}
#[test]
fn empty_get() {
let mut node = Node::bind(0).unwrap();
assert!(node.get(b"nonexistent").is_empty());
}
#[test]
fn put_zero_ttl_removes() {
let mut node = Node::bind(0).unwrap();
node.put(b"temp", b"data", 300, false);
assert!(!node.get(b"temp").is_empty());
// Store with TTL 0 is a delete in the protocol
// (handled at the wire level in handle_dht_store,
// but locally we'd need to call storage.remove).
// This test validates the local storage.
}
// ── Scale test ──────────────────────────────────────
#[test]
fn ten_nodes_put_get() {
let mut nodes = make_network(10);
// Node 0 stores
nodes[0].put(b"scale-key", b"scale-val", 300, false);
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
// Count how many nodes received the value
let mut count = 0;
for node in &mut nodes {
if !node.get(b"scale-key").is_empty() {
count += 1;
}
}
assert!(
count >= 2,
"At least 2 nodes should have the value, got {count}"
);
}
// ── Remote get via FIND_VALUE ───────────────────────
#[test]
fn remote_get_via_find_value() {
let mut nodes = make_network(3);
// Node 0 stores locally
nodes[0].put(b"remote-key", b"remote-val", 300, false);
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
// Node 2 does remote get
let before = nodes[2].get(b"remote-key");
// Might already have it from STORE, or empty
if before.is_empty() {
// Poll to let FIND_VALUE propagate
std::thread::sleep(Duration::from_millis(100));
poll_all(&mut nodes, 10);
let after = nodes[2].get(b"remote-key");
assert!(
!after.is_empty(),
"Node 2 should find the value via FIND_VALUE"
);
assert_eq!(after[0], b"remote-val");
}
}
// ── NAT detection tests ────────────────────────────
#[test]
fn nat_state_default_unknown() {
let node = Node::bind(0).unwrap();
assert_eq!(node.nat_state(), NatState::Unknown);
}
#[test]
fn nat_state_set_persists() {
let mut node = Node::bind(0).unwrap();
node.set_nat_state(NatState::SymmetricNat);
assert_eq!(node.nat_state(), NatState::SymmetricNat);
node.poll().unwrap();
assert_eq!(node.nat_state(), NatState::SymmetricNat);
}
// ── DTUN tests ──────────────────────────────────────
#[test]
fn dtun_find_node_exchange() {
// Two nodes: node2 sends DtunFindNode to node1
// by joining. The DTUN table should be populated.
let nodes = make_network(2);
// Both nodes should have peers after join
assert!(nodes[0].routing_table_size() >= 1);
assert!(nodes[1].routing_table_size() >= 1);
}
// ── Proxy tests ─────────────────────────────────────
#[test]
fn proxy_dgram_forwarded() {
use std::sync::{Arc, Mutex};
let mut nodes = make_network(2);
let received: Arc<Mutex<Vec<Vec<u8>>>> = Arc::new(Mutex::new(Vec::new()));
let recv_clone = received.clone();
nodes[1].set_dgram_callback(move |data, _from| {
recv_clone.lock().unwrap().push(data.to_vec());
});
// Node 0 sends dgram to Node 1
let id1 = *nodes[1].id();
nodes[0].send_dgram(b"proxy-test", &id1);
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
let msgs = received.lock().unwrap();
assert!(!msgs.is_empty(), "Node 1 should receive the dgram");
assert_eq!(msgs[0], b"proxy-test");
}
// ── Advertise tests ─────────────────────────────────
#[test]
fn nodes_peer_count_after_join() {
let nodes = make_network(3);
// All nodes should have at least 1 peer
for (i, node) in nodes.iter().enumerate() {
assert!(
node.peer_count() >= 1,
"Node {i} should have at least 1 peer"
);
}
}
// ── Storage tests ───────────────────────────────────
#[test]
fn storage_count_after_put() {
let mut node = Node::bind(0).unwrap();
assert_eq!(node.storage_count(), 0);
node.put(b"k1", b"v1", 300, false);
node.put(b"k2", b"v2", 300, false);
assert_eq!(node.storage_count(), 2);
}
#[test]
fn put_from_multiple_nodes() {
let mut nodes = make_network(3);
nodes[0].put(b"from-0", b"val-0", 300, false);
nodes[1].put(b"from-1", b"val-1", 300, false);
nodes[2].put(b"from-2", b"val-2", 300, false);
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
// Each node should have its own value
assert!(!nodes[0].get(b"from-0").is_empty());
assert!(!nodes[1].get(b"from-1").is_empty());
assert!(!nodes[2].get(b"from-2").is_empty());
}
// ── Config tests ────────────────────────────────────
#[test]
fn config_default_works() {
let config = tesseras_dht::config::Config::default();
assert_eq!(config.num_find_node, 10);
assert_eq!(config.bucket_size, 20);
assert_eq!(config.default_ttl, 300);
}
#[test]
fn config_pastebin_preset() {
let config = tesseras_dht::config::Config::pastebin();
assert_eq!(config.default_ttl, 65535);
assert!(config.require_signatures);
}
// ── Metrics tests ───────────────────────────────────
#[test]
fn metrics_after_put() {
let mut nodes = make_network(2);
let before = nodes[0].metrics();
nodes[0].put(b"m-key", b"m-val", 300, false);
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
let after = nodes[0].metrics();
assert!(
after.messages_sent > before.messages_sent,
"messages_sent should increase after put"
);
}
#[test]
fn metrics_bytes_tracked() {
let mut node = Node::bind(0).unwrap();
let m = node.metrics();
assert_eq!(m.bytes_sent, 0);
assert_eq!(m.bytes_received, 0);
}
// ── Builder tests ───────────────────────────────────
#[test]
fn builder_basic() {
use tesseras_dht::node::NodeBuilder;
let node = NodeBuilder::new()
.port(0)
.nat(NatState::Global)
.build()
.unwrap();
assert_eq!(node.nat_state(), NatState::Global);
}
#[test]
fn builder_with_seed() {
use tesseras_dht::node::NodeBuilder;
let n1 = NodeBuilder::new()
.port(0)
.seed(b"same-seed")
.build()
.unwrap();
let n2 = NodeBuilder::new()
.port(0)
.seed(b"same-seed")
.build()
.unwrap();
assert_eq!(n1.id(), n2.id());
}
#[test]
fn builder_with_config() {
use tesseras_dht::node::NodeBuilder;
let config = tesseras_dht::config::Config::pastebin();
let node = NodeBuilder::new().port(0).config(config).build().unwrap();
assert!(node.config().require_signatures);
}
// ── Persistence mock test ───────────────────────────
#[test]
fn persistence_nop_save_load() {
let mut node = Node::bind(0).unwrap();
node.put(b"persist-key", b"persist-val", 300, false);
// With NoPersistence, save does nothing
node.save_state();
// load_persisted with NoPersistence loads nothing
node.load_persisted();
// Value still there from local storage
assert!(!node.get(b"persist-key").is_empty());
}
// ── Ban list tests ────────────────────────────────────
#[test]
fn ban_list_initially_empty() {
let node = Node::bind(0).unwrap();
assert_eq!(node.ban_count(), 0);
}
#[test]
fn ban_list_unit() {
use tesseras_dht::banlist::BanList;
let mut bl = BanList::new();
let addr: std::net::SocketAddr = "127.0.0.1:9999".parse().unwrap();
assert!(!bl.is_banned(&addr));
bl.record_failure(addr);
bl.record_failure(addr);
assert!(!bl.is_banned(&addr)); // 2 < threshold 3
bl.record_failure(addr);
assert!(bl.is_banned(&addr)); // 3 >= threshold
}
#[test]
fn ban_list_success_resets() {
use tesseras_dht::banlist::BanList;
let mut bl = BanList::new();
let addr: std::net::SocketAddr = "127.0.0.1:9999".parse().unwrap();
bl.record_failure(addr);
bl.record_failure(addr);
bl.record_success(&addr);
bl.record_failure(addr); // starts over from 1
assert!(!bl.is_banned(&addr));
}
// ── Store tracker tests ───────────────────────────────
#[test]
fn store_tracker_initially_empty() {
let node = Node::bind(0).unwrap();
assert_eq!(node.pending_stores(), 0);
assert_eq!(node.store_stats(), (0, 0));
}
#[test]
fn store_tracker_counts_after_put() {
let mut nodes = make_network(3);
nodes[0].put(b"tracked-key", b"tracked-val", 300, false);
std::thread::sleep(Duration::from_millis(50));
poll_all(&mut nodes, 5);
// Node 0 should have pending stores (sent to peers)
// or acks if peers responded quickly
let (acks, _) = nodes[0].store_stats();
let pending = nodes[0].pending_stores();
assert!(
acks > 0 || pending > 0,
"Should have tracked some stores (acks={acks}, pending={pending})"
);
}
// ── Node activity monitor tests ──────────────────────
#[test]
fn activity_check_does_not_crash() {
let mut node = Node::bind(0).unwrap();
node.set_nat_state(NatState::Global);
// Calling poll runs the activity check — should
// not crash even with no peers
node.poll().unwrap();
}
// ── Batch operations tests ───────────────────────────
#[test]
fn put_batch_stores_locally() {
let mut node = Node::bind(0).unwrap();
let entries: Vec<(&[u8], &[u8], u16, bool)> = vec![
(b"b1", b"v1", 300, false),
(b"b2", b"v2", 300, false),
(b"b3", b"v3", 300, false),
];
node.put_batch(&entries);
assert_eq!(node.storage_count(), 3);
assert_eq!(node.get(b"b1"), vec![b"v1".to_vec()]);
assert_eq!(node.get(b"b2"), vec![b"v2".to_vec()]);
assert_eq!(node.get(b"b3"), vec![b"v3".to_vec()]);
}
#[test]
fn get_batch_returns_local() {
let mut node = Node::bind(0).unwrap();
node.put(b"gb1", b"v1", 300, false);
node.put(b"gb2", b"v2", 300, false);
let results = node.get_batch(&[b"gb1", b"gb2", b"gb-missing"]);
assert_eq!(results.len(), 3);
assert_eq!(results[0].1, vec![b"v1".to_vec()]);
assert_eq!(results[1].1, vec![b"v2".to_vec()]);
assert!(results[2].1.is_empty()); // not found
}
#[test]
fn put_batch_distributes_to_peers() {
let mut nodes = make_network(3);
let entries: Vec<(&[u8], &[u8], u16, bool)> = vec![
(b"dist-1", b"val-1", 300, false),
(b"dist-2", b"val-2", 300, false),
(b"dist-3", b"val-3", 300, false),
(b"dist-4", b"val-4", 300, false),
(b"dist-5", b"val-5", 300, false),
];
nodes[0].put_batch(&entries);
std::thread::sleep(Duration::from_millis(100));
poll_all(&mut nodes, 10);
// All 5 values should be stored locally on node 0
for i in 1..=5 {
let key = format!("dist-{i}");
let vals = nodes[0].get(key.as_bytes());
assert!(!vals.is_empty(), "Node 0 should have {key}");
}
// At least some should be distributed to other nodes
let total: usize = nodes.iter().map(|n| n.storage_count()).sum();
assert!(total > 5, "Total stored {total} should be > 5 (replicated)");
}
// ── Proactive replication tests ──────────────────
#[test]
fn proactive_replicate_on_new_node() {
// Node 0 stores a value, then node 2 joins.
// After routing table sync, node 2 should receive
// the value proactively (§2.5).
let mut nodes = make_network(2);
nodes[0].put(b"proactive-key", b"proactive-val", 300, false);
std::thread::sleep(Duration::from_millis(100));
poll_all(&mut nodes, 10);
// Add a third node
let bp = nodes[0].local_addr().unwrap().port();
let mut node2 = Node::bind(0).unwrap();
node2.set_nat_state(NatState::Global);
node2.join("127.0.0.1", bp).unwrap();
nodes.push(node2);
// Poll to let proactive replication trigger
std::thread::sleep(Duration::from_millis(100));
poll_all(&mut nodes, 20);
// At least the original 2 nodes should have the value;
// the new node may also have it via proactive replication
let total: usize = nodes.iter().map(|n| n.storage_count()).sum();
assert!(
total >= 2,
"Total stored {total} should be >= 2 after proactive replication"
);
}
// ── Republish on access tests ────────────────────
#[test]
fn republish_on_find_value() {
// Store on node 0, retrieve from node 2 via FIND_VALUE.
// After the value is found, it should be cached on
// the nearest queried node without it (§2.3).
let mut nodes = make_network(3);
nodes[0].put(b"republish-key", b"republish-val", 300, false);
std::thread::sleep(Duration::from_millis(100));
poll_all(&mut nodes, 10);
// Node 2 triggers FIND_VALUE
let _ = nodes[2].get(b"republish-key");
// Poll to let the lookup and republish propagate
for _ in 0..30 {
poll_all(&mut nodes, 5);
std::thread::sleep(Duration::from_millis(20));
let vals = nodes[2].get(b"republish-key");
if !vals.is_empty() {
break;
}
}
// Count total stored across all nodes — should be
// more than 1 due to republish-on-access caching
let total: usize = nodes.iter().map(|n| n.storage_count()).sum();
assert!(
total >= 2,
"Total stored {total} should be >= 2 after republish-on-access"
);
}
|