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
// Copyright 2025 Mysten Labs
// 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 host address. (IPv4, IPv6, or service address)

use std::{
    fmt::{Debug, Display, Formatter},
    net::{IpAddr, Ipv4Addr, Ipv6Addr},
    str::FromStr,
};

use serde_with::{DeserializeFromStr, SerializeDisplay};
use tinyvec::ArrayVec;

use crate::{
    address::ip_addr::ScionIpAddr,
    core::{
        encode::{InvalidStructureError, WireEncode},
        macros::impl_from,
    },
    scion::address::{AddressParseError, addr::ScionAddr},
};

/// Host Address for SCION packets. Conceptually [IpAddr] plus SCION specific address types.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, SerializeDisplay, DeserializeFromStr,
)]
pub enum ScionHostAddr {
    /// IPv4 address.
    V4(Ipv4Addr),
    /// IPv6 address.
    V6(Ipv6Addr),
    /// SCION service address.
    Svc(ServiceAddr),
}
impl ScionHostAddr {
    /// Creates a HostAddr from an IpAddr.
    #[inline]
    pub const fn from_ip(ip: IpAddr) -> Self {
        match ip {
            IpAddr::V4(v4) => ScionHostAddr::V4(v4),
            IpAddr::V6(v6) => ScionHostAddr::V6(v6),
        }
    }

    /// Returns the address as an `IpAddr` if it is IPv4 or IPv6.
    #[inline]
    pub const fn ip(&self) -> Option<IpAddr> {
        match self {
            ScionHostAddr::V4(v4) => Some(IpAddr::V4(*v4)),
            ScionHostAddr::V6(v6) => Some(IpAddr::V6(*v6)),
            _ => None,
        }
    }

    /// Returns the service address if it is a service address.
    #[inline]
    pub const fn service(&self) -> Option<ServiceAddr> {
        match self {
            ScionHostAddr::Svc(svc) => Some(*svc),
            _ => None,
        }
    }

    /// Returns the address as a [WireHostAddr] for encoding on the wire.
    #[inline]
    pub fn to_wire_host_addr(&self) -> WireHostAddr {
        (*self).into()
    }

    /// Returns true if the SCION Host Address is an IPv4 address
    #[inline]
    pub const fn is_ipv4(&self) -> bool {
        matches!(self, ScionHostAddr::V4(_))
    }

    /// Returns true if the SCION Host Address is an IPv6 address
    #[inline]
    pub const fn is_ipv6(&self) -> bool {
        matches!(self, ScionHostAddr::V6(_))
    }

    /// Returns true if the SCION Host Address is a service address
    #[inline]
    pub const fn is_service(&self) -> bool {
        matches!(self, ScionHostAddr::Svc(_))
    }
}
impl FromStr for ScionHostAddr {
    type Err = AddressParseError;
    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(ipv4) = s.parse::<Ipv4Addr>() {
            Ok(ScionHostAddr::V4(ipv4))
        } else if let Ok(ipv6) = s.parse::<Ipv6Addr>() {
            Ok(ScionHostAddr::V6(ipv6))
        } else if let Ok(svc) = s.parse::<ServiceAddr>() {
            Ok(ScionHostAddr::Svc(svc))
        } else {
            Err(AddressParseError::HostAddr)
        }
    }
}
impl Display for ScionHostAddr {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self {
            ScionHostAddr::V4(v4) => write!(f, "{}", v4)?,
            ScionHostAddr::V6(v6) => write!(f, "{}", v6)?,
            ScionHostAddr::Svc(svc) => write!(f, "{}", svc)?,
        }
        Ok(())
    }
}
impl TryFrom<ScionHostAddr> for Ipv4Addr {
    type Error = &'static str;
    #[inline]
    fn try_from(value: ScionHostAddr) -> Result<Self, Self::Error> {
        match value {
            ScionHostAddr::V4(v4) => Ok(v4),
            _ => Err("HostAddr is not an Ipv4Addr"),
        }
    }
}
impl TryFrom<ScionHostAddr> for Ipv6Addr {
    type Error = &'static str;
    #[inline]
    fn try_from(value: ScionHostAddr) -> Result<Self, Self::Error> {
        match value {
            ScionHostAddr::V6(v6) => Ok(v6),
            _ => Err("HostAddr is not an Ipv6Addr"),
        }
    }
}
impl TryFrom<WireHostAddr> for ScionHostAddr {
    type Error = UnknownAddressTypeError;
    #[inline]
    fn try_from(value: WireHostAddr) -> Result<Self, Self::Error> {
        value.scion_host_addr()
    }
}
impl_from!(IpAddr, ScionHostAddr, |value| ScionHostAddr::from_ip(value));
impl_from!(Ipv4Addr, ScionHostAddr, |value| ScionHostAddr::V4(value));
impl_from!(Ipv6Addr, ScionHostAddr, |value| ScionHostAddr::V6(value));
impl_from!(ServiceAddr, ScionHostAddr, |value| {
    ScionHostAddr::Svc(value)
});
impl_from!(ScionAddr, ScionHostAddr, |value| value.host());
impl_from!(ScionIpAddr, ScionHostAddr, |value| value.host());

