sciparse 0.6.1

Zero-copy SCION packet parsing, serialization and control plane components
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
// Copyright 2026 Anapaya Systems
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! SCION standard path routing

use std::fmt::{Debug, Display};

use crate::dataplane_path::standard::{
    mac::{
        ForwardingKey,
        algo::{calculate_hop_mac, mac_beta_step},
    },
    types::{HopFieldFlags, HopFieldMac, InfoFieldFlags},
    view::{HopFieldView, InfoFieldView, StandardPathView},
};

/// Error type for failures during path advance.
#[derive(Debug, thiserror::Error)]
pub enum AdvanceError {
    /// The hop field index is out of bounds.
    #[error("hop out of bounds: {0}")]
    HopOutOfBounds(u8),
    /// The info field index is out of bounds.
    #[error("info out of bounds: {0}")]
    InfoOutOfBounds(u8),
    /// The current hop field index is in a different segment than the current info
    /// field index.
    #[error(
        "current hop field index is in segment {expected}, but info index is at segment {actual}"
    )]
    InvalidSegmentIndex {
        /// The expected segment index based on the hop field index
        expected: usize,
        /// The actual segment index
        actual: usize,
    },
    /// Generic unrecoverable error indicating that the path is in an invalid state for
    /// advancing.
    #[error("path is in invalid state for advance: {0}")]
    InvalidPathState(&'static str),
}

/// Trait to allow validating hop fields and segment changes during path advance.
pub trait AdvanceValidator {
    /// The error type returned by the validator when validation fails
    type Error: Debug;

    /// Validates a hop field.
    ///
    /// This is called for each hop field required to be validated during advancing.
    ///
    /// Examples of what this function should validate include:
    /// - MAC validity
    /// - Correctness of the ingress and egress interfaces
    /// - HopField Expiry time
    ///
    /// If this returns an error, the advance process is aborted and the error is
    /// returned by the advance function.
    fn validate_hop(
        &self,
        hop_index: usize,
        hop_field: &HopFieldView,
        info_field: &InfoFieldView,
        is_segment_start: bool,
        is_segment_end: bool,
    ) -> Result<(), Self::Error>;

    /// Validates a segment change
    ///
    /// This is called when the path advances into a new segment, and allows validating
    /// the correctness of the transition between the two segments.
    ///
    /// Examples of what this function should validate include:
    /// - Correct link type for the transition between the two segments (e.g. no Down Segment
    ///   followed by an Up Segment)
    fn validate_segment_change(
        &self,
        hop_index: usize,
        current_hop_field: &HopFieldView,
        current_info_field: &InfoFieldView,
        next_hop_field: &HopFieldView,
        next_info_field: &InfoFieldView,
    ) -> Result<(), Self::Error>;
}

struct NoValidation;
impl AdvanceValidator for NoValidation {
    type Error = std::convert::Infallible;
    #[inline]
    fn validate_hop(
        &self,
        _hop_index: usize,
        _hop_field: &HopFieldView,
        _info_field: &InfoFieldView,
        _is_segment_start: bool,
        _is_segment_end: bool,
    ) -> Result<(), Self::Error> {
        Ok(())
    }

    #[inline]
    fn validate_segment_change(
        &self,
        _hop_index: usize,
        _current_hop_field: &HopFieldView,
        _current_info_field: &InfoFieldView,
        _next_hop_field: &HopFieldView,
        _next_info_field: &InfoFieldView,
    ) -> Result<(), Self::Error> {
        Ok(())
    }
}

/// Result of advancing the ingress of a path
#[derive(Debug)]
pub struct IngressAdvanceOutput {
    /// An SCMP alert was present on the packet, indicating it should be processed at
    /// the ingress router
    ///
    /// The router may choose to drop the packet after processing the alert, or it may
    /// choose to continue processing and forward the packet with the
    /// given action.
    pub scmp_alert: bool,
    /// The ingress interface according to the packet
    pub ingress_interface: u16,
    /// The action to perform with the packet after advancing
    pub action: IngressAdvanceAction,
}

