fips-core 0.4.34

Reusable FIPS mesh, endpoint, transport, and protocol library
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
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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
use super::*;

pub(in crate::node) enum TransitNextHopPlan {
    Route(NodeAddr),
    Loop(NodeAddr),
    NoRoute,
}

impl Node {
    // === Routing ===

    pub(in crate::node) fn cache_current_root_coords(
        &mut self,
        node_addr: NodeAddr,
        coords: crate::tree::TreeCoordinate,
        now_ms: u64,
    ) -> bool {
        if coords.node_addr() != &node_addr
            || coords.root_id() != self.tree_state.my_coords().root_id()
        {
            return false;
        }
        self.coord_cache.insert(node_addr, coords, now_ms);
        true
    }

    /// Check if a peer is a tree neighbor (parent or child in the spanning tree).
    ///
    /// Returns true if the peer is our current tree parent, or if the peer
    /// has declared us as their parent (making them our child).
    pub(crate) fn is_tree_peer(&self, peer_addr: &NodeAddr) -> bool {
        // Peer is our parent
        if !self.tree_state.is_root() && self.tree_state.my_declaration().parent_id() == peer_addr {
            return true;
        }
        // Peer is our child (their declaration names us as parent)
        if let Some(decl) = self.tree_state.peer_declaration(peer_addr)
            && decl.parent_id() == self.node_addr()
        {
            return true;
        }
        false
    }