/// A SCION service address.
///
/// Service addresses are 16-bit values used to identify services within a SCION AS.
/// They can be either anycast or multicast addresses.
#[derive(Eq, PartialEq, Copy, Clone, Debug, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "proptest", derive(proptest_derive::Arbitrary))]
pub struct ServiceAddr(pub u16);
impl ServiceAddr {
    /// SCION daemon anycast service address (DS_A)
    pub const DAEMON: Self = Self(0x0001);
    /// SCION control-service anycast address (CS_A)
    pub const CONTROL: Self = Self(0x0002);
    /// Wildcard service address (Wildcard_A)
    pub const WILDCARD: Self = Self(0x0010);
    /// Special none service address value.
    pub const NONE: Self = Self(0xffff);

    /// Flag bit indicating whether the address includes multicast
    const MULTICAST_FLAG: u16 = 0x8000;

    /// Returns the raw u16 value of the service address.
    #[inline]
    pub const fn to_u16(&self) -> u16 {
        self.0
    }

    /// Returns true if the service address is multicast, false otherwise.
    #[inline]
    pub const fn is_multicast(&self) -> bool {
        (self.0 & Self::MULTICAST_FLAG) == Self::MULTICAST_FLAG
    }

    /// Creates a new service address as multicast, disabling anycast.
    #[inline]
    pub const fn to_multicast(self) -> Self {
        Self(self.0 | Self::MULTICAST_FLAG)
    }

    /// Creates a new service address as anycast, disabling multicast.
    #[inline]
    pub const fn to_anycast(self) -> Self {
        Self(self.0 & !Self::MULTICAST_FLAG)
    }

    /// Returns true if the service address is anycast, false otherwise.
    #[inline]
    pub const fn is_anycast(&self) -> bool {
        (self.0 & Self::MULTICAST_FLAG) == 0
    }
}
impl Display for ServiceAddr {
    #[inline]
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        match self.to_anycast() {
            ServiceAddr::DAEMON => write!(f, "DS")?,
            ServiceAddr::CONTROL => write!(f, "CS")?,
            ServiceAddr::WILDCARD => write!(f, "Wildcard")?,
            ServiceAddr(value) => write!(f, "<SVC:{value:#06x}>")?,
        }

        if self.is_multicast() {
            write!(f, "_M")?;
        }

        Ok(())
    }
}
impl FromStr for ServiceAddr {
    type Err = &'static str;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        const ERR: &str = "invalid service address";
        let (service, suffix) = s.split_once('_').unwrap_or((s, "A"));

        let address = match service {
            "CS" => ServiceAddr::CONTROL,
            "DS" => ServiceAddr::DAEMON,
            "Wildcard" => ServiceAddr::WILDCARD,
            _ => return Err(ERR),
        };

        match suffix {
            "A" => Ok(address),
            "M" => Ok(address.to_multicast()),
            _ => Err(ERR),
        }
    }
}
impl TryFrom<ScionHostAddr> for ServiceAddr {
    type Error = &'static str;
    #[inline]
    fn try_from(value: ScionHostAddr) -> Result<Self, Self::Error> {
        match value {
            ScionHostAddr::Svc(svc) => Ok(svc),
            _ => Err("HostAddr is not a ServiceAddr"),
        }
    }
}
impl_from!(u16, ServiceAddr, |value| ServiceAddr(value));
impl_from!(ServiceAddr, u16, |value| value.0);
impl_from!(ServiceAddr, WireHostAddr, |value| {
    WireHostAddr::Svc(value)
});