/// Action to perform with the packet after advancing the ingress of a path
#[derive(Debug)]
pub enum IngressAdvanceAction {
    /// The packet should be sent out by its egress interface
    ContinueEgress {
        /// The interface through which the packet should be sent out
        egress_if: u16,
    },
    /// The packet is at the end of the path and should be processed at the local
    /// destination.
    ForwardLocal,
}

/// Result of advancing the ingress of a path, including potential validation errors
#[derive(Debug)]
pub enum IngressValidateResult<ValidationErrorType> {
    /// The path was successfully advanced and validated, and can be processed according to the
    /// returned [IngressAdvanceOutput].
    Ok(IngressAdvanceOutput),
    /// The path was successfully advanced, but validation failed with the provided error.
    ValidationFailed(IngressAdvanceOutput, ValidationErrorType),
}
impl<E> IngressValidateResult<E> {
    /// Converts the IngressAdvanceValidateResult into a Result
    #[inline]
    pub fn into_result(self) -> Result<IngressAdvanceOutput, (IngressAdvanceOutput, E)> {
        match self {
            IngressValidateResult::Ok(output) => Ok(output),
            IngressValidateResult::ValidationFailed(output, err) => Err((output, err)),
        }
    }
}

impl StandardPathView {
    /// Advances the path at ingress, without performing any validation.
    ///
    /// See [`Self::advance_ingress_with_validator`] for a version of this function that allows
    /// providing a validator to perform extended validation during the advance process.
    #[inline]
    pub fn advance_ingress(
        &mut self,
        from_internal_interface: bool,
    ) -> Result<IngressAdvanceOutput, AdvanceError> {
        match self.advance_ingress_with_validator(NoValidation, from_internal_interface)? {
            IngressValidateResult::Ok(ingress_advance_result) => Ok(ingress_advance_result),
            IngressValidateResult::ValidationFailed(..) => {
                unreachable!("NoValidation is Infallible")
            }
        }
    }