    /// Find next hop for a destination node address.
    ///
    /// Routing priority:
    /// 1. Destination is self → `None` (local delivery)
    /// 2. Destination is a healthy direct peer → that peer. A known fallback
    ///    next-hop may beat a non-static direct path when it has a meaningful
    ///    link-quality advantage; operator-configured static UDP peers stay
    ///    pinned to direct while healthy and endpoint traffic is getting
    ///    authenticated return traffic.
    /// 3. Reply-learned routes in `reply_learned` mode. These are locally
    ///    observed reverse paths, selected with weighted multipath plus
    ///    periodic coordinate/tree exploration.
    /// 4. Bloom filter candidates with cached dest coords → among peers whose
    ///    bloom filter contains the destination, pick the one that minimizes
    ///    tree distance to the destination, with
    ///    `(link_cost, tree_distance_to_dest, node_addr)` tie-breaking.
    ///    The self-distance check ensures only peers strictly closer to the
    ///    destination than us are considered (prevents routing loops).
    /// 5. Greedy tree routing fallback (requires cached dest coords)
    /// 6. No route → `None`
    ///
    /// Both the bloom filter and tree routing paths require cached destination
    /// coordinates (checked in `coord_cache`). Without coordinates, the node
    /// cannot make loop-free forwarding decisions. The caller should signal
    /// `CoordsRequired` back to the source when `None` is returned for a
    /// non-local destination.
    pub fn find_next_hop(&mut self, dest_node_addr: &NodeAddr) -> Option<&ActivePeer> {
        // 1. Local delivery
        if dest_node_addr == self.node_addr() {
            return None;
        }
        let now_ms = Self::now_ms();
        let failed_learned_routes = self.learned_routes.failed_next_hops(dest_node_addr, now_ms);
        let direct_path_hard_degraded =
            self.session_direct_path_is_degraded(dest_node_addr, now_ms);
        let direct_path_soft_degraded = !direct_path_hard_degraded
            && self.session_direct_discovered_endpoint_trust_expired(dest_node_addr, now_ms);
        let fallback_peer_available = self.has_sendable_fallback_lookup_peer(dest_node_addr);
        let direct_session_degraded =
            fallback_peer_available && (direct_path_hard_degraded || direct_path_soft_degraded);
        let direct_session_untrusted = !direct_session_degraded
            && self.session_direct_path_exclusive_trust_expired(dest_node_addr, now_ms);
        let stale_traversal_direct_route = self
            .peers
            .get(dest_node_addr)
            .filter(|peer| {
                !direct_path_hard_degraded
                    && !direct_session_degraded
                    && !peer.is_healthy()
                    && peer.can_send()
            })
            .and_then(|_| {
                self.configured_peer(dest_node_addr)
                    .and_then(|peer_config| {
                        (peer_config.is_auto_connect()
                            && self.active_peer_uses_traversal_path(dest_node_addr, peer_config))
                        .then_some(*dest_node_addr)
                    })
            });

        let healthy_direct_route = self
            .peers
            .get(dest_node_addr)
            .filter(|peer| peer.is_healthy() && !direct_session_degraded)
            .map(|_| *dest_node_addr);
        let direct_payload_untried = self.sessions.get(dest_node_addr).is_some()
            && self
                .dataplane
                .fsp_owner_activity(dest_node_addr)
                .is_none_or(|activity| activity.last_outbound_next_hop().is_none());

        // A new FSP session has no payload evidence for any branch yet. Start
        // it on an already-authenticated direct FMP carrier even when a routed
        // handshake ingress currently has a better link-cost sample. This is
        // the only ordering-independent way to validate a direct path that was
        // promoted just before the FSP owner was installed. Once payload has
        // selected a branch, the ordinary affinity, cost, and degradation
        // rules below take over; missing direct return traffic expires the
        // exclusive-trust window and moves the owner back to fallback.
        if let Some(direct_addr) = healthy_direct_route
            && direct_payload_untried
            && !direct_session_untrusted
        {
            return self.peers.get(&direct_addr);
        }
        let authenticated_direct_handshake = self.config.node.routing.mode
            == RoutingMode::ReplyLearned
            && self
                .learned_routes
                .active_handshake_route(dest_node_addr, now_ms)
                == Some(*dest_node_addr);

        // A completed direct FSP handshake is fresh, authenticated evidence
        // that the recovered carrier can move control traffic. Let it carry a
        // bounded payload validation attempt before an older fallback flow
        // affinity or stale link-cost sample can reclaim the owner route. If
        // payload does not return, exclusive-trust expiry makes the direct
        // route untrusted and fallback routing resumes normally.
        if let Some(direct_addr) = healthy_direct_route
            && authenticated_direct_handshake
            && !direct_session_untrusted
        {
            return self.peers.get(&direct_addr);
        }
        let active_fallback_affinity = (self.config.node.routing.mode == RoutingMode::ReplyLearned)
            .then(|| {
                let activity = self.dataplane.fsp_owner_activity(dest_node_addr)?;
                let next_hop = activity.last_outbound_next_hop()?;
                (next_hop != *dest_node_addr
                    && activity.has_recent_outbound_activity(
                        now_ms,
                        self.session_direct_path_exclusive_trust_timeout_ms(),
                    )
                    && !failed_learned_routes.contains(&next_hop)
                    && self
                        .peers
                        .get(&next_hop)
                        .is_some_and(|peer| peer.is_healthy() && peer.can_send()))
                .then_some(next_hop)
            })
            .flatten();
        if let Some(next_hop_addr) = active_fallback_affinity {
            self.learned_routes
                .record_selected(dest_node_addr, &next_hop_addr, now_ms);
            return self.peers.get(&next_hop_addr);
        }
        let direct_session_has_recent_data_return =
            self.session_direct_path_has_recent_data_return(dest_node_addr, now_ms);
        if let Some(direct_addr) = healthy_direct_route
            && direct_session_has_recent_data_return
        {
            return self.peers.get(&direct_addr);
        }
        if let Some(direct_addr) = healthy_direct_route
            && !direct_session_untrusted
            && self.dataplane_fmp_link_cost(&direct_addr)
                <= 1.0 + ROUTING_FALLBACK_MIN_COST_ADVANTAGE
        {
            return self.peers.get(&direct_addr);
        }
        let direct_payload_eligible = healthy_direct_route.is_some();
        let payload_candidate_can_send = |addr: &NodeAddr, peer: &ActivePeer| {
            if addr == dest_node_addr {
                direct_payload_eligible
            } else {
                peer.is_healthy() && !failed_learned_routes.contains(addr)
            }
        };

        // A healthy direct path is not automatically the best path. A
        // hotspot/NAT hairpin can remain sendable with high RTT or mild loss;
        // in that case a lower-cost mesh next-hop should carry traffic while
        // direct probes continue in the background.
        let fallback_beats_direct = |node: &Self, fallback_addr: NodeAddr| {
            if direct_session_untrusted {
                return healthy_direct_route != Some(fallback_addr)
                    && node
                        .peers
                        .get(&fallback_addr)
                        .is_some_and(|peer| peer.is_healthy());
            }
            node.route_candidate_beats_direct(healthy_direct_route, fallback_addr)
        };

        let sendable_learned_peers = if self.config.node.routing.mode == RoutingMode::ReplyLearned {
            Some(
                self.peers
                    .iter()
                    .filter(|(addr, peer)| payload_candidate_can_send(addr, peer))
                    .map(|(addr, _)| *addr)
                    .collect::<HashSet<_>>(),
            )
        } else {
            None
        };

        let explore_fallback = sendable_learned_peers.as_ref().is_some_and(|sendable| {
            self.learned_routes.should_explore_fallback(
                dest_node_addr,
                now_ms,
                self.config.node.routing.learned_fallback_explore_interval,
                |addr| sendable.contains(addr),
            )
        });
        // 3. Optional reply-learned routing. These entries are not peer
        // claims; they are local observations of which peer carried traffic
        // or a verified lookup response back from the destination. Most
        // packets use weighted multipath over learned routes, but periodic
        // fallback exploration lets coord/bloom/tree routes discover better
        // candidates.
        if let Some(sendable) = &sendable_learned_peers
            && !explore_fallback
        {
            let eligible = sendable
                .iter()
                .copied()
                .filter(|addr| fallback_beats_direct(self, *addr))
                .collect::<HashSet<_>>();
            if !eligible.is_empty()
                && let Some(next_hop_addr) =
                    self.learned_routes
                        .select_next_hop(dest_node_addr, now_ms, |addr| eligible.contains(addr))
            {
                return self.peers.get(&next_hop_addr);
            }
        }

        // Look up cached destination coordinates (required by both bloom and tree paths).
        let Some(dest_coords) = self
            .coord_cache
            .get_and_touch(dest_node_addr, now_ms)
            .cloned()
        else {
            if (healthy_direct_route.is_none() || explore_fallback)
                && let Some(sendable) = &sendable_learned_peers
                && let Some(next_hop_addr) =
                    self.learned_routes
                        .select_next_hop(dest_node_addr, now_ms, |addr| sendable.contains(addr))
            {
                return self.peers.get(&next_hop_addr);
            }
            if let Some(direct_addr) = healthy_direct_route {
                return self.peers.get(&direct_addr);
            }
            if let Some(direct_addr) = stale_traversal_direct_route {
                return self.peers.get(&direct_addr);
            }
            return None;
        };

        // 4. Bloom filter candidates — requires dest_coords for loop-free selection.
        //    If no candidate is strictly closer, fall through to tree routing.
        let coordinate_route_addr = {
            let candidates: Vec<&ActivePeer> = self
                .peers
                .iter()
                .filter(|(addr, peer)| {
                    payload_candidate_can_send(addr, peer) && peer.may_reach(dest_node_addr)
                })
                .map(|(_, peer)| peer)
                .collect();
            if !candidates.is_empty() {
                self.select_best_candidate(&candidates, &dest_coords)
                    .map(|peer| *peer.node_addr())
            } else {
                None
            }
        };
        if let Some(next_hop_addr) = coordinate_route_addr
            && fallback_beats_direct(self, next_hop_addr)
        {
            return self.peers.get(&next_hop_addr);
        }

        // 5. Greedy tree routing fallback
        let tree_route_addr = self.select_tree_payload_candidate(
            &dest_coords,
            dest_node_addr,
            direct_payload_eligible,
        );
        if let Some(next_hop_addr) = tree_route_addr
            && fallback_beats_direct(self, next_hop_addr)
        {
            return self.peers.get(&next_hop_addr);
        }

        if explore_fallback
            && let Some(peer) = sendable_learned_peers.as_ref().and_then(|sendable| {
                self.learned_routes
                    .select_next_hop(dest_node_addr, now_ms, |addr| sendable.contains(addr))
                    .and_then(|next_hop_addr| self.peers.get(&next_hop_addr))
            })
        {
            return Some(peer);
        }

        if let Some(direct_addr) = healthy_direct_route {
            return self.peers.get(&direct_addr);
        }

        if let Some(sendable) = &sendable_learned_peers
            && let Some(next_hop_addr) =
                self.learned_routes
                    .select_next_hop(dest_node_addr, now_ms, |addr| sendable.contains(addr))
        {
            return self.peers.get(&next_hop_addr);
        }

        if let Some(direct_addr) = stale_traversal_direct_route {
            return self.peers.get(&direct_addr);
        }

        None
    }