/// Host Address retrieved from the wire. Conceptually [IpAddr] plus SCION specific address types.
///
/// Includes the `Unknown` variant to represent address types that are not recognized by this
/// version of the library or are invalid.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum WireHostAddr {
    /// IPv4 address.
    V4(Ipv4Addr),
    /// IPv6 address.
    V6(Ipv6Addr),
    /// Service address.
    Svc(ServiceAddr),
    /// Unknown address type. Raw bytes.
    Unknown {
        /// Address type identifier.
        id: u8,
        /// Raw address bytes.
        ///
        /// Must be 4, 8, 12, or 16 bytes.
        bytes: ArrayVec<[u8; 16]>,
    },
}
impl WireHostAddr {
    /// Attempts to create an Address from the given type and byte buffer.
    ///
    /// If the advertised address type does not match the expected length of the byte buffer, an
    /// error is returned.
    pub fn try_from_parts(
        addr_type: WireHostAddrType,
        buf: &[u8],
    ) -> Result<Self, HostAddressSizeError> {
        // Note: we are checking the length here, as the address type and advertised length
        // might not match.
        let addr = match addr_type {
            WireHostAddrType::IPV4 => {
                let buf: [u8; 4] = buf.try_into().map_err(|_| {
                    HostAddressSizeError {
                        address_type: addr_type,
                        expected_size: 4,
                        actual_size: buf.len(),
                    }
                })?;
                WireHostAddr::V4(Ipv4Addr::from(buf))
            }
            WireHostAddrType::IPV6 => {
                let buf: [u8; 16] = buf.try_into().map_err(|_| {
                    HostAddressSizeError {
                        address_type: addr_type,
                        expected_size: 16,
                        actual_size: buf.len(),
                    }
                })?;
                WireHostAddr::V6(Ipv6Addr::from(buf))
            }
            WireHostAddrType::Service => {
                let buf: [u8; 4] = buf.try_into().map_err(|_| {
                    HostAddressSizeError {
                        address_type: addr_type,
                        expected_size: 4,
                        actual_size: buf.len(),
                    }
                })?;

                let svc_addr = u16::from_be_bytes([buf[0], buf[1]]);
                let svc_addr = ServiceAddr(svc_addr);
                WireHostAddr::Svc(svc_addr)
            }
            WireHostAddrType::Unknown { id, size } => {
                let bytes = buf.try_into().map_err(|_| {
                    HostAddressSizeError {
                        address_type: addr_type,
                        expected_size: size as usize,
                        actual_size: buf.len(),
                    }
                })?;

                WireHostAddr::Unknown { id, bytes }
            }
        };

        Ok(addr)
    }

    /// Returns an `IpAddr` if the address is IPv4 or IPv6.
    #[inline]
    pub const fn ip(&self) -> Option<IpAddr> {
        match self {
            WireHostAddr::V4(v4) => Some(IpAddr::V4(*v4)),
            WireHostAddr::V6(v6) => Some(IpAddr::V6(*v6)),
            _ => None,
        }
    }

    /// Returns the service address bytes if the address is a service address.
    #[inline]
    pub const fn service(&self) -> Option<ServiceAddr> {
        match self {
            WireHostAddr::Svc(svc) => Some(*svc),
            _ => None,
        }
    }

    /// Returns the address as a [ScionHostAddr] if it is a recognized address type (IPv4, IPv6, or
    /// service) or an error if it is an unknown address type.
    #[inline]
    pub const fn scion_host_addr(&self) -> Result<ScionHostAddr, UnknownAddressTypeError> {
        match self {
            WireHostAddr::V4(v4) => Ok(ScionHostAddr::V4(*v4)),
            WireHostAddr::V6(v6) => Ok(ScionHostAddr::V6(*v6)),
            WireHostAddr::Svc(svc) => Ok(ScionHostAddr::Svc(*svc)),
            WireHostAddr::Unknown { id, .. } => Err(UnknownAddressTypeError { id: *id }),
        }
    }

    /// Returns the address type of the address.
    #[inline]
    pub fn addr_type(&self) -> WireHostAddrType {
        match self {
            WireHostAddr::V4(_) => WireHostAddrType::IPV4,
            WireHostAddr::V6(_) => WireHostAddrType::IPV6,
            WireHostAddr::Svc(_) => WireHostAddrType::Service,
            WireHostAddr::Unknown { id, bytes } => {
                WireHostAddrType::Unknown {
                    id: *id,
                    size: bytes.len() as u8,
                }
            }
        }
    }
}
impl WireEncode for WireHostAddr {
    #[inline]
    fn required_size(&self) -> usize {
        match self {
            WireHostAddr::V4(_) => 4,
            WireHostAddr::V6(_) => 16,
            WireHostAddr::Svc(_) => 4,
            WireHostAddr::Unknown { bytes, .. } => bytes.len(),
        }
    }