    /// Advances the path at ingress.
    ///
    /// If successful, the path is updated in-place to reflect the advance, and an
    /// [`IngressAdvanceOutput`] indicating the next steps for processing the packet is
    /// returned.
    ///
    /// If the path is invalid an error is returned and the path is not modified.
    /// A validation error will be returned with the [IngressAdvanceOutput] if the path is useable
    /// but the validation failed.
    ///
    /// This function itself only performs minimal validation.
    ///
    /// Extended validation can be performed by providing a validator. An example
    /// validator is provided in the form of [`HopMacValidator`], which
    /// checks the validity of hop field MACs.
    ///
    /// To advance the path on egress, use the [`Self::advance_egress_with_validator`].
    ///
    /// ## Parameters
    /// - `validator`: A validator allowing to perform extended validation during the advance
    ///   process.
    /// - `from_internal_interface`: Indicates whether the advance is triggered by a packet arriving
    ///   from an internal interface, or if received from an external AS
    #[inline]
    pub fn advance_ingress_with_validator<ValidatorType, E>(
        &mut self,
        validator: ValidatorType,
        from_internal_interface: bool,
    ) -> Result<IngressValidateResult<E>, AdvanceError>
    where
        ValidatorType: AdvanceValidator<Error = E>,
        E: Debug,
    {
        // Extract
        let hop_field_count = self.hop_field_count();
        let curr_hop_idx = self.curr_hop_field_idx() as usize;
        let curr_info_idx = self.curr_info_field_idx() as usize;

        let (seg_idx, start_of_segment, end_of_segment) = self
            .calculate_segment_index(curr_hop_idx)
            .ok_or(AdvanceError::HopOutOfBounds(curr_hop_idx as u8))?;

        if start_of_segment && end_of_segment {
            return Err(AdvanceError::InvalidPathState(
                "Path contains a segment with a single hop",
            ));
        }

        if seg_idx != curr_info_idx {
            return Err(AdvanceError::InvalidSegmentIndex {
                expected: seg_idx,
                actual: curr_info_idx,
            });
        }

        let is_final_hop = curr_hop_idx + 1 >= hop_field_count as usize;

        // XXX(ake): In theory the check above guarantees that we can access the current
        // hop and info fields.
        let mut curr_hop_copy = *self
            .hop_field(curr_hop_idx)
            .ok_or(AdvanceError::HopOutOfBounds(curr_hop_idx as u8))?;

        let mut curr_info_copy = *self
            .curr_info_field()
            .ok_or(AdvanceError::InfoOutOfBounds(curr_info_idx as u8))?;

        let curr_ingress_interface = curr_hop_copy.ingress_interface(&curr_info_copy);

        let in_construction_dir = curr_info_copy.flags().contains(InfoFieldFlags::CONS_DIR);

        // Process

        // If not in construction dir, update mac before validation
        if !from_internal_interface && !in_construction_dir {
            let curr_segment_id = curr_info_copy.segment_id();
            let hop_mac = curr_hop_copy.mac();
            let new_segment_id = mac_beta_step(curr_segment_id, *hop_mac.as_bytes());
            curr_info_copy.set_segment_id(new_segment_id);
        }

        // Validate the current hop field
        let mut validation_err = validator
            .validate_hop(
                curr_hop_idx,
                &curr_hop_copy,
                &curr_info_copy,
                start_of_segment,
                end_of_segment,
            )
            .err();

        // Check if we have an SCMP alert at the ingress router.
        let scmp_alert = curr_hop_copy
            .flags()
            .normalized_ingress_router_alert(in_construction_dir);

        if !from_internal_interface && scmp_alert {
            // Unset the alert flag in the hop field
            let mut flags = curr_hop_copy.flags();
            match in_construction_dir {
                true => flags.remove(HopFieldFlags::CONS_INGRESS_ROUTER_ALERT),
                false => flags.remove(HopFieldFlags::CONS_EGRESS_ROUTER_ALERT),
            };
            curr_hop_copy.set_flags(flags);
        }

        let res = match (is_final_hop, end_of_segment) {
            // FINAL_HOP: process at local destination
            (true, true) => {
                IngressAdvanceOutput {
                    scmp_alert,
                    ingress_interface: curr_ingress_interface,
                    action: IngressAdvanceAction::ForwardLocal,
                }
            }
            // NORMAL ADVANCE: continue to egress
            (false, false) => {
                IngressAdvanceOutput {
                    scmp_alert,
                    ingress_interface: curr_ingress_interface,
                    action: IngressAdvanceAction::ContinueEgress {
                        egress_if: curr_hop_copy.egress_interface(&curr_info_copy),
                    },
                }
            }
            // SEGMENT CHANGE: advance to the next segment
            (false, true) => {
                let next_hop_field = self
                    .hop_field(curr_hop_idx + 1)
                    .ok_or(AdvanceError::HopOutOfBounds(curr_hop_idx as u8 + 1))?;
                let next_info_field = self
                    .info_field(seg_idx + 1)
                    .ok_or(AdvanceError::InfoOutOfBounds((seg_idx + 1) as u8))?;

                // Validate the segment change if previous validation did not fail yet
                validation_err = validation_err.or_else(|| {
                    validator
                        .validate_segment_change(
                            curr_hop_idx,
                            &curr_hop_copy,
                            &curr_info_copy,
                            next_hop_field,
                            next_info_field,
                        )
                        .err()
                });
                let egress_if = next_hop_field.egress_interface(next_info_field);

                // Validate the current hop field if validation did not fail yet

                validation_err = validation_err.or_else(|| {
                    validator
                        .validate_hop(
                            curr_hop_idx + 1,
                            next_hop_field,
                            next_info_field,
                            true,  // We are at the start of the new segment
                            false, // Can't be the end of the new segment
                        )
                        .err()
                });

                // Advance the hop field index by one
                self.set_curr_hop_field((curr_hop_idx + 1) as u8);
                self.set_curr_info_field((seg_idx + 1) as u8);

                // NOTE: We are ignoring SCMP alerts which are set on the segment change
                // hop fields.

                IngressAdvanceOutput {
                    scmp_alert,
                    ingress_interface: curr_ingress_interface,
                    action: IngressAdvanceAction::ContinueEgress { egress_if },
                }
            }
            _ => {
                unreachable!(
                    "The only case where we can have a final hop is when we are also at a segment end, which is handled by the first match arm"
                )
            }
        };

        // Commit the updated fields
        *self
            .info_field_mut(curr_info_idx)
            .expect("If we can get the current info field without mut, we can get it with mut") =
            curr_info_copy;
        *self
            .hop_field_mut(curr_hop_idx)
            .expect("If we can get the current hop field without mut, we can get it with mut") =
            curr_hop_copy;

        match validation_err {
            Some(err) => Ok(IngressValidateResult::ValidationFailed(res, err)),
            None => Ok(IngressValidateResult::Ok(res)),
        }
    }
}