    pub(in crate::node) fn plan_transit_next_hop(
        &mut self,
        dest_node_addr: &NodeAddr,
        previous_hop: &NodeAddr,
    ) -> TransitNextHopPlan {
        if dest_node_addr == self.node_addr() {
            return TransitNextHopPlan::NoRoute;
        }

        if dest_node_addr != previous_hop
            && self
                .peers
                .get(dest_node_addr)
                .is_some_and(|peer| peer.is_healthy())
        {
            return TransitNextHopPlan::Route(*dest_node_addr);
        }

        // A forwarded LookupResponse proves this direction of the transit
        // path. Keep an established encrypted flow on that learned path while
        // it is live; origin-side route exploration must not spray transit
        // records into an unproven branch. Failure handling removes/decays the
        // route and the ordinary coordinate/tree fallback remains below.
        if self.config.node.routing.mode == RoutingMode::ReplyLearned {
            let sendable = self
                .peers
                .iter()
                .filter(|(addr, peer)| *addr != previous_hop && peer.is_healthy())
                .map(|(addr, _)| *addr)
                .collect::<HashSet<_>>();
            if let Some(next_hop_addr) =
                self.learned_routes
                    .select_handshake_route(dest_node_addr, Self::now_ms(), |addr| {
                        sendable.contains(addr)
                    })
            {
                return TransitNextHopPlan::Route(next_hop_addr);
            }
        }

        let Some(next_hop_addr) = self
            .find_next_hop(dest_node_addr)
            .map(|peer| *peer.node_addr())
        else {
            return TransitNextHopPlan::NoRoute;
        };
        if next_hop_addr == *dest_node_addr && &next_hop_addr != previous_hop {
            return TransitNextHopPlan::Route(next_hop_addr);
        }

        let now_ms = Self::now_ms();
        let dest_coords = self
            .coord_cache
            .get_and_touch(dest_node_addr, now_ms)
            .cloned();
        let selected_strictly_progresses = dest_coords.as_ref().is_some_and(|dest_coords| {
            self.tree_state.my_coords().root_id() == dest_coords.root_id()
                && self
                    .tree_state
                    .peer_coords(&next_hop_addr)
                    .is_some_and(|peer_coords| {
                        peer_coords.distance_to(dest_coords)
                            < self.tree_state.my_coords().distance_to(dest_coords)
                    })
        });

        if &next_hop_addr != previous_hop && (dest_coords.is_none() || selected_strictly_progresses)
        {
            return TransitNextHopPlan::Route(next_hop_addr);
        }

        let coordinate_fallback = dest_coords.and_then(|dest_coords| {
            self.select_tree_payload_candidate_avoiding(
                &dest_coords,
                dest_node_addr,
                false,
                Some(previous_hop),
            )
        });
        if let Some(next_hop_addr) = coordinate_fallback {
            return TransitNextHopPlan::Route(next_hop_addr);
        }
        TransitNextHopPlan::Loop(next_hop_addr)
    }

