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
// 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.
//! Inter AS Routing Simulation of Packets
//!
//! Takes a [ScionTopology] and simulates the traversal of a SCION packet through it.
//!
//! Returns the Action the Packet has to take at the final AS
use anyhow::Context;
use scion_proto::{address::IsdAsn, packet::ScionPacketRaw, path::crypto::ForwardingKey};
use crate::network::scion::{
routing::{
AsRoutingAction, AsRoutingInterfaceState, AsRoutingLinkType, LocalAsRoutingAction,
RoutingLogic, ScionNetworkTime,
},
topology::{ScionLinkType, ScionTopology},
};
/// Simulates traversal in a SCION Network
pub struct ScionNetworkSim;
impl ScionNetworkSim {
/// Simulates the traversal of a SCION packet through the given topology.
///
/// Applies the [RoutingLogic] per AS to processing the packet until it reaches a final
/// decision.
///
/// Returns a [ScionNetworkSimOutput] indicating the next step for the packet.
/// Unexpected errors will be returned as an [anyhow::Error].
///
/// ## Parameters
/// - `topology`: The topology to simulate the traversal on
/// - `scion_packet`: The packet to simulate the traversal for. This packet will be modified
/// during the simulation, so it must be mutable.
/// - `now`: The current network time
/// - `ingress_as`: The AS the packet is processed at
/// - `ingress_interface`: The interface the packet is being processed at, 0 means the packet
/// entered from inside the AS, otherwise it entered from a link to another AS
pub fn simulate_traversal<RoutingImpl: RoutingLogic>(
topology: &ScionTopology,
scion_packet: &mut ScionPacketRaw,
now: ScionNetworkTime,
ingress_asn: IsdAsn,
ingress_interface: u16,
) -> anyhow::Result<ScionNetworkSimOutput> {
let iter = ScionNetworkSimIter::<RoutingImpl>::new(
topology,
scion_packet,
now,
ingress_asn,
ingress_interface,
)?;
let iter_result = iter
.last()
.context("traversal of topology returned none")??;
let local_action = match iter_result.action {
AsRoutingAction::Local(action) => action,
_ => {
return Err(anyhow::anyhow!(
"topology iteration should return a local action, but got: {:?}",
iter_result.action
));
}
};
Ok(ScionNetworkSimOutput {
at_as: iter_result.at_as,
at_ingress_interface: iter_result.at_ingress_interface,
action: local_action,
})
}
/// Returns an iterator over the traversal steps of a SCION packet through the topology.
///
/// ## Parameters
/// - `topology`: The topology to simulate the traversal on
/// - `scion_packet`: The packet to simulate the traversal for. This packet will be modified
/// during the simulation, so it must be mutable.
/// - `now`: The current network time
/// - `ingress_as`: The AS where the packet enters the network
/// - `ingress_interface`: The interface ID where the packet enters the AS if 0 the packet
/// entered from inside the AS, otherwise it entered from a link to another AS
pub fn iter<'input, AsRoutingImpl: RoutingLogic>(
topology: &'input ScionTopology,
scion_packet: &'input mut ScionPacketRaw,
now: ScionNetworkTime,
ingress_asn: IsdAsn,
ingress_interface: u16,
) -> anyhow::Result<ScionNetworkSimIter<'input, AsRoutingImpl>> {
ScionNetworkSimIter::new(topology, scion_packet, now, ingress_asn, ingress_interface)
}
}
/// Iterator over the traversal steps of a SCION packet through a topology.
pub struct ScionNetworkSimIter<'input, AsRoutingImpl: RoutingLogic> {
topology: &'input ScionTopology,
scion_packet: &'input mut ScionPacketRaw,
now: ScionNetworkTime,
current_as: IsdAsn,
current_ingress_interface_id: u16,
/// The forwarding key of the current AS, if it exists. This is needed for the RoutingLogic to
/// make
current_forwarding_key: ForwardingKey,
finished: bool,
_phantom: std::marker::PhantomData<AsRoutingImpl>,
}
impl<'input, AsRoutingImpl: RoutingLogic> ScionNetworkSimIter<'input, AsRoutingImpl> {
/// Creates a new ScionNetworkSimIter starting at the given ingress AS and interface
///
/// ## Parameters
/// - `topology`: The topology to simulate the traversal on
/// - `scion_packet`: The packet to simulate the traversal for. This packet will be modified
/// during the simulation, so it must be mutable.
/// - `now`: The current network time
/// - `ingress_as`: The AS the packet is processed at
/// - `ingress_interface`: The interface the packet is being processed at, 0 means the packet
/// entered from inside the AS.
fn new(
topology: &'input ScionTopology,
scion_packet: &'input mut ScionPacketRaw,
now: ScionNetworkTime,
ingress_as: IsdAsn,
ingress_interface: u16,
) -> anyhow::Result<Self> {
let current_as = topology
.as_map
.get(&ingress_as)
.with_context(|| format!("AS {ingress_as} does not exist in the topology"))?;
if current_as.is_external() {
return Err(anyhow::anyhow!(
"ingress AS {ingress_as} is an external AS, cannot simulate traversal starting from an external AS"
));
}
let current_forwarding_key = current_as
.forwarding_key()
.expect("Simulated ASes always have a forwarding key");
Ok(Self {
topology,
scion_packet,
now,
current_as: ingress_as,
current_ingress_interface_id: ingress_interface,
current_forwarding_key,
finished: false,
_phantom: std::marker::PhantomData,
})
}
/// Returns the AS which will process the packet next.
pub fn get_processing_as(&self) -> IsdAsn {
self.current_as
}
/// Returns the ingress interface ID where the packet will be processed next.
pub fn get_processing_interface_id(&self) -> u16 {
self.current_ingress_interface_id
}
/// Processes the packet at the current AS and interface, advancing the iterator.
/// Returns Ok(None) if all routing steps are finished.
/// Returns [anyhow::Error] on unexpected errors.
fn next_step(&mut self) -> anyhow::Result<Option<ScionNetworkSimIterOutput>> {
if self.finished {
return Ok(None);
}
let processing_as = self.current_as;
let processing_ingress_interface_id = self.current_ingress_interface_id;
// Process the packet at the current AS and interface
let processing_result = AsRoutingImpl::route(
processing_as,
self.scion_packet,
self.current_ingress_interface_id,
self.now,
&self.current_forwarding_key,
|if_id| {
let link = self.topology.scion_link(&processing_as, if_id)?;
let link_type = link.get_link_type(&processing_as)?;
// ScionLinkType states that this is the X of something, InterfaceLinkType states
// that this is a link to X - so needs to swap
let link_type = match link_type {
ScionLinkType::Core => AsRoutingLinkType::LinkToCore,
ScionLinkType::Child => AsRoutingLinkType::LinkToParent,
ScionLinkType::Parent => AsRoutingLinkType::LinkToChild,
ScionLinkType::Peer => AsRoutingLinkType::LinkToPeer,
};
Some(AsRoutingInterfaceState {
link_type,
is_up: link.is_up,
})
},
);
let processing_result: AsRoutingAction = processing_result.into();
// If the decision is to forward to the next hop, we need to prepare the current variables
// for the next iteration by looking up the next AS and interface based on the
// egress interface ID
if let AsRoutingAction::ForwardNextHop {
egress_interface_id,
} = processing_result
{
let uplink = self
.topology
.scion_link(&self.current_as, egress_interface_id)
.with_context(|| {
format!(
"no link for {}#{} to AS does not exist in the topology",
self.current_as, egress_interface_id
)
})?;
let link_partner = uplink.get_peer(&self.current_as).with_context(|| {
format!("link {uplink:?} does not contain AS {}", self.current_as)
})?;
let partner_as = self
.topology
.as_map
.get(&link_partner.isd_as)
.with_context(|| {
format!(
"AS {} does not exist in the topology even though a link to it exists",
self.current_as
)
})?;
// If the next AS is external, we cannot continue the simulation and have to return a
// final result with a ForwardExternal action
if partner_as.is_external() {
self.finished = true; // Mark the simulation as finished as we cannot continue to simulate external ASes
return Ok(Some(ScionNetworkSimIterOutput {
at_as: self.current_as,
at_ingress_interface: self.current_ingress_interface_id,
action: AsRoutingAction::Local(LocalAsRoutingAction::ForwardExternal {
sim_egress_interface_id: egress_interface_id,
extern_ingress_interface_id: link_partner.if_id,
external_as: partner_as.isd_as(),
}),
finished: self.finished,
}));
} else {
// If the next AS is internal, we can continue the simulation by updating the
// current AS and
self.current_as = link_partner.isd_as;
self.current_ingress_interface_id = link_partner.if_id;
self.current_forwarding_key = partner_as
.forwarding_key()
.expect("simulated ASes always have a forwarding key")
}
} else {
// If the decision is not to forward to the next hop, we can finalize the iteration
self.finished = true;
}
// Return the result of processing
Ok(Some(ScionNetworkSimIterOutput {
at_as: processing_as,
at_ingress_interface: processing_ingress_interface_id,
action: processing_result,
finished: self.finished,
}))
}
}
impl<'input, AsRoutingImpl: RoutingLogic> Iterator for ScionNetworkSimIter<'input, AsRoutingImpl> {
type Item = anyhow::Result<ScionNetworkSimIterOutput>;
fn next(&mut self) -> Option<Self::Item> {
self.next_step().transpose()
}
}
/// Result of a single step in of the [ScionNetworkSimIter]
pub struct ScionNetworkSimIterOutput {
/// The ISD-ASN at which the result was produced
pub at_as: IsdAsn,
/// The ingress interface ID at which the ASN received the packet
pub at_ingress_interface: u16,
/// Action which should be taken for the packet at this step
pub action: AsRoutingAction,
/// Iteration is finished, next call to `next()` will return None
pub finished: bool,
}
/// Final result of routing
#[derive(Debug)]
pub struct ScionNetworkSimOutput {
/// The ISD-ASN at which the result was produced
pub at_as: IsdAsn,
/// The ingress interface ID at which the ASN received the packet
pub at_ingress_interface: u16,
/// The decision made for the packet
pub action: LocalAsRoutingAction,
}
#[cfg(test)]
mod tests {
use std::net::Ipv4Addr;
use bytes::{Bytes, BytesMut};
use helper::*;
use scion_proto::{
address::{ScionAddr, ScionAddrV4},
packet::{ByEndpoint, FlowId, ScionPacketRaw},
path::{DataPlanePath, EncodedStandardPath},
scmp::ScmpErrorMessage,
};
use super::*;
use crate::network::scion::topology::ScionAs;
#[test_log::test]
fn should_successfully_route_on_existing_path() {
let mut topology = ScionTopology::new(); // Assume this creates a valid topology
topology
.add_as(ScionAs::new("1-1".parse().unwrap()))
.unwrap()
.add_as(ScionAs::new("1-2".parse().unwrap()))
.unwrap()
.add_as(ScionAs::new("1-3".parse().unwrap()))
.unwrap()
.add_as(ScionAs::new("1-4".parse().unwrap()))
.unwrap();
topology
.add_link("1-1#1 up_to 1-2#2".parse().unwrap())
.unwrap()
.add_link("1-2#3 up_to 1-3#4".parse().unwrap())
.unwrap()
.add_link("1-3#5 up_to 1-4#6".parse().unwrap())
.unwrap();
let src_addr = ScionAddr::V4(ScionAddrV4::new(
"1-1".parse().unwrap(),
Ipv4Addr::new(1, 1, 1, 1),
));
let dst_addr = ScionAddr::V4(ScionAddrV4::new(
"1-4".parse().unwrap(),
Ipv4Addr::new(2, 2, 2, 2),
));
let mut packet = raw_scion_packet(src_addr, dst_addr, &Bytes::from_static(b"Test Payload"));
let result = ScionNetworkSim::simulate_traversal::<MockScionPacketProcessor>(
&topology,
&mut packet,
ScionNetworkTime::from_timestamp_secs(0),
src_addr.isd_asn(),
0,
)
.expect("should not fail to route");
match result.action {
LocalAsRoutingAction::ForwardLocal { target_address } => {
assert_eq!(target_address, dst_addr, "Target address mismatch");
}
_ => {
panic!(
"expected a local forwarding decision, but got: {:?}",
result.action
)
}
}
assert_eq!(result.at_as, dst_addr.isd_asn(), "Final ISD-ASN mismatch");
assert_eq!(
result.at_ingress_interface, 6,
"Final ingress interface ID mismatch"
);
}
#[test_log::test]
fn should_fail_to_route_if_path_is_broken() {
// Note - kind of a mixed test as the mock impl needs to report that the path is broken,
// otherwise the Network Sim would just throw an anyhow error
let mut topology = ScionTopology::new();
let failing_as = "1-2".parse().unwrap();
topology
.add_as(ScionAs::new("1-1".parse().unwrap()))
.unwrap()
.add_as(ScionAs::new(failing_as))
.unwrap()
.add_as(ScionAs::new("1-3".parse().unwrap()))
.unwrap()
.add_as(ScionAs::new("1-4".parse().unwrap()))
.unwrap();
topology
.add_link("1-1#1 up_to 1-2#2".parse().unwrap())
.unwrap()
// .add_link("1-2#3 up_to 1-3#4".parse().unwrap())
// .unwrap()
.add_link("1-3#5 up_to 1-4#6".parse().unwrap())
.unwrap();
let src_addr = ScionAddr::V4(ScionAddrV4::new(
"1-1".parse().unwrap(),
Ipv4Addr::new(1, 1, 1, 1),
));
let dst_addr = ScionAddr::V4(ScionAddrV4::new(
"1-4".parse().unwrap(),
Ipv4Addr::new(2, 2, 2, 2),
));
let mut packet = raw_scion_packet(src_addr, dst_addr, &Bytes::from_static(b"Test Payload"));
let result = ScionNetworkSim::simulate_traversal::<MockScionPacketProcessor>(
&topology,
&mut packet,
ScionNetworkTime::from_timestamp_secs(0),
src_addr.isd_asn(),
0,
)
.expect("should not fail to simulate");
assert!(result.at_as == failing_as, "Final ISD-ASN mismatch");
assert!(
result.at_ingress_interface == 2,
"Final ingress interface ID mismatch"
);
match result.action {
LocalAsRoutingAction::SendSCMPErrorResponse(err) => {
assert!(
matches!(err, ScmpErrorMessage::ParameterProblem(_)),
"expected a ParameterProblem SCMP error"
);
}
_ => panic!("expected a SCMP error response due to broken path"),
}
}
#[test_log::test]
fn should_iterate_as_expected() {
let mut topology = ScionTopology::new(); // Assume this creates a valid topology
let as1 = ScionAs::new("1-1".parse().unwrap());
let as2 = ScionAs::new("1-2".parse().unwrap());
let as3 = ScionAs::new("1-3".parse().unwrap());
let as4 = ScionAs::new("1-4".parse().unwrap());
topology
.add_as(as1.clone())
.unwrap()
.add_as(as2.clone())
.unwrap()
.add_as(as3.clone())
.unwrap()
.add_as(as4.clone())
.unwrap();
topology
.add_link("1-1#1 up_to 1-2#2".parse().unwrap())
.unwrap()
.add_link("1-2#3 up_to 1-3#4".parse().unwrap())
.unwrap()
.add_link("1-3#5 up_to 1-4#6".parse().unwrap())
.unwrap();
let src_addr = ScionAddr::V4(ScionAddrV4::new(as1.isd_as(), Ipv4Addr::new(1, 1, 1, 1)));
let dst_addr = ScionAddr::V4(ScionAddrV4::new(as4.isd_as(), Ipv4Addr::new(2, 2, 2, 2)));
let mut packet = raw_scion_packet(src_addr, dst_addr, &Bytes::from_static(b"Test Payload"));
let mut iter = ScionNetworkSim::iter::<MockScionPacketProcessor>(
&topology,
&mut packet,
ScionNetworkTime::from_timestamp_secs(0),
src_addr.isd_asn(),
0,
)
.expect("should not fail to route");
check_step(
&mut iter,
0,
src_addr.isd_asn(),
AsRoutingAction::ForwardNextHop {
egress_interface_id: 1,
},
false,
);
check_step(
&mut iter,
2,
as2.isd_as(),
AsRoutingAction::ForwardNextHop {
egress_interface_id: 3,
},
false,
);
check_step(
&mut iter,
4,
as3.isd_as(),
AsRoutingAction::ForwardNextHop {
egress_interface_id: 5,
},
false,
);
check_step(
&mut iter,
6,
as4.isd_as(),
AsRoutingAction::Local(LocalAsRoutingAction::ForwardLocal {
target_address: dst_addr,
}),
true,
);
fn check_step(
iter: &mut ScionNetworkSimIter<MockScionPacketProcessor>,
expected_ingress_interface: u16,
expected_isd_asn: IsdAsn,
expected_action: AsRoutingAction,
expected_finished: bool,
) {
let res = iter.next().expect("Step").expect("No error");
assert_eq!(
res.at_ingress_interface, expected_ingress_interface,
"ingress interface should match expected value at this step"
);
assert_eq!(
res.at_as, expected_isd_asn,
"AS should match expected IsdAsn at this step"
);
assert_eq!(
res.action, expected_action,
"routing action should match expected action at this step"
);
assert_eq!(
res.finished, expected_finished,
"finished flag should match expected state at this step"
);
}
// No more steps should be available
assert!(
iter.next().is_none(),
"iter.next() returned Some. no more steps should be available after the last one"
);
}
mod helper {
use bytes::BufMut;
use scion_proto::{
scmp::{ScmpErrorMessage, ScmpParameterProblem},
wire_encoding::{WireDecode, WireEncodeVec},
};
use super::*;
/// Mock implementation of the [ScionPacketProcessingLogic] trait for testing purposes.
///
/// Passes the packet to the the next interface id (e.g. ingress interface id + 1)
/// If the ingress interface ID is 6, it simulates a decision to forward the packet locally
pub struct MockScionPacketProcessor;
impl RoutingLogic for MockScionPacketProcessor {
fn route(
_local_as: IsdAsn,
scion_packet: &mut ScionPacketRaw,
ingress_interface_id: u16,
_now: ScionNetworkTime,
_as_forwarding_key: &ForwardingKey,
interface_link_type_lookup: impl Fn(u16) -> Option<AsRoutingInterfaceState>,
) -> Result<AsRoutingAction, ScmpErrorMessage> {
if ingress_interface_id == 6 {
// Simulate a decision to handle the packet as a SCMP request at the ingress
// interface
return Ok(AsRoutingAction::Local(LocalAsRoutingAction::ForwardLocal {
target_address: scion_packet.headers.address.destination().unwrap(),
}));
}
interface_link_type_lookup(ingress_interface_id + 1) // For mock - Egress must be one higher than ingress
.ok_or_else(|| {
tracing::warn!(
interface_id = ingress_interface_id,
"No link type found for interface ID"
);
ScmpErrorMessage::ParameterProblem(
ScmpParameterProblem::new(
scion_proto::scmp::ParameterProblemCode::UnknownHopFieldConsEgressInterface // note - this would need to be normalized from travel direction but not for mock
, 0
, scion_packet.encode_to_bytes_vec().concat().into())
)
})?;
// For testing, we just return a decision to forward to the next hop
// This is a mock implementation and should be replaced with actual logic
Ok(AsRoutingAction::ForwardNextHop {
egress_interface_id: ingress_interface_id + 1, /* Just incrementing for the
* sake of example */
})
}
}
/// Builds a SCION packet with the given payload and source address.
pub fn raw_scion_packet(
source_addr: ScionAddr,
dest_addr: ScionAddr,
payload: &Bytes,
) -> ScionPacketRaw {
let endpoints = ByEndpoint {
source: source_addr,
destination: dest_addr,
};
// Construct a simple one hop path:
// https://docs.scion.org/en/latest/protocols/scion-header.html#path-type-onehoppath
let mut path_raw = BytesMut::with_capacity(36);
path_raw.put_u32(0x0000_2000);
path_raw.put_slice(&[0_u8; 32]);
let dp_path = DataPlanePath::Standard(
EncodedStandardPath::decode(&mut path_raw.freeze()).unwrap(),
);
ScionPacketRaw::new(
endpoints,
dp_path,
payload.clone(),
0,
FlowId::new(0).unwrap(),
)
.unwrap()
}
}
}