/// Result of advancing a path at the egress of a router.
///
/// The router may choose to drop the packet after processing the alert, or it may
/// choose to continue processing and forward the packet with the given
/// egress interface.
#[derive(Debug)]
pub struct EgressAdvanceOutput {
    /// An SCMP alert was present on the packet, indicating it should be processed at
    /// the egress router.
    pub scmp_alert: bool,
    /// The egress interface according to the packet.
    pub egress_interface: u16,
}

/// Result of advancing the egress of a path, including potential validation errors
#[derive(Debug)]
pub enum EgressValidateResult<ValidationErrorType> {
    /// The path was successfully advanced and validated, and can be processed according to the
    /// returned [EgressAdvanceOutput].
    Ok(EgressAdvanceOutput),
    /// The path was successfully advanced, but validation failed with the provided error.
    ValidationFailed(EgressAdvanceOutput, ValidationErrorType),
}
impl<E> EgressValidateResult<E> {
    /// Converts the EgressAdvanceValidateResult into a Result
    #[inline]
    pub fn into_result(self) -> Result<EgressAdvanceOutput, (EgressAdvanceOutput, E)> {
        match self {
            EgressValidateResult::Ok(output) => Ok(output),
            EgressValidateResult::ValidationFailed(output, err) => Err((output, err)),
        }
    }
}

impl StandardPathView {
    /// Advances the path at egress, without performing any validation.
    ///
    /// See [`Self::advance_egress_with_validator`] for a version of this function that allows
    /// providing a validator to perform extended validation during the advance process.
    #[inline]
    pub fn advance_egress(&mut self) -> Result<EgressAdvanceOutput, AdvanceError> {
        match self.advance_egress_with_validator(NoValidation)? {
            EgressValidateResult::Ok(egress_advance_result) => Ok(egress_advance_result),
            EgressValidateResult::ValidationFailed(..) => {
                unreachable!("NoValidation is Infallible")
            }
        }
    }

