pocketscion 0.5.2

A lightweight SCION network simulator
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
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
// Copyright 2025 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.
//! Representation of a SCION Topology

use std::{
    collections::{BTreeMap, HashMap, btree_map::Entry},
    fmt::{Display, Formatter},
    hash::Hash,
    net::IpAddr,
    str::FromStr,
};

use anyhow::{Context, bail};
use scion_proto::address::{Isd, IsdAsn};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;

use crate::network::scion::trust_store::TrustStore;

pub mod dto;
pub mod visitor;

/// General representation of a SCION Topology.
#[derive(Eq, PartialEq, Debug, Clone, Default)]
pub struct ScionTopology {
    pub(crate) trust_store: TrustStore,
    pub(crate) as_map: BTreeMap<IsdAsn, ScionAs>,
    pub(crate) link_map: BTreeMap<ScionLinkId, ScionLink>,
    pub(crate) router_map: BTreeMap<IsdAsn, Vec<ScionRouter>>,
}

impl ScionTopology {
    /// Creates a new, empty SCION topology.
    pub fn new() -> Self {
        Self {
            trust_store: TrustStore::new(),
            as_map: Default::default(),
            link_map: Default::default(),
            router_map: Default::default(),
        }
    }

    /// Sets the trust store to use for this topology.
    ///
    /// The trust store must contain certificates for all ASes in the topology, or this will return
    /// an error.
    ///
    /// If setting the trust store before adding ASes, the trust store will be used to issue
    /// certificates for ASes as they are added.
    pub fn set_trust_store(&mut self, trust_store: TrustStore) -> anyhow::Result<&mut Self> {
        // Apply certificates from trust store to ASes in the topology, if they exist. If an AS does
        // not have a certificate in the trust store, this will fail
        for sas in self.as_map.values_mut() {
            let sas @ ScionAs::Simulated { .. } = sas else {
                continue;
            };

            // Check that AS identity exists
            trust_store.as_key_pair(&sas.isd_as()).with_context(|| {
                format!(
                    "AS '{}' does not have a certificate in the trust store",
                    sas.isd_as()
                )
            })?;
        }

        self.trust_store = trust_store;

        Ok(self)
    }

    /// Add a new AS to the topology.
    ///
    /// If a Trust Store is set, this will issue a certificate for the AS and add it to the trust
    /// store, or use the existing certificate if it already exists in the trust store.
    ///
    /// Validates that the AS does not already exist.
    pub fn add_as(&mut self, scion_as: ScionAs) -> anyhow::Result<&mut Self> {
        // Ensure AS has identity in the trust store
        let _identity = self.trust_store.get_or_issue_as_key_pair(scion_as.isd_as());

        match self.as_map.entry(scion_as.isd_as()) {
            Entry::Occupied(occupied_entry) => {
                bail!("AS '{}' already exists", occupied_entry.key())
            }
            Entry::Vacant(vacant_entry) => vacant_entry.insert(scion_as),
        };

        Ok(self)
    }