    #[inline]
    fn wire_valid(&self) -> Result<(), InvalidStructureError> {
        match self {
            WireHostAddr::V4(_) => Ok(()),
            WireHostAddr::V6(_) => Ok(()),
            WireHostAddr::Svc(_) => Ok(()),
            WireHostAddr::Unknown { bytes, .. } => {
                if bytes.is_empty() {
                    Err("ScionHostAddr::Unknown bytes.len() must be non-zero".into())
                } else if !bytes.len().is_multiple_of(4) {
                    Err("ScionHostAddr::Unknown bytes.len() must be a multiple of 4".into())
                } else {
                    Ok(())
                }
            }
        }
    }

    unsafe fn encode_unchecked(&self, buf: &mut [u8]) -> usize {
        match self {
            WireHostAddr::V4(v4) => {
                let bytes = v4.to_bits().to_be_bytes();
                unsafe {
                    buf.get_unchecked_mut(..4).copy_from_slice(&bytes);
                }
                4
            }
            WireHostAddr::V6(v6) => {
                let bytes = v6.to_bits().to_be_bytes();
                unsafe {
                    buf.get_unchecked_mut(..16).copy_from_slice(&bytes);
                }
                16
            }
            WireHostAddr::Svc(addr) => {
                let val = addr.to_u16().to_be_bytes();
                let bytes = [val[0], val[1], 0, 0];
                unsafe {
                    buf.get_unchecked_mut(..4).copy_from_slice(&bytes);
                }
                4
            }
            WireHostAddr::Unknown { bytes, .. } => {
                let len = bytes.len();
                unsafe {
                    buf.get_unchecked_mut(..len).copy_from_slice(bytes);
                }
                len
            }
        }
    }
}
impl_from!(ScionHostAddr, WireHostAddr, |value| {
    match value {
        ScionHostAddr::V4(v4) => WireHostAddr::V4(v4),
        ScionHostAddr::V6(v6) => WireHostAddr::V6(v6),
        ScionHostAddr::Svc(svc) => WireHostAddr::Svc(svc),
    }
});

/// Host Address types on the wire.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum WireHostAddrType {
    /// IPv4 address.
    IPV4 = 0b0000,
    /// IPv6 address.
    IPV6 = 0b0011,
    /// Service address.
    Service = 0b0100,
    /// Unknown address type.
    Unknown {
        /// Address type identifier.
        id: u8,
        /// Address size in bytes.
        /// Must be 4, 8, 12, or 16.
        size: u8,
    },
}
impl WireHostAddrType {
    /// Returns the size of the address type in bytes.
    #[inline]
    pub const fn size(&self) -> u8 {
        match self {
            WireHostAddrType::IPV4 => 4,
            WireHostAddrType::IPV6 => 16,
            WireHostAddrType::Service => 4,
            WireHostAddrType::Unknown { size, .. } => *size,
        }
    }
}
impl From<u8> for WireHostAddrType {
    #[inline]
    fn from(value: u8) -> Self {
        match value {
            0 => WireHostAddrType::IPV4,
            0b0011 => WireHostAddrType::IPV6,
            0b0100 => WireHostAddrType::Service,
            other => {
                let id = other >> 2;
                let size = ((other & 0b11) + 1) * 4;
                WireHostAddrType::Unknown { id, size }
            }
        }
    }
}
impl From<WireHostAddrType> for u8 {
    #[inline]
    fn from(val: WireHostAddrType) -> Self {
        match val {
            WireHostAddrType::IPV4 => 0,
            WireHostAddrType::IPV6 => 0b0011,
            WireHostAddrType::Service => 0b0100,
            WireHostAddrType::Unknown { id: type_id, size } => {
                (type_id << 2) | (size / 4).saturating_sub(1)
            }
        }
    }
}

/// Errors related to parsing a [WireHostAddr] to a [ScionHostAddr] directly from the wire.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum WireHostAddrError {
    /// The advertised address type does not match the expected length of the byte buffer.
    #[error(transparent)]
    HostAddressSizeError(#[from] HostAddressSizeError),
    /// The address type is unknown and cannot be converted to a ScionHostAddr.
    #[error(transparent)]
    UnknownAddressType(#[from] UnknownAddressTypeError),
}

/// The [WireHostAddr] contained an address type that is not recognized by this version of the
/// library or is invalid.
#[derive(Debug, Clone, PartialEq, Eq, Hash, thiserror::Error)]
#[error("Unknown address type with id {id}")]
pub struct UnknownAddressTypeError {
    /// The unrecognized address type identifier.
    pub id: u8,
}

/// Error indicating a mismatch between expected and actual address sizes.
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error(
    "address size error: address type {address_type:?} expects {expected_size} bytes, got {actual_size} bytes"
)]
pub struct HostAddressSizeError {
    /// Address type
    pub address_type: WireHostAddrType,
    /// Expected buffer size in bytes
    pub expected_size: usize,
    /// Provided buffer size in bytes
    pub actual_size: usize,
}