    /// Advances the path at the egress of a router.
    ///
    /// This function itself only performs minimal validation.
    ///
    /// Extended validation can be performed by providing a custom validator, which can
    /// for example check the validity of the MAC, check if the segment
    /// change is allowed.
    #[inline]
    pub fn advance_egress_with_validator<ValidatorType, E>(
        &mut self,
        validator: ValidatorType,
    ) -> Result<EgressValidateResult<E>, AdvanceError>
    where
        ValidatorType: AdvanceValidator<Error = E>,
        E: Debug + Display,
    {
        // Extract
        let hop_field_count = self.hop_field_count();
        let curr_hop_idx = self.curr_hop_field_idx() as usize;
        let curr_info_idx = self.curr_info_field_idx() as usize;

        let (seg_idx, start_of_segment, end_of_segment) = self
            .calculate_segment_index(curr_hop_idx)
            .ok_or(AdvanceError::HopOutOfBounds(curr_hop_idx as u8))?;

        if seg_idx != curr_info_idx {
            return Err(AdvanceError::InvalidSegmentIndex {
                expected: seg_idx,
                actual: curr_info_idx,
            });
        }

        let is_final_hop = curr_hop_idx + 1 >= hop_field_count as usize;

        // XXX(ake): In theory the check above guarantees that we can access the current
        // hop and info fields.
        let mut curr_hop_copy = *self
            .hop_field(curr_hop_idx)
            .ok_or(AdvanceError::HopOutOfBounds(curr_hop_idx as u8))?;

        let mut curr_info_copy = *self
            .curr_info_field()
            .ok_or(AdvanceError::InfoOutOfBounds(curr_info_idx as u8))?;

        let in_construction_dir = curr_info_copy.flags().contains(InfoFieldFlags::CONS_DIR);

        // Check

        if is_final_hop {
            // We are at the end of the path, we can't advance further
            return Err(AdvanceError::HopOutOfBounds(curr_hop_idx as u8 + 1));
        }

        if end_of_segment {
            // Segment change should never reach egress, it should have been handled at
            // ingress.
            return Err(AdvanceError::InvalidPathState(
                "Path is at segment end, which must have been handled at ingress",
            ));
        }

        if seg_idx != curr_info_idx {
            return Err(AdvanceError::InvalidSegmentIndex {
                expected: seg_idx,
                actual: curr_info_idx,
            });
        }

        // Process

        let validation_error = validator
            .validate_hop(
                curr_hop_idx,
                &curr_hop_copy,
                &curr_info_copy,
                start_of_segment,
                end_of_segment,
            )
            .err();

        // Update segment_id if we are in construction dir
        if in_construction_dir {
            let curr_segment_id = curr_info_copy.segment_id();
            let hop_mac = curr_hop_copy.mac();
            let new_segment_id = mac_beta_step(curr_segment_id, *hop_mac.as_bytes());
            curr_info_copy.set_segment_id(new_segment_id);
        }

        // Check if we have an SCMP alert at the egress router.
        let scmp_alert = curr_hop_copy
            .flags()
            .normalized_egress_router_alert(in_construction_dir);
        if scmp_alert {
            // Unset the alert flag
            let mut flags = curr_hop_copy.flags();
            match in_construction_dir {
                true => flags.remove(HopFieldFlags::CONS_EGRESS_ROUTER_ALERT),
                false => flags.remove(HopFieldFlags::CONS_INGRESS_ROUTER_ALERT),
            };
            curr_hop_copy.set_flags(flags);
        }

        // Commit
        *self
            .info_field_mut(curr_info_idx)
            .expect("If we can get the current info field without mut, we can get it with mut") =
            curr_info_copy;
        *self
            .hop_field_mut(curr_hop_idx)
            .expect("If we can get the current hop field without mut, we can get it with mut") =
            curr_hop_copy;
        self.set_curr_hop_field((curr_hop_idx + 1) as u8);

        let out = EgressAdvanceOutput {
            scmp_alert,
            egress_interface: curr_hop_copy.egress_interface(&curr_info_copy),
        };

        match validation_error {
            Some(err) => Ok(EgressValidateResult::ValidationFailed(out, err)),
            None => Ok(EgressValidateResult::Ok(out)),
        }
    }
}

/// Error type for invalid hop field MACs during validation.
#[derive(Debug, thiserror::Error, PartialEq, Eq, Clone)]
#[error("invalid hop field MAC: expected {expected:?}, got {actual:?}")]
pub struct InvalidMacError {
    expected: HopFieldMac,
    actual: HopFieldMac,
}