    /// Add a new link to the topology.
    ///
    /// Validates the link according to the following link rules:
    /// 1. A link is bidirectional. (e.g. AS1#0 is Parent of  AS2#0 implies AS2#0 is Child of AS1#0)
    /// 2. Between two ASes, multiple links are allowed if they are all of the same type, with Peer
    ///    links permitted as exceptions.
    /// 3. One Scion interface can only have one link.
    /// 4. A Peer link is allowed between ANY two ASes
    /// 5. Inter ISD links are only allowed: 5.1 Between Core ASes using a Core link type 5.2
    ///    Between Any ASes using a Peer link Type
    /// 6. Interface ID 0 is invalid and may mean unspecified
    pub fn add_link(&mut self, new_link: ScionLink) -> anyhow::Result<&mut Self> {
        // Ensure ASes exist
        let lower_as = self.as_map.get(&new_link.id.lower.isd_as);
        let higher_as = self.as_map.get(&new_link.id.higher.isd_as);

        let lower_as = lower_as
            .ok_or_else(|| anyhow::anyhow!("A AS {} does not exist", new_link.id.lower.isd_as))?;
        let higher_as = higher_as
            .ok_or_else(|| anyhow::anyhow!("A AS {} does not exist", new_link.id.higher.isd_as))?;

        // Validate link rules
        {
            if new_link.id.lower.if_id == 0 || new_link.id.higher.if_id == 0 {
                bail!("Interface ID 0 is invalid");
            }

            // Validate Link Type usage
            let same_isd_link = lower_as.isd_as().isd() == higher_as.isd_as().isd();
            match same_isd_link {
                true => {
                    // | From AS  | To AS     | Allowed Link Type     |
                    // | -------- | --------- | --------------------- |
                    // | Core     | Core      | `Core`, `Peer`        |
                    // | Core     | Non-Core  | `Parent`, `Peer`      |
                    // | Non-Core | Core      | `Child`, `Peer`       |
                    // | Non-Core | Non-Core  | all Except `Core`     |
                    match (lower_as.is_core(), higher_as.is_core(), new_link.link_type) {
                        //(FromAS, ToAS, LinkType)
                        (true, true, ScionLinkType::Core | ScionLinkType::Peer) => {}
                        (true, false, ScionLinkType::Parent | ScionLinkType::Peer) => {}
                        (false, true, ScionLinkType::Child | ScionLinkType::Peer) => {}
                        (
                            false,
                            false,
                            ScionLinkType::Child | ScionLinkType::Parent | ScionLinkType::Peer,
                        ) => {}
                        (from_is_core, to_is_core, link) => {
                            let left = if from_is_core { "Core AS" } else { "AS" };
                            let right = if to_is_core { "Core AS" } else { "AS" };

                            bail!(
                                "{left} '{}' and {right} '{}' can not be linked with '{link}'",
                                lower_as.isd_as(),
                                higher_as.isd_as(),
                            );
                        }
                    }
                }
                false => {
                    // | From AS  | To AS     | Allowed Link Type     |
                    // | -------- | --------- | --------------------- |
                    // | Core     | Core      | `Core`, `Peer`        |
                    // | Core     | Non-Core  | `Peer`                |
                    // | Non-Core | Core      | `Peer`                |
                    // | Non-Core | Non-Core  | `Peer`                |
                    match (lower_as.is_core(), higher_as.is_core(), new_link.link_type) {
                        //(FromAS, ToAS, LinkType)
                        (true, true, ScionLinkType::Core | ScionLinkType::Peer) => {}
                        (_, _, ScionLinkType::Peer) => {}
                        (from_is_core, to_is_core, link) => {
                            let left = if from_is_core { "Core AS" } else { "AS" };
                            let right = if to_is_core { "Core AS" } else { "AS" };

                            bail!(
                                "{left} '{}' and {right} '{}' can not be linked across ISDs with '{link}'",
                                lower_as.isd_as(),
                                higher_as.isd_as(),
                            );
                        }
                    }
                }
            }

            // Rule: One Scion interface can only have one link.
            {
                let lower_as_has_conflict = self
                    .scion_link(&new_link.id.lower.isd_as, new_link.id.lower.if_id)
                    .is_some();

                if lower_as_has_conflict {
                    bail!(
                        "Interface {} of AS '{}' already was assigned to another link",
                        new_link.id.lower.if_id,
                        new_link.id.lower.isd_as
                    );
                };

                let higher_as_has_conflict = self
                    .scion_link(&new_link.id.higher.isd_as, new_link.id.higher.if_id)
                    .is_some();

                if higher_as_has_conflict {
                    bail!(
                        "Interface {} of AS '{}' already was assigned to another link",
                        new_link.id.higher.if_id,
                        new_link.id.higher.isd_as
                    );
                };
            }

            // Rule: Between two ASes, multiple links are allowed if they are all of the same type,
            // with Peer links permitted as exceptions.
            if new_link.link_type != ScionLinkType::Peer {
                for existing_link in self.link_map.values() {
                    // If it's the same link
                    if existing_link.id.higher.isd_as == new_link.id.higher.isd_as
                        && existing_link.id.lower.isd_as == new_link.id.lower.isd_as
                        // But the link type is incompatible
                        && existing_link.link_type != ScionLinkType::Peer
                        && existing_link.link_type != new_link.link_type
                    {
                        // If it is the same link
                        bail!(
                            "Another between '{}' and '{}' already exists and using a different type: '{}'",
                            lower_as.isd_as(),
                            higher_as.isd_as(),
                            existing_link.link_type
                        );
                    }
                }
            }
        }

        // Add Link to the topology
        match self.link_map.entry(new_link.id) {
            Entry::Occupied(occupied_entry) => {
                bail!("Link {} already exists", occupied_entry.key())
            }
            Entry::Vacant(vacant_entry) => vacant_entry.insert(new_link),
        };

        Ok(self)
    }