    #[cfg(test)]
    pub(in crate::node) fn find_transit_next_hop(
        &mut self,
        dest_node_addr: &NodeAddr,
        previous_hop: &NodeAddr,
    ) -> Option<NodeAddr> {
        match self.plan_transit_next_hop(dest_node_addr, previous_hop) {
            TransitNextHopPlan::Route(next_hop_addr) => Some(next_hop_addr),
            TransitNextHopPlan::Loop(next_hop_addr) => {
                self.record_route_failure(*dest_node_addr, next_hop_addr);
                None
            }
            TransitNextHopPlan::NoRoute => None,
        }
    }

    pub(super) fn route_candidate_beats_direct(
        &self,
        healthy_direct_route: Option<NodeAddr>,
        candidate_addr: NodeAddr,
    ) -> bool {
        let Some(direct_addr) = healthy_direct_route else {
            return true;
        };
        if candidate_addr == direct_addr {
            return false;
        }

        if !self.peers.contains_key(&direct_addr) {
            return true;
        }
        if self.active_peer_uses_configured_static_udp_path(&direct_addr) {
            return false;
        }
        let Some(candidate) = self.peers.get(&candidate_addr) else {
            return false;
        };
        if !candidate.is_healthy() {
            return false;
        }

        let direct_cost = self.dataplane_fmp_link_cost(&direct_addr);
        let candidate_cost = self.dataplane_fmp_link_cost(&candidate_addr);
        candidate_cost + ROUTING_FALLBACK_MIN_COST_ADVANTAGE < direct_cost
    }