/// Support for [`proptest::arbitrary`].
#[cfg(feature = "proptest")]
pub mod ptest {
    use ::proptest::prelude::*;

    use super::*;

    /// Configuration for generating arbitrary [`WireHostAddr`] values.
    ///
    /// Controls the relative probability of each variant being generated.
    /// Weights are relative to each other — e.g., setting `v4` and `v6` to `1`
    /// and `svc` and `unknown` to `0` will only generate IPv4 and IPv6 addresses.
    ///
    /// Default weights: `v4 = 3, v6 = 3, svc = 3, unknown = 1`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct ArbitraryWireHostAddrParams {
        /// Weight for generating IPv4 addresses.
        pub v4: u32,
        /// Weight for generating IPv6 addresses.
        pub v6: u32,
        /// Weight for generating service addresses.
        pub svc: u32,
        /// Weight for generating unknown address types.
        pub unknown: u32,
    }
    impl Default for ArbitraryWireHostAddrParams {
        fn default() -> Self {
            Self {
                v4: 3,
                v6: 3,
                svc: 3,
                unknown: 1,
            }
        }
    }

    impl Arbitrary for WireHostAddr {
        type Parameters = ArbitraryWireHostAddrParams;
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
            prop_oneof![
                params.v4 => any::<Ipv4Addr>().prop_map(WireHostAddr::V4),
                params.v6 => any::<Ipv6Addr>().prop_map(WireHostAddr::V6),
                params.svc => any::<ServiceAddr>().prop_map(WireHostAddr::Svc),
                params.unknown => arbitrary_unknown_wire_host_addr(),
            ]
            .boxed()
        }
    }

    fn arbitrary_unknown_wire_host_addr() -> impl Strategy<Value = WireHostAddr> {
        (
            2u8..=3,
            proptest::collection::vec(prop::num::u8::ANY, 4..=16),
        )
            .prop_map(|(id, bytes_vec)| {
                // Take chunks of 4 bytes to keep alignment
                let chunks = bytes_vec.chunks_exact(4);
                let mut bytes = ArrayVec::new();
                for chunk in chunks {
                    for &b in chunk {
                        bytes.push(b);
                    }
                }
                WireHostAddr::Unknown { id, bytes }
            })
    }

    /// Configuration for generating arbitrary [`WireHostAddrType`] values.
    ///
    /// Controls the relative probability of each variant being generated.
    ///
    /// Default weights: `ipv4 = 3, ipv6 = 3, service = 3, unknown = 1`.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
    pub struct ArbitraryWireHostAddrTypeParams {
        /// Weight for generating IPv4 address types.
        pub ipv4: u32,
        /// Weight for generating IPv6 address types.
        pub ipv6: u32,
        /// Weight for generating service address types.
        pub service: u32,
        /// Weight for generating unknown address types.
        pub unknown: u32,
    }
    impl Default for ArbitraryWireHostAddrTypeParams {
        fn default() -> Self {
            Self {
                ipv4: 3,
                ipv6: 3,
                service: 3,
                unknown: 1,
            }
        }
    }

    impl Arbitrary for WireHostAddrType {
        type Parameters = ArbitraryWireHostAddrTypeParams;
        type Strategy = BoxedStrategy<Self>;

        fn arbitrary_with(params: Self::Parameters) -> Self::Strategy {
            prop_oneof![
                params.ipv4 => Just(WireHostAddrType::IPV4),
                params.ipv6 => Just(WireHostAddrType::IPV6),
                params.service => Just(WireHostAddrType::Service),
                params.unknown => arbitrary_unknown_wire_host_addr_type(),
            ]
            .boxed()
        }
    }

    fn arbitrary_unknown_wire_host_addr_type() -> impl Strategy<Value = WireHostAddrType> {
        let size_strategy = prop::num::u8::ANY.prop_map(|size| ((size % 4) + 1) * 4);
        (2u8..=3, size_strategy).prop_map(|(id, size)| WireHostAddrType::Unknown { id, size })
    }
}