    /// Add a new router to the topology, associated with the given AS.
    ///
    /// Adding routers is optional, if no routers are added to an AS, it is assumed that the AS has
    /// a single router managing all interfaces.
    pub fn add_router(&mut self, isd_as: IsdAsn, router: ScionRouter) -> anyhow::Result<&mut Self> {
        if !self.as_map.contains_key(&isd_as) {
            bail!("AS '{}' does not exist", isd_as);
        }

        let routers = self.router_map.entry(isd_as).or_default();

        // No other router should have the same interface IDs assigned
        for existing_router in routers.iter() {
            if existing_router.interfaces.collides(&router.interfaces) {
                bail!(
                    "Router for AS '{}' has conflicting interface IDs with an existing router, existing router: {:?}, new router: {:?}",
                    isd_as,
                    existing_router.interfaces,
                    router.interfaces
                );
            }
        }

        routers.push(router);

        Ok(self)
    }
}
// Accessor functions
impl ScionTopology {
    /// Returns an iterator over all scion links of the given AS.
    pub fn iter_scion_links_by_as(&self, isd_as: &IsdAsn) -> impl Iterator<Item = &ScionLink> {
        self.link_map
            .values()
            .filter(|link| link.id.lower.isd_as == *isd_as || link.id.higher.isd_as == *isd_as)
    }

    /// Returns the ScionLink for the given AS and interface ID. If none exists, returns None.
    pub fn scion_link(&self, isd_as: &IsdAsn, interface_id: u16) -> Option<&ScionLink> {
        self.iter_scion_links_by_as(isd_as).find(|link| {
            link.id.lower.if_id == interface_id && link.id.lower.isd_as == *isd_as
                || link.id.higher.if_id == interface_id && link.id.higher.isd_as == *isd_as
        })
    }

    /// Returns a mutable iterator over all scion links of the given AS.
    pub fn mut_iter_scion_links_by_as(
        &mut self,
        isd_as: &IsdAsn,
    ) -> impl Iterator<Item = &mut ScionLink> {
        self.link_map
            .values_mut()
            .filter(|link| link.id.lower.isd_as == *isd_as || link.id.higher.isd_as == *isd_as)
    }

    /// Returns a mutable reference to the ScionLink for the given AS and interface ID. If none
    /// exists, returns None.
    pub fn mut_scion_link(&mut self, isd_as: &IsdAsn, interface_id: u16) -> Option<&mut ScionLink> {
        self.mut_iter_scion_links_by_as(isd_as).find(|link| {
            link.id.lower.if_id == interface_id && link.id.lower.isd_as == *isd_as
                || link.id.higher.if_id == interface_id && link.id.higher.isd_as == *isd_as
        })
    }

    /// Returns the ScionRouter for the given AS and ingress interface ID.
    ///
    /// If no router is found for the given AS a fallback router is returned.
    pub fn get_router(&self, isd_as: &IsdAsn, ingress_interface: u16) -> &ScionRouter {
        static FALLBACK_ROUTER: ScionRouter = ScionRouter {
            interfaces: ScionRouterInterface::Fallback,
            ip: IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED),
        };

        let mut fallback = &FALLBACK_ROUTER;
        for router in self.router_map.get(isd_as).into_iter().flatten() {
            match router.interfaces {
                // If the router is a fallback router, store it as a potential fallback if no better
                // match is found
                ScionRouterInterface::Fallback => {
                    fallback = router;
                }
                // If the router has specific interface IDs assigned, check if it matches the
                // ingress interface
                ScionRouterInterface::Ids(ref ids) => {
                    if ids.contains(&ingress_interface) {
                        return router;
                    }
                }
            }
        }