    pub(super) fn select_tree_payload_candidate(
        &self,
        dest_coords: &crate::tree::TreeCoordinate,
        direct_dest: &NodeAddr,
        direct_payload_eligible: bool,
    ) -> Option<NodeAddr> {
        self.select_tree_payload_candidate_avoiding(
            dest_coords,
            direct_dest,
            direct_payload_eligible,
            None,
        )
    }

    fn select_tree_payload_candidate_avoiding(
        &self,
        dest_coords: &crate::tree::TreeCoordinate,
        direct_dest: &NodeAddr,
        direct_payload_eligible: bool,
        excluded: Option<&NodeAddr>,
    ) -> Option<NodeAddr> {
        if self.tree_state.my_coords().root_id() != dest_coords.root_id() {
            return None;
        }

        let my_distance = self.tree_state.my_coords().distance_to(dest_coords);
        let mut best: Option<(NodeAddr, usize)> = None;

        for (peer_addr, peer) in &self.peers {
            if excluded == Some(peer_addr) {
                continue;
            }
            if peer_addr == direct_dest {
                if !direct_payload_eligible {
                    continue;
                }
            } else if !peer.is_healthy() {
                continue;
            }

            let Some(peer_coords) = self.tree_state.peer_coords(peer_addr) else {
                continue;
            };
            let distance = peer_coords.distance_to(dest_coords);
            if distance >= my_distance {
                continue;
            }

            let dominated = match &best {
                None => true,
                Some((best_id, best_dist)) => {
                    distance < *best_dist || (distance == *best_dist && peer_addr < best_id)
                }
            };
            if dominated {
                best = Some((*peer_addr, distance));
            }
        }

        best.map(|(peer_addr, _)| peer_addr)
    }

    pub(in crate::node) fn session_direct_path_is_degraded(
        &mut self,
        dest: &NodeAddr,
        now_ms: u64,
    ) -> bool {
        self.session_direct_degradation.is_degraded(dest, now_ms)
    }

    pub(in crate::node) fn session_direct_path_degradation_active(
        &self,
        dest: &NodeAddr,
        now_ms: u64,
    ) -> bool {
        self.session_direct_degradation.is_degraded_at(dest, now_ms)
    }

    pub(in crate::node) fn session_direct_path_blocks_direct_payload(
        &mut self,
        dest: &NodeAddr,
        now_ms: u64,
    ) -> bool {
        self.session_direct_path_is_degraded(dest, now_ms)
            || self.session_direct_discovered_endpoint_trust_expired(dest, now_ms)
    }

    pub(in crate::node) fn session_direct_path_exclusive_trust_timeout_ms(&self) -> u64 {
        self.config
            .node
            .heartbeat_interval_secs
            .saturating_mul(1000)
            .saturating_add(1_500)
            .max(SESSION_DIRECT_MIN_EXCLUSIVE_TRUST_MS)
    }