/// A validator for advancing a standard path, only checking the validity of hop field MACs.
///
/// This is not intended to be used in production, as it does not perform any other validation,
/// such as checking the validity of the ingress and egress interfaces, or checking hop field
/// expiry times.
#[derive(Clone)]
pub struct HopMacValidator {
    /// The key used for calculating the expected MACs of the hop field/s to be validated.
    pub key: ForwardingKey,
}
impl AdvanceValidator for HopMacValidator {
    type Error = InvalidMacError;

    #[inline]
    fn validate_hop(
        &self,
        _hop_index: usize,
        hop_field: &HopFieldView,
        info_field: &InfoFieldView,
        _is_segment_start: bool,
        _is_segment_end: bool,
    ) -> Result<(), Self::Error> {
        let mac = hop_field.mac();
        let expected_mac = calculate_hop_mac(
            info_field.segment_id(),
            info_field.timestamp(),
            hop_field.exp_time(),
            hop_field.cons_ingress(),
            hop_field.cons_egress(),
            &self.key,
        );

        if mac.0 != expected_mac {
            Err(InvalidMacError {
                expected: expected_mac.into(),
                actual: mac,
            })
        } else {
            Ok(())
        }
    }

    #[inline]
    fn validate_segment_change(
        &self,
        _hop_index: usize,
        _current_hop_field: &HopFieldView,
        _current_info_field: &InfoFieldView,
        _next_hop_field: &HopFieldView,
        _next_info_field: &InfoFieldView,
    ) -> Result<(), Self::Error> {
        // Note: We can't do any meaningful validation of the segment change without additional
        // information.  Like e.g. if an interface exists, what kind of interface it is
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use proptest::{prelude::Arbitrary, proptest, test_runner::Config};

    use crate::{
        core::{encode::WireEncode, view::View},
        dataplane_path::standard::{
            mac::ForwardingKey,
            model::{
                HopField, StandardPath,
                ptest::{ArbitraryForwardingKeyGenerator, ArbitraryPathContext},
            },
            routing::{HopMacValidator, IngressAdvanceAction},
            view::StandardPathView,
        },
    };

    struct StaticKeyGen;
    impl StaticKeyGen {
        pub const STATIC_KEY: ForwardingKey = [0u8; 16];
    }
    impl ArbitraryForwardingKeyGenerator for StaticKeyGen {
        fn generate(
            &self,
            _field: &HopField,
            _segment_index: usize,
            _segment_hop_index: usize,
            _segment_change: bool,
        ) -> ForwardingKey {
            Self::STATIC_KEY
        }
    }

    /// Validates that we can successfully advance through any valid path, including MAC
    /// checks, forwards and backwards.
    #[test]
    fn should_succeed_advancing_any_path() {
        proptest!(
            Config::with_cases(500),
            |(path in StandardPath::arbitrary_with(ArbitraryPathContext {
                forwarding_key_generator: Some(Arc::new(StaticKeyGen)),
                ..Default::default()
            }))| {
                test_imp(path)?;
            }
        );

        fn test_imp(path: StandardPath) -> Result<(), proptest::test_runner::TestCaseError> {
            let mut view = path.try_encode_to_vec()?;
            let (view, rest) = StandardPathView::try_from_mut_slice(view.as_mut_slice())?;
            if !rest.is_empty() {
                return Err(proptest::test_runner::TestCaseError::Fail(
                    "Encoded path has remaining bytes".into(),
                ));
            }

            advance_path(view, None)?;

            view.try_reverse()
                .expect("Reverse should succeed when we have advanced through the path");

            advance_path(view, None)?;

            Ok(())
        }
    }

    /// Validates that we can successfully reverse the path at any point, allowing it to be
    /// advanced forwards and backwards multiple times.
    #[test]
    fn should_succeed_reversing_at_any_point() {
        proptest!(
            Config::with_cases(500),
            |(
                path in StandardPath::arbitrary_with(ArbitraryPathContext {
                    forwarding_key_generator: Some(Arc::new(StaticKeyGen)),
                    ..Default::default()
                }),
                advance_seed in 0..255u8
            )| {
                test_imp(path, advance_seed)?;
            }
        );

        fn test_imp(
            path: StandardPath,
            advance_seed: u8,
        ) -> Result<(), proptest::test_runner::TestCaseError> {
            let mut view = path.try_encode_to_vec()?;
            let (view, rest) = StandardPathView::try_from_mut_slice(view.as_mut_slice())?;
            if !rest.is_empty() {
                return Err(proptest::test_runner::TestCaseError::Fail(
                    "Encoded path has remaining bytes".into(),
                ));
            }

            // Cap advance to number of hops in path
            let advance_count = advance_seed as usize % (view.hop_field_count() as usize - 1);
            advance_path(view, Some(advance_count as u8))?;

            view.try_reverse().expect(
                "Reverse should succeed when we have advanced through the
                    path",
            );

            advance_path(view, None)?;

            Ok(())
        }
    }

    /// Advances the path until we reach the end or the specified maximum number of steps,
    /// validating the MACs at each step.
    fn advance_path(
        view: &mut StandardPathView,
        max_steps: Option<u8>,
    ) -> Result<(), proptest::prelude::TestCaseError> {
        if view.curr_hop_field_idx() == view.hop_field_count() - 1 {
            // We are at the end of the path, we can't advance further
            return Ok(());
        }

        let static_key = StaticKeyGen::STATIC_KEY;

        let validator = HopMacValidator { key: static_key };

        view.advance_ingress_with_validator(validator.clone(), true)
            .map_err(|e| {
                proptest::test_runner::TestCaseError::Fail(
                    format!("First Advance ingress failed: {e:?}").into(),
                )
            })?
            .into_result()
            .map_err(|(output, err)| {
                proptest::test_runner::TestCaseError::Fail(
                    format!("First Advance ingress validation failed: {err:?}, output: {output:?}")
                        .into(),
                )
            })?;

        view.advance_egress_with_validator(validator.clone())
            .map_err(|e| {
                proptest::test_runner::TestCaseError::Fail(
                    format!("Second Advance egress failed: {e:?}").into(),
                )
            })?
            .into_result()
            .map_err(|(output, err)| {
                proptest::test_runner::TestCaseError::Fail(
                    format!(
                        "Second Advance ingress validation failed: {err:?}, output: {output:?}"
                    )
                    .into(),
                )
            })?;

        let mut steps = 1;
        loop {
            let validator = HopMacValidator { key: static_key };
            let res = view
                .advance_ingress_with_validator(validator.clone(), false)
                .map_err(|e| {
                    proptest::test_runner::TestCaseError::Fail(
                        format!("Advance failed: {e:?}").into(),
                    )
                })?
                .into_result()
                .map_err(|(output, err)| {
                    proptest::test_runner::TestCaseError::Fail(
                        format!("Advance ingress validation failed: {err:?}, output: {output:?}")
                            .into(),
                    )
                })?;

            match res.action {
                // Continue to egress
                IngressAdvanceAction::ContinueEgress { egress_if: _ } => {}
                // We are at the end of the path, we can't advance further
                IngressAdvanceAction::ForwardLocal => {
                    break;
                }
            }

            steps += 1;

            if let Some(max) = max_steps
                && steps >= max
            {
                break;
            }

            view.advance_egress_with_validator(validator.clone())
                .map_err(|e| {
                    proptest::test_runner::TestCaseError::Fail(
                        format!("Advance failed: {e:?}").into(),
                    )
                })?
                .into_result()
                .map_err(|(output, err)| {
                    proptest::test_runner::TestCaseError::Fail(
                        format!("Advance egress validation failed: {err:?}, output: {output:?}")
                            .into(),
                    )
                })?;
        }

        Ok(())
    }
}