        fallback
    }
}
// Visualization
impl ScionTopology {
    /// Generate a mermaid graph representation of the topology.
    pub fn format_mermaid(&self) -> String {
        let mut isd_maps: HashMap<Isd, Vec<IsdAsn>> = HashMap::new();
        let mut isd_core_maps: HashMap<Isd, Vec<IsdAsn>> = HashMap::new();

        // Group ASes by ISD
        for scion_as in self.as_map.values() {
            let isd = scion_as.isd_as().isd();

            isd_maps.entry(isd).or_default().push(scion_as.isd_as());

            if scion_as.is_core() {
                isd_core_maps
                    .entry(isd)
                    .or_default()
                    .push(scion_as.isd_as());
            };
        }

        let mut result = String::new();
        result.push_str("graph TD\n");

        // Add ISD subgraphs
        for (isd, as_numbers) in isd_maps.iter() {
            result.push_str(&format!("subgraph ISD{isd} \n"));
            result.push_str(" direction BT\n");
            // Add Core ASes as additional subgraph
            if let Some(core_asns) = isd_core_maps.get(isd) {
                result.push_str(&format!(" subgraph CORE{isd} \n"));
                result.push_str("  direction LR\n");
                for core_asn in core_asns {
                    result.push_str(&format!("  {core_asn}{{{{\"{core_asn}\"}}}}\n"));
                }
                result.push_str(" end\n");
            }

            for asn in as_numbers {
                result.push_str(&format!(" {asn}\n"));
            }

            result.push_str("end\n");
        }

        // Add links
        for link in self.link_map.values() {
            let (uplink, downlink) = link.get_up_and_downlink();

            let connector = match link.link_type {
                ScionLinkType::Peer => format!("-.->|{} Peer {}|", uplink.if_id, downlink.if_id),
                ScionLinkType::Core => format!("==>|{} Core {}|", uplink.if_id, downlink.if_id),
                _ => format!("-->|{} Up {}|", uplink.if_id, downlink.if_id),
            };

            result.push_str(&format!(
                "{} {} {}\n",
                uplink.isd_as, connector, downlink.isd_as
            ));
        }

        result
    }
}

/// Representation of a SCION Autonomous System (AS).
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
pub enum ScionAs {
    /// Representation of a simulated AS, which can be linked to other simulated ASes and external
    /// ASes.
    Simulated {
        /// The ISD-AS number of the SCION AS.
        isd_as: IsdAsn,
        /// Whether the AS is a core AS.
        core: bool,
        /// Forwarding key for the AS - if not defined, falls back to all 0
        forwarding_key: [u8; 16],
    },
    /// Representation of an external AS, external ASes are not simulated
    External {
        /// The ISD-AS number of the SCION AS.
        isd_as: IsdAsn,
        /// Whether the AS is a core AS.
        core: bool,
    },
}

impl ScionAs {
    /// Creates a new core SCION AS.
    pub fn new_core(isd_as: IsdAsn) -> Self {
        Self::Simulated {
            isd_as,
            core: true,
            forwarding_key: Self::default_forwarding_key(isd_as),
        }
    }

    /// Creates a new non-core SCION AS.
    pub fn new(isd_as: IsdAsn) -> Self {
        Self::Simulated {
            isd_as,
            core: false,
            forwarding_key: Self::default_forwarding_key(isd_as),
        }
    }

    /// Creates a new SCION AS outside of the simulation.
    pub fn new_external(isd_as: IsdAsn) -> Self {
        Self::External {
            isd_as,
            core: false,
        }
    }

    /// Creates a new core SCION AS outside of the simulation.
    pub fn new_external_core(isd_as: IsdAsn) -> Self {
        Self::External { isd_as, core: true }
    }

    /// Sets a custom forwarding key for the AS.
    ///
    /// If this AS is an external AS, this is a no-op.
    pub fn with_forwarding_key(mut self, forwarding_key: [u8; 16]) -> Self {
        match &mut self {
            ScionAs::Simulated {
                forwarding_key: fk, ..
            } => *fk = forwarding_key,
            ScionAs::External { .. } => {}
        }
        self
    }

    /// Use the ISD-AS to create the forwarding key.
    fn default_forwarding_key(isd_as: IsdAsn) -> [u8; 16] {
        let mut forwarding_key = [0; 16];
        forwarding_key[..8].copy_from_slice(&isd_as.0.to_be_bytes());
        forwarding_key
    }
}

impl ScionAs {
    /// Returns the ISD-AS number of the AS.
    pub fn isd_as(&self) -> IsdAsn {
        match self {
            ScionAs::Simulated { isd_as, .. } | ScionAs::External { isd_as, .. } => *isd_as,
        }
    }

    /// Returns true if the AS is a core AS, false otherwise.
    pub fn is_core(&self) -> bool {
        match self {
            ScionAs::Simulated { core, .. } | ScionAs::External { core, .. } => *core,
        }
    }