    pub(in crate::node) fn session_direct_path_exclusive_trust_expired(
        &self,
        dest: &NodeAddr,
        now_ms: u64,
    ) -> bool {
        if !self
            .peers
            .get(dest)
            .is_some_and(|peer| peer.is_healthy() && peer.can_send())
        {
            return false;
        }
        let Some(activity) = self.dataplane.fsp_owner_activity(dest) else {
            return false;
        };
        activity.has_recent_outbound_without_data_return_from(
            dest,
            now_ms,
            self.session_direct_path_exclusive_trust_timeout_ms(),
        )
    }

    pub(in crate::node) fn session_direct_path_has_recent_data_return(
        &self,
        dest: &NodeAddr,
        now_ms: u64,
    ) -> bool {
        self.dataplane
            .fsp_owner_activity(dest)
            .is_some_and(|activity| {
                activity.has_recent_data_return_from(
                    dest,
                    now_ms,
                    self.session_direct_path_exclusive_trust_timeout_ms(),
                )
            })
    }

    fn session_direct_discovered_endpoint_trust_expired(
        &self,
        dest: &NodeAddr,
        now_ms: u64,
    ) -> bool {
        self.session_direct_path_exclusive_trust_expired(dest, now_ms)
            && self.configured_peer(dest).is_some_and(|peer_config| {
                peer_config.is_auto_connect()
                    && self.active_peer_uses_traversal_path(dest, peer_config)
            })
    }

    pub(in crate::node) fn mark_session_direct_path_degraded(
        &mut self,
        dest: NodeAddr,
        now_ms: u64,
    ) -> bool {
        let changed = self.session_direct_degradation.mark_degraded(
            dest,
            now_ms,
            SESSION_DIRECT_DEGRADED_HOLD_MS,
        );
        if changed {
            let _ = self.refresh_dataplane_fsp_owner_routes(&dest);
        }
        changed
    }

    pub(in crate::node) fn clear_session_direct_path_degraded(&mut self, dest: &NodeAddr) -> bool {
        let changed = self.session_direct_degradation.clear(dest);
        if changed {
            let _ = self.refresh_dataplane_fsp_owner_routes(dest);
        }
        changed
    }

    pub(in crate::node) fn clear_session_direct_path_degraded_after_promotion(
        &mut self,
        dest: &NodeAddr,
        now_ms: u64,
    ) {
        let direct_was_degraded = self.session_direct_path_degradation_active(dest, now_ms);
        let active_fallback_next_hop = self
            .dataplane
            .fsp_owner_activity(dest)
            .and_then(|activity| activity.last_outbound_next_hop())
            .filter(|next_hop| next_hop != dest);
        if direct_was_degraded || active_fallback_next_hop.is_some() {
            if let Some(fallback_next_hop) = active_fallback_next_hop {
                let _ = self
                    .dataplane
                    .forget_fsp_data_route(*dest, fallback_next_hop);
            }
            debug!(
                peer = %self.peer_display_name(dest),
                direct_was_degraded,
                released_fallback_affinity = active_fallback_next_hop.is_some(),
                "Authenticated direct-path promotion restored payload eligibility"
            );
            if !self.clear_session_direct_path_degraded(dest) {
                let _ = self.refresh_dataplane_fsp_owner_routes(dest);
            }
            return;
        }

        let keep_degraded = self.session_direct_path_blocks_direct_payload(dest, now_ms);
        if !keep_degraded {
            self.clear_session_direct_path_degraded(dest);
        } else if self.promoted_path_matches_configured_static_peer(dest) {
            debug!(
                peer = %self.peer_display_name(dest),
                "Clearing direct payload degradation after configured direct-path promotion"
            );
            self.clear_session_direct_path_degraded(dest);
        } else {
            debug!(
                peer = %self.peer_display_name(dest),
                "Keeping direct payload degraded after direct-path promotion"
            );
        }
    }