    /// Returns the forwarding key for the AS. For simulated ASes, this is always defined.
    ///
    /// For external ASes, this is None, as the forwarding key is not known.
    pub fn forwarding_key(&self) -> Option<[u8; 16]> {
        match self {
            ScionAs::Simulated { forwarding_key, .. } => Some(*forwarding_key),
            ScionAs::External { .. } => None,
        }
    }

    /// Returns true if the AS is an external AS, false otherwise.
    pub fn is_external(&self) -> bool {
        matches!(self, ScionAs::External { .. })
    }
}

impl From<IsdAsn> for ScionAs {
    fn from(isd_as: IsdAsn) -> Self {
        Self::new(isd_as)
    }
}

/// Globally unique identifier for a SCION interface.
#[derive(Hash, Copy, Eq, PartialEq, Debug, Clone, PartialOrd, Ord, ToSchema)]
#[schema(example = "1-1#0")]
pub struct ScionGlobalInterfaceId {
    /// ISD-AS number of the AS the interface belongs to.
    pub isd_as: IsdAsn,
    /// Interface ID within the AS.
    pub if_id: u16,
}

impl Serialize for ScionGlobalInterfaceId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(&format!("{}#{}", self.isd_as, self.if_id))
    }
}

impl<'de> Deserialize<'de> for ScionGlobalInterfaceId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        ScionGlobalInterfaceId::from_str(&s).map_err(serde::de::Error::custom)
    }
}

impl Display for ScionGlobalInterfaceId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}#{}", self.isd_as, self.if_id)
    }
}

impl FromStr for ScionGlobalInterfaceId {
    type Err = anyhow::Error;

    /// Parses a string representation of a SCION interface ID.
    /// Format: "AS#IF"
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = s.split('#').collect();
        if parts.len() != 2 {
            bail!(
                "invalid AS interface format: '{}' expected ISD-AS#IF (1-1#1)",
                s
            );
        }

        let isd_as = IsdAsn::from_str(parts[0])?;

        let if_id = parts[1]
            .parse::<u16>()
            .context("could not convert interface id to number")?;

        Ok(Self { isd_as, if_id })
    }
}

/// Globally unique identifier for a SCION link.
#[derive(Hash, Copy, Eq, PartialEq, Debug, Clone, PartialOrd, Ord)]
#[non_exhaustive]
pub struct ScionLinkId {
    pub(crate) lower: ScionGlobalInterfaceId,
    pub(crate) higher: ScionGlobalInterfaceId,
}

impl ScionLinkId {
    /// Creates a new SCION link ID, ensuring that the lower AS is always first.
    pub fn new(
        from_as: IsdAsn,
        from_interface_id: u16,
        to_as: IsdAsn,
        to_interface_id: u16,
    ) -> anyhow::Result<Self> {
        match from_as.cmp(&to_as) {
            std::cmp::Ordering::Less => {
                Ok(Self {
                    lower: ScionGlobalInterfaceId {
                        isd_as: from_as,
                        if_id: from_interface_id,
                    },
                    higher: ScionGlobalInterfaceId {
                        isd_as: to_as,
                        if_id: to_interface_id,
                    },
                })
            }
            std::cmp::Ordering::Greater => {
                Ok(Self {
                    higher: ScionGlobalInterfaceId {
                        isd_as: from_as,
                        if_id: from_interface_id,
                    },
                    lower: ScionGlobalInterfaceId {
                        isd_as: to_as,
                        if_id: to_interface_id,
                    },
                })
            }
            std::cmp::Ordering::Equal => bail!("Cannot create a link between the same AS"),
        }
    }
}

impl Display for ScionLinkId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} <-> {}", self.lower, self.higher)
    }
}

/// Represents a link between two ASes in the SCION topology.
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
pub struct ScionLink {
    pub(crate) id: ScionLinkId,
    /// Link Type from perspective of the lower AS \
    /// e.g. "Lower AS is {link_type} of Higher AS"
    pub(crate) link_type: ScionLinkType,

    pub(crate) is_up: bool,
}

impl Display for ScionLink {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.link_type {
            ScionLinkType::Peer => write!(f, "{} peer {}", self.id.lower, self.id.higher),
            ScionLinkType::Parent => write!(f, "{} parent_of {}", self.id.lower, self.id.higher),
            ScionLinkType::Child => write!(f, "{} child_of {}", self.id.lower, self.id.higher),
            ScionLinkType::Core => write!(f, "{} core {}", self.id.lower, self.id.higher),
        }
    }
}

impl FromStr for ScionLink {
    type Err = anyhow::Error;

    /// Parses a string representation of a link into a `ScionLink`. \
    /// Format: "AS1#IF1 LinkType AS2#IF2" \
    /// 1 parent_of 2
    fn from_str(string: &str) -> Result<Self, Self::Err> {
        let parts: Vec<&str> = string.split_whitespace().collect();
        if parts.len() != 3 {
            bail!(
                "Invalid link format. Expected 'AS1#IF1 LinkType AS2#IF2' - found '{:?}'",
                parts
            );
        }

        let from_part = parts[0];
        let link_type_str = parts[1];
        let to_part = parts[2];

        let ScionGlobalInterfaceId {
            isd_as: from_as,
            if_id: from_interface_id,
        } = from_part.parse()?;

        let ScionGlobalInterfaceId {
            isd_as: to_as,
            if_id: to_interface_id,
        } = to_part.parse()?;

        let link_type = match link_type_str.to_lowercase().as_str() {
            "peer" => ScionLinkType::Peer,
            "down_to" => ScionLinkType::Parent,
            "parent_of" => ScionLinkType::Parent,
            "up_to" => ScionLinkType::Child,
            "child_of" => ScionLinkType::Child,
            "core" => ScionLinkType::Core,
            _ => bail!("Unknown link type: {}", link_type_str),
        };

        Self::new(
            from_as,
            from_interface_id,
            link_type,
            to_as,
            to_interface_id,
        )
    }
}

impl ScionLink {
    /// Creates a new `ScionLink` with the given parameters.
    ///
    /// `link_type` is from perspective of `from_as`. e.g\
    /// e.g. "from_as is {link_type} of to_as"
    pub fn new(
        from_as: IsdAsn,
        from_interface_id: u16,
        link_type: ScionLinkType,
        to_as: IsdAsn,
        to_interface_id: u16,
    ) -> anyhow::Result<Self> {
        if from_interface_id == 0 || to_interface_id == 0 {
            bail!("Interface ID 0 is invalid for a SCION link");
        }

        let link_id = ScionLinkId::new(from_as, from_interface_id, to_as, to_interface_id)?;

        // Normalize the link type based on the AS order - if from as is the lower as, link type
        // stays the same.
        let normalized_type = match from_as == link_id.lower.isd_as {
            true => link_type,
            false => link_type.into_swapped_direction(),
        };

        Ok(Self {
            id: link_id,
            link_type: normalized_type,
            is_up: true,
        })
    }

    /// Returns the link type from the perspective of the given AS.
    ///
    /// If the ISD-AS Number does not match either the lower or higher AS of the link, returns None.
    ///
    /// E.g. "The given AS is {link_type} of the other AS"
    pub fn get_link_type(&self, asn: &IsdAsn) -> Option<ScionLinkType> {
        if self.id.lower.isd_as == *asn {
            return Some(self.link_type);
        } else if self.id.higher.isd_as == *asn {
            return Some(self.link_type.into_swapped_direction());
        }

        None
    }

    /// Returns the peer for the given AS.
    ///
    /// If the ISD-AS Number does not match either AS of the link, returns None.
    pub fn get_peer(&self, isd_as: &IsdAsn) -> Option<ScionGlobalInterfaceId> {
        self.get_directed_from(isd_as).map(|link| link.to)
    }

    /// Returns the ScionGlobalInterfaceId for the given AS
    ///
    /// If the ISD-AS Number does not match either AS of the link, returns None.
    pub fn get_own(&self, isd_as: &IsdAsn) -> Option<ScionGlobalInterfaceId> {
        self.get_directed_from(isd_as).map(|link| link.from)
    }

    /// Returns the link in directed format from the given AS
    ///
    /// If the ISD-AS Number does not match either AS of the link, returns None.
    pub fn get_directed_from(&self, from_as: &IsdAsn) -> Option<DirectedScionLink> {
        if self.id.lower.isd_as == *from_as {
            Some(DirectedScionLink {
                from: self.id.lower,
                to: self.id.higher,
                link_type: self.link_type,
            })
        } else if self.id.higher.isd_as == *from_as {
            Some(DirectedScionLink {
                from: self.id.higher,
                to: self.id.lower,
                link_type: self.link_type.into_swapped_direction(),
            })
        } else {
            None
        }
    }