    pub(in crate::node) fn retain_direct_payload_validation_after_fmp_rekey(
        &mut self,
        dest: &NodeAddr,
    ) {
        // FMP control proves only that the link rekey completed. It does not
        // prove that end-to-end FSP payload has returned to the direct path;
        // routed fallback traffic can remain healthy at the same time. Keep
        // the degradation marker and retry loop until authenticated direct
        // FSP receive activity clears them.
        if !self.promoted_path_matches_configured_static_peer(dest) {
            return;
        }

        let fallback_next_hop = self
            .dataplane
            .fsp_owner_activity(dest)
            .and_then(|activity| activity.last_outbound_next_hop())
            .filter(|next_hop| next_hop != dest);
        if let Some(next_hop) = fallback_next_hop {
            let _ = self.dataplane.forget_fsp_data_route(*dest, next_hop);
        }
        let _ = self
            .session_direct_degradation
            .release_hold_for_validation(dest, Self::now_ms());
        let refreshed = self.refresh_dataplane_fsp_owner_routes(dest);
        let pending_payload_validation =
            self.session_direct_degradation.has_pending_validation(dest);
        debug!(
            peer = %self.peer_display_name(dest),
            released_fallback_affinity = fallback_next_hop.is_some(),
            refreshed,
            pending_payload_validation,
            "Authenticated FMP rekey made direct FSP payload eligible for validation"
        );
        if !pending_payload_validation {
            self.clear_retry_unless_direct_refresh_needed(dest);
        }
    }

    fn promoted_path_matches_configured_static_peer(&self, peer_node_addr: &NodeAddr) -> bool {
        self.config
            .auto_connect_peers()
            .filter(|peer_config| {
                PeerIdentity::from_npub(&peer_config.npub)
                    .ok()
                    .is_some_and(|identity| identity.node_addr() == peer_node_addr)
            })
            .any(|peer_config| {
                self.static_peer_addresses(peer_config)
                    .iter()
                    .any(|candidate| self.active_peer_matches_candidate(peer_node_addr, candidate))
            })
    }

    pub(in crate::node) fn learn_reverse_route(
        &mut self,
        destination: NodeAddr,
        next_hop: NodeAddr,
    ) {
        if self.config.node.routing.mode != RoutingMode::ReplyLearned
            || destination == *self.node_addr()
        {
            return;
        }
        let now_ms = Self::now_ms();
        self.learned_routes.learn(
            destination,
            next_hop,
            now_ms,
            self.config.node.routing.learned_ttl_secs,
            self.config.node.routing.max_learned_routes_per_dest,
        );
        // Discovery may return through more than one live seed. Once an FSP
        // handshake has authenticated one complete path, keep that owner route
        // stable while its physical next hop remains usable; later learned
        // candidates stay available for explicit failure/degradation recovery.
        let _ = self.refresh_dataplane_fsp_owner_routes_retaining_current(&destination);
    }

    pub(in crate::node) fn pin_handshake_reverse_route(
        &mut self,
        destination: NodeAddr,
        next_hop: NodeAddr,
    ) {
        if self.config.node.routing.mode != RoutingMode::ReplyLearned
            || destination == *self.node_addr()
        {
            return;
        }
        self.learned_routes.pin_handshake_route(
            destination,
            next_hop,
            Self::now_ms(),
            self.config.node.routing.learned_ttl_secs,
            self.config.node.routing.max_learned_routes_per_dest,
        );
    }

    pub(in crate::node) fn pin_duplicate_handshake_reverse_route(
        &mut self,
        destination: NodeAddr,
        next_hop: NodeAddr,
    ) {
        if self.config.node.routing.mode != RoutingMode::ReplyLearned
            || destination == *self.node_addr()
        {
            return;
        }
        let now_ms = Self::now_ms();
        if self
            .learned_routes
            .active_handshake_route(&destination, now_ms)
            .is_some_and(|pinned_hop| pinned_hop != next_hop)
        {
            return;
        }
        self.learned_routes.pin_handshake_route(
            destination,
            next_hop,
            now_ms,
            self.config.node.routing.learned_ttl_secs,
            self.config.node.routing.max_learned_routes_per_dest,
        );
    }