    /// Returns the link in directed format to the given AS
    ///
    /// If the ISD-AS Number does not match either AS of the link, returns None.
    pub fn get_directed_to(&self, to_as: &IsdAsn) -> Option<DirectedScionLink> {
        if self.id.higher.isd_as == *to_as {
            Some(DirectedScionLink {
                from: self.id.lower,
                to: self.id.higher,
                link_type: self.link_type,
            })
        } else if self.id.lower.isd_as == *to_as {
            Some(DirectedScionLink {
                from: self.id.higher,
                to: self.id.lower,
                link_type: self.link_type.into_swapped_direction(),
            })
        } else {
            None
        }
    }

    /// Returns the up and downlink interface AS from the Link \
    /// (Uplink, Downlink)
    ///
    /// If Connection is Peer or Core, just returns \
    /// (Lower, Higher)
    pub fn get_up_and_downlink(&self) -> (ScionGlobalInterfaceId, ScionGlobalInterfaceId) {
        match self.link_type {
            ScionLinkType::Parent => (self.id.higher, self.id.lower),
            ScionLinkType::Child => (self.id.lower, self.id.higher),
            _ => (self.id.lower, self.id.higher),
        }
    }

    /// Set whether the link is up or down.
    pub fn set_is_up(&mut self, is_up: bool) {
        self.is_up = is_up;
    }
}

/// Directed Variant of a [ScionLink]
#[derive(Hash, Eq, PartialEq, Debug, Clone)]
pub struct DirectedScionLink {
    pub(crate) from: ScionGlobalInterfaceId,
    /// Link Type - from is `{link_type}` of to
    pub(crate) link_type: ScionLinkType,
    pub(crate) to: ScionGlobalInterfaceId,
}

/// Link type of a SCION link
#[derive(Hash, Eq, PartialEq, Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum ScionLinkType {
    /// ASes are Peers without any parent-child relationship.
    Peer,
    /// AS is the Parent (Uplink) of the Other
    Parent,
    /// AS is the Child (Downlink) of the Other
    Child,
    /// The Link is between Core ASes.
    Core,
}

impl Display for ScionLinkType {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ScionLinkType::Peer => write!(f, "Peer"),
            ScionLinkType::Parent => write!(f, "Parent"),
            ScionLinkType::Child => write!(f, "Child"),
            ScionLinkType::Core => write!(f, "Core"),
        }
    }
}

impl ScionLinkType {
    /// Returns the opposite direction of the link type.
    pub fn into_swapped_direction(&self) -> Self {
        match self {
            ScionLinkType::Peer => ScionLinkType::Peer,
            ScionLinkType::Parent => ScionLinkType::Child,
            ScionLinkType::Child => ScionLinkType::Parent,
            ScionLinkType::Core => ScionLinkType::Core,
        }
    }
}

/// Representation of a SCION Router, which can be associated with an AS in the topology.
#[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize, ToSchema)]
pub struct ScionRouter {
    /// The interface IDs of the router within the AS.
    pub interfaces: ScionRouterInterface,
    /// The IP address of the router.

    #[schema(value_type = String, example = "192.168.1.1")]
    pub ip: IpAddr,
}
impl ScionRouter {
    /// Creates a new SCION router with the given interface IDs and IP address.
    pub fn new(interfaces: Vec<u16>, ip: IpAddr) -> Self {
        Self {
            interfaces: ScionRouterInterface::Ids(interfaces),
            ip,
        }
    }

    /// Creates a new SCION router with the given IP address and no associated interfaces.
    ///
    /// This router can be used as a default router for an AS, which is used if no other router is
    /// explicitly associated with the ingress interface.
    pub fn new_fallback(ip: IpAddr) -> Self {
        Self {
            interfaces: ScionRouterInterface::Fallback,
            ip,
        }
    }
}

/// Defines the interfaces associated with a SCION router.
#[derive(Eq, PartialEq, Debug, Clone, Serialize, Deserialize, ToSchema)]
pub enum ScionRouterInterface {
    /// The router is not explicitly associated with any interface, and should be used as a fallback
    /// for the AS unless another router is explicitly assigned.
    Fallback,
    /// The router is associated with the given interface IDs.
    Ids(Vec<u16>),
}
impl ScionRouterInterface {
    /// Checks if the interface id collides with this interface id.
    pub fn collides(&self, other: &ScionRouterInterface) -> bool {
        match (self, other) {
            (ScionRouterInterface::Fallback, ScionRouterInterface::Fallback) => true,
            (ScionRouterInterface::Ids(ids), ScionRouterInterface::Ids(other_ids)) => {
                ids.iter().any(|id| other_ids.contains(id))
            }
            _ => false,
        }
    }
}

/// Helper struct to quickly look up links in a topology.
pub struct FastTopologyLookup<'topo> {
    pub(crate) topology: &'topo ScionTopology,
    pub(crate) as_to_link_map: HashMap<IsdAsn, Vec<&'topo ScionLink>>,

    // Contains all peer links for the given AS
    #[allow(unused)]
    pub(crate) as_to_peer_link_map: HashMap<IsdAsn, Vec<&'topo ScionLink>>,
}

impl<'topo> FastTopologyLookup<'topo> {
    /// Creates a new FastTopologyLookup from the given topology.
    pub fn new(topology: &'topo ScionTopology) -> Self {
        let mut as_to_link_map: HashMap<IsdAsn, Vec<&'topo ScionLink>> = HashMap::new();
        let mut as_to_peer_link_map: HashMap<IsdAsn, Vec<&'topo ScionLink>> = HashMap::new();

        for (link_id, link) in &topology.link_map {
            let left_as = link_id.lower.isd_as;
            as_to_link_map.entry(left_as).or_default().push(link);

            let right_as = link_id.higher.isd_as;
            as_to_link_map.entry(right_as).or_default().push(link);

            if link.link_type == ScionLinkType::Peer {
                as_to_peer_link_map.entry(left_as).or_default().push(link);
            }
        }
        Self {
            topology,
            as_to_link_map,
            as_to_peer_link_map,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    mod scion_link_tests {
        use super::*;

        #[test]
        fn should_parse_and_stringify() -> anyhow::Result<()> {
            let link = ScionLink::from_str("1-1#1 core 1-2#12")?;
            assert_eq!(link.to_string(), "1-1#1 core 1-2#12");

            let link = ScionLink::from_str("1-1#1 parent_of 1-2#12")?;
            assert_eq!(link.to_string(), "1-1#1 parent_of 1-2#12");
            Ok(())
        }

        #[test]
        fn should_hold_correct_data_when_parsed() -> anyhow::Result<()> {
            let link = ScionLink::from_str("1-01#1 core 1-02#12")?;
            assert_eq!(link.link_type, ScionLinkType::Core);
            assert_eq!(link.id.lower.isd_as, IsdAsn::from_str("1-01")?);
            assert_eq!(link.id.lower.if_id, 1);
            assert_eq!(link.id.higher.isd_as, IsdAsn::from_str("1-02")?);
            assert_eq!(link.id.higher.if_id, 12);
            Ok(())
        }

        #[test]
        fn should_correctly_normalize_link_order_and_direction() -> anyhow::Result<()> {
            // Should not touch the order or type
            let isd_as_lower = IsdAsn::from_str("1-01")?;
            let isd_as_higher = IsdAsn::from_str("1-02")?;

            let link = ScionLink::from_str("1-01#1 parent_of 1-02#12")?;
            assert_eq!(link.link_type, ScionLinkType::Parent);
            assert_eq!(link.id.lower.isd_as, isd_as_lower);
            assert_eq!(link.id.lower.if_id, 1);
            assert_eq!(link.id.higher.isd_as, isd_as_higher);
            assert_eq!(link.id.higher.if_id, 12);

            // Should swap the order and type
            let swapped_link = ScionLink::from_str("1-02#12 child_of 1-01#1")?;
            assert_eq!(swapped_link.link_type, ScionLinkType::Parent);
            assert_eq!(swapped_link.id.lower.isd_as, isd_as_lower);
            assert_eq!(swapped_link.id.lower.if_id, 1);
            assert_eq!(swapped_link.id.higher.isd_as, isd_as_higher);
            assert_eq!(swapped_link.id.higher.if_id, 12);

            Ok(())
        }

        #[test]
        fn should_disallow_interface_id_0() -> anyhow::Result<()> {
            // Should not allow interface ID 0
            assert!(ScionLink::from_str("1-01#0 parent_of 1-02#12").is_err());
            assert!(ScionLink::from_str("1-01#1 parent_of 1-02#0").is_err());
            Ok(())
        }
    }
}