    pub(in crate::node) fn routing_error_matches_active_path(
        &mut self,
        destination: &NodeAddr,
        previous_hop: &NodeAddr,
    ) -> bool {
        if self.config.node.routing.mode != RoutingMode::ReplyLearned {
            return true;
        }

        // Once established traffic has selected a branch, match feedback to
        // the branch that actually carried the last outbound payload. The
        // handshake pin may still name the authenticated msg2 ingress until
        // its TTL expires, but reverse traffic can legitimately establish a
        // different outbound route before then.
        if let Some(last_outbound_next_hop) = self
            .dataplane
            .fsp_owner_activity(destination)
            .and_then(|activity| activity.last_outbound_next_hop())
        {
            return last_outbound_next_hop == *previous_hop;
        }

        if let Some(pinned_hop) = self
            .learned_routes
            .active_handshake_route(destination, Self::now_ms())
        {
            // The reporter may be any downstream router on a legitimate
            // multi-hop path. The authenticated adjacent ingress is the part
            // we can match to the pinned route.
            return pinned_hop == *previous_hop;
        }

        // The owner's wrap route can move as reverse traffic teaches a new
        // branch while an already-transmitted payload and its PathBroken are
        // still returning on the old branch. Match that explicit feedback to
        // the branch actually used by the last outbound payload. Clearing the
        // affinity when the failure is recorded makes later errors from the
        // same branch stale.
        // Before any payload has selected a branch, the dataplane owner's wrap
        // route is the best authenticated local match available.
        self.dataplane
            .fsp_owner_next_hop(destination)
            .is_none_or(|next_hop| next_hop == *previous_hop)
    }

    pub(in crate::node) fn record_route_failure(
        &mut self,
        destination: NodeAddr,
        next_hop: NodeAddr,
    ) {
        if self.config.node.routing.mode != RoutingMode::ReplyLearned {
            return;
        }
        let _ = self.dataplane.forget_fsp_data_route(destination, next_hop);
        self.learned_routes.record_failure(&destination, &next_hop);
        let _ = self.refresh_dataplane_fsp_owner_routes(&destination);
    }

    pub(crate) fn learned_route_table_snapshot(&self, now_ms: u64) -> LearnedRouteTableSnapshot {
        self.learned_routes.snapshot(now_ms)
    }

    pub(in crate::node) fn purge_learned_routes(&mut self, now_ms: u64) {
        self.learned_routes.purge_expired(now_ms);
    }

    /// Select the best peer from a set of bloom filter candidates.
    ///
    /// Uses distance from each candidate's tree coordinates to the destination
    /// as the primary metric (after link_cost). Only selects peers that are
    /// strictly closer to the destination than we are (self-distance check
    /// prevents routing loops).
    ///
    /// Ordering: `(link_cost, distance_to_dest, node_addr)`.
    pub(super) fn select_best_candidate<'a>(
        &'a self,
        candidates: &[&'a ActivePeer],
        dest_coords: &crate::tree::TreeCoordinate,
    ) -> Option<&'a ActivePeer> {
        let my_distance = self.tree_state.my_coords().distance_to(dest_coords);

        let mut best: Option<(&ActivePeer, f64, usize)> = None;

        for &candidate in candidates {
            if !candidate.can_send() {
                continue;
            }

            let cost = self.dataplane_fmp_link_cost(candidate.node_addr());

            let dist = self
                .tree_state
                .peer_coords(candidate.node_addr())
                .map(|pc| pc.distance_to(dest_coords))
                .unwrap_or(usize::MAX);

            // Self-distance check: only consider peers strictly closer
            // to the destination than we are (prevents routing loops)
            if dist >= my_distance {
                continue;
            }

            let dominated = match &best {
                None => true,
                Some((_, best_cost, best_dist)) => {
                    cost < *best_cost
                        || (cost == *best_cost && dist < *best_dist)
                        || (cost == *best_cost
                            && dist == *best_dist
                            && candidate.node_addr() < best.as_ref().unwrap().0.node_addr())
                }
            };

            if dominated {
                best = Some((candidate, cost, dist));
            }
        }

        best.map(|(peer, _, _)| peer)
    }

    /// Check if a destination is in any peer's bloom filter.
    pub fn destination_in_filters(&self, dest: &NodeAddr) -> Vec<&ActivePeer> {
        self.peers.values().filter(|p| p.may_reach(dest)).collect()
    }
}