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
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
// Internet2 addresses with support for Tor v3
//
// Written in 2019-2022 by
//     Dr. Maxim Orlovsky <orlovsky@lnp-bp.org>
//     Martin Habovstiak <martin.habovstiak@gmail.com>
//
// To the extent possible under law, the author(s) have dedicated all copyright
// and related and neighboring rights to this software to the public domain
// worldwide. This software is distributed without any warranty.
//
// You should have received a copy of the MIT License along with this software.
// If not, see <https://opensource.org/licenses/MIT>.

use std::cmp::Ordering;
#[cfg(feature = "tor")]
use std::convert::TryFrom;
use std::fmt;
use std::net::{
    IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6,
};
use std::num::ParseIntError;
use std::str::FromStr;

#[cfg(feature = "tor")]
use torut::onion::{OnionAddressV3, TorPublicKeyV3};

/// Address type do not support ONION address format and can be used only with
/// IPv4 or IPv6 addresses
#[derive(
    Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Display, Error
)]
#[display(doc_comments)]
pub struct NoOnionSupportError;

/// Errors during address string parse process
#[derive(Debug, Display, Error, From)]
#[display(doc_comments)]
pub enum AddrParseError {
    /// Wrong port number; must be a 16-bit unsigned integer number
    #[from(ParseIntError)]
    WrongPortNumber,

    /// Can't recognize IPv4, v6 or Onion v2/v3 address in string "{_0}"
    WrongAddrFormat(String),

    /// Wrong format of socket address string "{_0}"; use
    /// \<inet_address\>\[:\<port\>\]
    WrongSocketFormat(String),

    /// Wrong format of extended socket address string "{_0}"; use
    /// \<transport\>://\<inet_address\>\[:\<port\>\]
    WrongSocketExtFormat(String),

    /// Unknown transport protocol "{_0}"
    UnknownProtocolError(String),

    /// Error parsing onion address
    #[cfg(feature = "tor")]
    #[display(inner)]
    #[from]
    OnionAddressError(torut::onion::OnionAddressParseError),

    /// Tor addresses are not supported; consider compiling with `tor` feature
    #[from(NoOnionSupportError)]
    NeedsTorFeature,
}

/// A universal address covering IPv4, IPv6 and Tor in a single byte sequence
/// of 32 bytes.
///
/// Holds either:
/// * IPv4-to-IPv6 address
/// * IPv6 address
/// * Tor Onion address (V3 only)
///
/// NB: we are using [`TorPublicKeyV3`] instead of `OnionAddressV3`, since
/// `OnionAddressV3` keeps checksum and other information which can be
/// reconstructed from [`TorPublicKeyV3`]. The 2-byte checksum in
/// `OnionAddressV3` is designed for human-readable part that checks that the
/// address was typed in correctly. In computer-stored digital data it may be
/// deterministically regenerated and does not add any additional security.
#[derive(Clone, Copy, PartialEq, Eq, Debug, From, Display)]
#[cfg_attr(
    all(feature = "serde", feature = "serde_str_helpers"),
    derive(Serialize, Deserialize),
    serde(
        try_from = "serde_str_helpers::DeserBorrowStr",
        into = "String",
        crate = "serde_crate"
    )
)]
#[cfg_attr(
    all(feature = "serde", not(feature = "serde_str_helpers")),
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[display(inner)]
#[non_exhaustive] // Required since we use feature-gated enum variants
pub enum InetAddr {
    /// IP address of V4 standard
    #[from]
    IPv4(Ipv4Addr),

    /// IP address of V6 standard
    #[from]
    IPv6(Ipv6Addr),

    /// Tor address of V3 standard
    #[cfg(feature = "tor")]
    #[from]
    Tor(TorPublicKeyV3),
}

impl PartialOrd for InetAddr {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self, other) {
            (InetAddr::IPv4(addr1), InetAddr::IPv4(addr2)) => {
                addr1.partial_cmp(addr2)
            }
            (InetAddr::IPv6(addr1), InetAddr::IPv6(addr2)) => {
                addr1.partial_cmp(addr2)
            }
            #[cfg(feature = "tor")]
            (InetAddr::Tor(addr1), InetAddr::Tor(addr2)) => {
                addr1.partial_cmp(addr2)
            }
            (InetAddr::IPv4(_), _) => Some(Ordering::Greater),
            (_, InetAddr::IPv4(_)) => Some(Ordering::Less),
            #[cfg(feature = "tor")]
            (InetAddr::IPv6(_), _) => Some(Ordering::Greater),
            #[cfg(feature = "tor")]
            (_, InetAddr::IPv6(_)) => Some(Ordering::Less),
        }
    }
}

impl Ord for InetAddr {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap_or(Ordering::Equal)
    }
}

// We need this since TorPublicKeyV3 does not implement Hash
#[allow(clippy::derive_hash_xor_eq)]
impl std::hash::Hash for InetAddr {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            InetAddr::IPv4(ipv4) => ipv4.hash(state),
            InetAddr::IPv6(ipv6) => ipv6.hash(state),
            #[cfg(feature = "tor")]
            InetAddr::Tor(torv3) => torv3.as_bytes().hash(state),
        }
    }
}

impl InetAddr {
    /// Returns an IPv6 address, constructed from IPv4 data; or, if Onion
    /// address is used, [`Option::None`]
    #[inline]
    pub fn ipv6_addr(self) -> Option<Ipv6Addr> {
        match self {
            InetAddr::IPv4(ipv4_addr) => Some(ipv4_addr.to_ipv6_mapped()),
            InetAddr::IPv6(ipv6_addr) => Some(ipv6_addr),
            #[cfg(feature = "tor")]
            _ => None,
        }
    }

    /// Returns an IPv4 address, if any, or [`Option::None`]
    #[inline]
    pub fn ipv4_addr(self) -> Option<Ipv4Addr> {
        match self {
            InetAddr::IPv4(ipv4_addr) => Some(ipv4_addr),
            InetAddr::IPv6(ipv6_addr) => ipv6_addr.to_ipv4(),
            #[cfg(feature = "tor")]
            _ => None,
        }
    }

    /// Determines whether provided address is a Tor address. Always returns
    /// `false` (the library is built without `tor` feature; use it to
    /// enable Tor addresses).
    #[cfg(not(feature = "tor"))]
    #[inline]
    pub fn is_tor(self) -> bool { false }

    /// Always returns [`Option::None`] (the library is built without `tor`
    /// feature; use it to enable Tor addresses).
    #[cfg(not(feature = "tor"))]
    #[inline]
    pub fn onion_address(self) -> Option<()> { None }

    /// Determines whether provided address is a Tor address
    #[cfg(feature = "tor")]
    #[inline]
    pub fn is_tor(self) -> bool { matches!(self, InetAddr::Tor(_)) }

    /// Returns Onion v3 address, if any, or [`Option::None`]
    #[cfg(feature = "tor")]
    #[inline]
    pub fn onion_address(self) -> Option<OnionAddressV3> {
        match self {
            InetAddr::IPv4(_) | InetAddr::IPv6(_) => None,
            InetAddr::Tor(key) => Some(OnionAddressV3::from(&key)),
        }
    }
}

impl Default for InetAddr {
    #[inline]
    fn default() -> Self { InetAddr::IPv4(Ipv4Addr::from(0)) }
}

#[cfg(feature = "tor")]
impl TryFrom<InetAddr> for IpAddr {
    type Error = NoOnionSupportError;
    #[inline]
    fn try_from(addr: InetAddr) -> Result<Self, Self::Error> {
        Ok(match addr {
            InetAddr::IPv4(addr) => IpAddr::V4(addr),
            InetAddr::IPv6(addr) => IpAddr::V6(addr),
            #[cfg(feature = "tor")]
            InetAddr::Tor(_) => return Err(NoOnionSupportError),
        })
    }
}

#[cfg(not(feature = "tor"))]
impl From<InetAddr> for IpAddr {
    #[inline]
    fn from(addr: InetAddr) -> Self {
        match addr {
            InetAddr::IPv4(addr) => IpAddr::V4(addr),
            InetAddr::IPv6(addr) => IpAddr::V6(addr),
        }
    }
}

impl From<IpAddr> for InetAddr {
    #[inline]
    fn from(value: IpAddr) -> Self {
        match value {
            IpAddr::V4(v4) => InetAddr::from(v4),
            IpAddr::V6(v6) => InetAddr::from(v6),
        }
    }
}

#[cfg(feature = "tor")]
impl From<OnionAddressV3> for InetAddr {
    #[inline]
    fn from(addr: OnionAddressV3) -> Self {
        InetAddr::Tor(addr.get_public_key())
    }
}

#[cfg(feature = "stringly_conversions")]
impl_try_from_stringly_standard!(InetAddr);
#[cfg(feature = "stringly_conversions")]
impl_into_stringly_standard!(InetAddr);

impl FromStr for InetAddr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        #[cfg(feature = "tor")]
        match (IpAddr::from_str(s), OnionAddressV3::from_str(s)) {
            (Ok(_), Ok(_)) => {
                Err(AddrParseError::WrongAddrFormat(s.to_owned()))
            }
            (Ok(ip_addr), _) => Ok(Self::from(ip_addr)),
            (_, Ok(onionv3)) => Ok(Self::from(onionv3)),
            _ => Err(AddrParseError::WrongAddrFormat(s.to_owned())),
        }

        #[cfg(not(feature = "tor"))]
        match IpAddr::from_str(s) {
            Ok(ip_addr) => Ok(InetAddr::from(ip_addr)),
            _ => Err(AddrParseError::NeedsTorFeature),
        }
    }
}

// Yes, I checked that onion addresses don't need to optimize ownership of input
// String.
#[cfg(feature = "parse_arg")]
impl parse_arg::ParseArgFromStr for InetAddr {
    fn describe_type<W: std::fmt::Write>(mut writer: W) -> std::fmt::Result {
        #[cfg(not(feature = "tor"))]
        {
            write!(writer, "IPv4 or IPv6 address")
        }
        #[cfg(feature = "tor")]
        {
            write!(writer, "IPv4, IPv6, or Tor (onion) address")
        }
    }
}

impl From<[u8; 4]> for InetAddr {
    #[inline]
    fn from(value: [u8; 4]) -> Self { InetAddr::from(Ipv4Addr::from(value)) }
}

impl From<[u8; 16]> for InetAddr {
    #[inline]
    fn from(value: [u8; 16]) -> Self { InetAddr::from(Ipv6Addr::from(value)) }
}

impl From<[u16; 8]> for InetAddr {
    #[inline]
    fn from(value: [u16; 8]) -> Self { InetAddr::from(Ipv6Addr::from(value)) }
}

/// A universal address covering IPv4, IPv6 and Tor in a single byte sequence
/// of 32 bytes, which may contain optional port number part.
#[derive(Clone, Copy, PartialEq, Eq, Debug, From)]
#[cfg_attr(
    all(feature = "serde", feature = "serde_str_helpers"),
    derive(Serialize, Deserialize),
    serde(
        try_from = "serde_str_helpers::DeserBorrowStr",
        into = "String",
        crate = "serde_crate"
    )
)]
#[cfg_attr(
    all(feature = "serde", not(feature = "serde_str_helpers")),
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[non_exhaustive] // Required since we use feature-gated enum variants
pub enum PartialSocketAddr {
    /// IP address of V4 standard with optional port number
    IPv4(Ipv4Addr, Option<u16>),

    /// IP address of V6 standard with optional port number
    IPv6(Ipv6Addr, Option<u16>),

    /// Tor address of V3 standard
    #[cfg(feature = "tor")]
    #[from]
    Tor(TorPublicKeyV3),
}

impl PartialOrd for PartialSocketAddr {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self, other) {
            (
                PartialSocketAddr::IPv4(addr1, Some(port1)),
                PartialSocketAddr::IPv4(addr2, Some(port2)),
            ) => SocketAddrV4::new(*addr1, *port1)
                .partial_cmp(&SocketAddrV4::new(*addr2, *port2)),
            (
                PartialSocketAddr::IPv6(addr1, Some(port1)),
                PartialSocketAddr::IPv6(addr2, Some(port2)),
            ) => SocketAddrV6::new(*addr1, *port1, 0, 0)
                .partial_cmp(&SocketAddrV6::new(*addr2, *port2, 0, 0)),
            (
                PartialSocketAddr::IPv4(addr1, Some(port1)),
                PartialSocketAddr::IPv4(addr2, None),
            ) => SocketAddrV4::new(*addr1, *port1)
                .partial_cmp(&SocketAddrV4::new(*addr2, 0)),
            (
                PartialSocketAddr::IPv6(addr1, Some(port1)),
                PartialSocketAddr::IPv6(addr2, None),
            ) => SocketAddrV6::new(*addr1, *port1, 0, 0)
                .partial_cmp(&SocketAddrV6::new(*addr2, 0, 0, 0)),
            (
                PartialSocketAddr::IPv4(addr1, None),
                PartialSocketAddr::IPv4(addr2, Some(port2)),
            ) => SocketAddrV4::new(*addr1, 0)
                .partial_cmp(&SocketAddrV4::new(*addr2, *port2)),
            (
                PartialSocketAddr::IPv6(addr1, None),
                PartialSocketAddr::IPv6(addr2, Some(port2)),
            ) => SocketAddrV6::new(*addr1, 0, 0, 0)
                .partial_cmp(&SocketAddrV6::new(*addr2, *port2, 0, 0)),
            (
                PartialSocketAddr::IPv4(addr1, None),
                PartialSocketAddr::IPv4(addr2, None),
            ) => addr1.partial_cmp(addr2),
            (
                PartialSocketAddr::IPv6(addr1, None),
                PartialSocketAddr::IPv6(addr2, None),
            ) => addr1.partial_cmp(addr2),
            #[cfg(feature = "tor")]
            (PartialSocketAddr::Tor(addr1), PartialSocketAddr::Tor(addr2)) => {
                addr1.partial_cmp(addr2)
            }
            (PartialSocketAddr::IPv4(_, _), _) => Some(Ordering::Greater),
            (_, PartialSocketAddr::IPv4(_, _)) => Some(Ordering::Less),
            #[cfg(feature = "tor")]
            (PartialSocketAddr::IPv6(_, _), _) => Some(Ordering::Greater),
            #[cfg(feature = "tor")]
            (_, PartialSocketAddr::IPv6(_, _)) => Some(Ordering::Less),
        }
    }
}

impl Ord for PartialSocketAddr {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap_or(Ordering::Equal)
    }
}

// We need this since TorPublicKeyV3 does not implement Hash
#[allow(clippy::derive_hash_xor_eq)]
impl std::hash::Hash for PartialSocketAddr {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            PartialSocketAddr::IPv4(ipv4, port) => {
                ipv4.hash(state);
                port.hash(state)
            }
            PartialSocketAddr::IPv6(ipv6, port) => {
                ipv6.hash(state);
                port.hash(state)
            }
            #[cfg(feature = "tor")]
            PartialSocketAddr::Tor(torv3) => torv3.as_bytes().hash(state),
        }
    }
}

impl PartialSocketAddr {
    /// Constructs new socket address matching the provided Tor v3 address
    #[cfg(feature = "tor")]
    #[inline]
    pub fn tor3(tor: TorPublicKeyV3) -> Self { PartialSocketAddr::Tor(tor) }

    /// Constructs new socket address from an internet address and a port
    /// information
    #[inline]
    pub fn socket(ip: IpAddr, port: Option<u16>) -> Self {
        match ip {
            IpAddr::V4(ipv4) => PartialSocketAddr::IPv4(ipv4, port),
            IpAddr::V6(ipv6) => PartialSocketAddr::IPv6(ipv6, port),
        }
    }

    /// Determines whether provided address is a Tor address. Always returns
    /// `false` (the library is built without `tor` feature; use it to
    /// enable Tor addresses).
    #[cfg(not(feature = "tor"))]
    #[inline]
    pub fn is_tor(self) -> bool { false }

    /// Always returns [`Option::None`] (the library is built without `tor`
    /// feature; use it to enable Tor addresses).
    #[cfg(not(feature = "tor"))]
    #[inline]
    pub fn onion_address(self) -> Option<()> { None }

    /// Determines whether provided address is a Tor address
    #[cfg(feature = "tor")]
    #[inline]
    pub fn is_tor(self) -> bool { matches!(self, PartialSocketAddr::Tor(_)) }

    /// Returns Onion v3 address, if any, or [`Option::None`]
    #[cfg(feature = "tor")]
    #[inline]
    pub fn onion_address(self) -> Option<OnionAddressV3> {
        match self {
            PartialSocketAddr::IPv4(_, _) | PartialSocketAddr::IPv6(_, _) => {
                None
            }
            PartialSocketAddr::Tor(key) => Some(OnionAddressV3::from(&key)),
        }
    }

    /// Returns [`InetAddr`] address of the socket
    #[inline]
    pub fn address(self) -> InetAddr {
        match self {
            PartialSocketAddr::IPv4(addr, _) => InetAddr::IPv4(addr),
            PartialSocketAddr::IPv6(addr, _) => InetAddr::IPv6(addr),
            #[cfg(feature = "tor")]
            PartialSocketAddr::Tor(tor) => InetAddr::Tor(tor),
        }
    }

    /// Returns port for the socket, if address allows different ports.
    #[inline]
    pub fn port(self) -> Option<u16> {
        match self {
            PartialSocketAddr::IPv4(_, port)
            | PartialSocketAddr::IPv6(_, port) => port,
            #[cfg(feature = "tor")]
            PartialSocketAddr::Tor(_) => None,
        }
    }

    /// Constructs [`InetSocketAddr`] using default port information.
    pub fn inet_socket(self, default_port: u16) -> InetSocketAddr {
        match self {
            PartialSocketAddr::IPv4(addr, None) => {
                InetSocketAddr::IPv4(SocketAddrV4::new(addr, default_port))
            }
            PartialSocketAddr::IPv6(addr, None) => InetSocketAddr::IPv6(
                SocketAddrV6::new(addr, default_port, 0, 0),
            ),
            PartialSocketAddr::IPv4(addr, Some(port)) => {
                InetSocketAddr::IPv4(SocketAddrV4::new(addr, port))
            }
            PartialSocketAddr::IPv6(addr, Some(port)) => {
                InetSocketAddr::IPv6(SocketAddrV6::new(addr, port, 0, 0))
            }
            #[cfg(feature = "tor")]
            PartialSocketAddr::Tor(addr) => InetSocketAddr::Tor(addr),
        }
    }
}

impl Default for PartialSocketAddr {
    #[inline]
    fn default() -> Self { PartialSocketAddr::IPv4(Ipv4Addr::from(0), None) }
}

#[cfg(feature = "tor")]
impl TryFrom<PartialSocketAddr> for IpAddr {
    type Error = NoOnionSupportError;
    #[inline]
    fn try_from(addr: PartialSocketAddr) -> Result<Self, Self::Error> {
        Ok(match addr {
            PartialSocketAddr::IPv4(addr, _) => IpAddr::V4(addr),
            PartialSocketAddr::IPv6(addr, _) => IpAddr::V6(addr),
            #[cfg(feature = "tor")]
            PartialSocketAddr::Tor(_) => return Err(NoOnionSupportError),
        })
    }
}

impl From<IpAddr> for PartialSocketAddr {
    #[inline]
    fn from(value: IpAddr) -> Self {
        match value {
            IpAddr::V4(v4) => PartialSocketAddr::from(v4),
            IpAddr::V6(v6) => PartialSocketAddr::from(v6),
        }
    }
}

impl From<Ipv4Addr> for PartialSocketAddr {
    #[inline]
    fn from(value: Ipv4Addr) -> Self { PartialSocketAddr::IPv4(value, None) }
}

impl From<Ipv6Addr> for PartialSocketAddr {
    #[inline]
    fn from(value: Ipv6Addr) -> Self { PartialSocketAddr::IPv6(value, None) }
}

impl From<SocketAddr> for PartialSocketAddr {
    #[inline]
    fn from(value: SocketAddr) -> Self {
        match value {
            SocketAddr::V4(v4) => PartialSocketAddr::from(v4),
            SocketAddr::V6(v6) => PartialSocketAddr::from(v6),
        }
    }
}

impl From<SocketAddrV4> for PartialSocketAddr {
    #[inline]
    fn from(value: SocketAddrV4) -> Self {
        PartialSocketAddr::IPv4(*value.ip(), Some(value.port()))
    }
}

impl From<SocketAddrV6> for PartialSocketAddr {
    #[inline]
    fn from(value: SocketAddrV6) -> Self {
        PartialSocketAddr::IPv6(*value.ip(), Some(value.port()))
    }
}

#[cfg(feature = "tor")]
impl From<OnionAddressV3> for PartialSocketAddr {
    #[inline]
    fn from(addr: OnionAddressV3) -> Self {
        PartialSocketAddr::Tor(addr.get_public_key())
    }
}

impl From<InetAddr> for PartialSocketAddr {
    fn from(addr: InetAddr) -> Self {
        match addr {
            InetAddr::IPv4(addr) => PartialSocketAddr::IPv4(addr, None),
            InetAddr::IPv6(addr) => PartialSocketAddr::IPv6(addr, None),
            #[cfg(feature = "tor")]
            InetAddr::Tor(addr) => PartialSocketAddr::Tor(addr),
        }
    }
}

impl From<InetSocketAddr> for PartialSocketAddr {
    fn from(addr: InetSocketAddr) -> Self {
        match addr {
            InetSocketAddr::IPv4(socket) => {
                PartialSocketAddr::IPv4(*socket.ip(), Some(socket.port()))
            }
            InetSocketAddr::IPv6(socket) => {
                PartialSocketAddr::IPv6(*socket.ip(), Some(socket.port()))
            }
            #[cfg(feature = "tor")]
            InetSocketAddr::Tor(addr) => PartialSocketAddr::Tor(addr),
        }
    }
}

impl fmt::Display for PartialSocketAddr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            PartialSocketAddr::IPv4(addr, None) => fmt::Display::fmt(addr, f),
            PartialSocketAddr::IPv6(addr, None) => fmt::Display::fmt(addr, f),
            PartialSocketAddr::IPv4(addr, Some(port)) => {
                fmt::Display::fmt(&SocketAddrV4::new(*addr, *port), f)
            }
            PartialSocketAddr::IPv6(addr, Some(port)) => {
                fmt::Display::fmt(&SocketAddrV6::new(*addr, *port, 0, 0), f)
            }
            #[cfg(feature = "tor")]
            PartialSocketAddr::Tor(addr) => fmt::Display::fmt(addr, f),
        }
    }
}

#[cfg(feature = "stringly_conversions")]
impl_try_from_stringly_standard!(PartialSocketAddr);
#[cfg(feature = "stringly_conversions")]
impl_into_stringly_standard!(PartialSocketAddr);

impl FromStr for PartialSocketAddr {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        #[cfg(not(feature = "tor"))]
        struct OnionAddressV3;
        #[cfg(not(feature = "tor"))]
        impl OnionAddressV3 {
            fn from_str(_: &str) -> Result<Self, AddrParseError> {
                Err(AddrParseError::NeedsTorFeature)
            }
        }

        match (
            SocketAddr::from_str(s),
            IpAddr::from_str(s),
            OnionAddressV3::from_str(s),
        ) {
            (Ok(_), _, Ok(_)) | (_, Ok(_), Ok(_)) => {
                Err(AddrParseError::WrongAddrFormat(s.to_owned()))
            }
            (Ok(socket_addr), ..) => Ok(Self::from(socket_addr)),
            (_, Ok(ip_addr), _) => Ok(Self::from(ip_addr)),
            #[cfg(feature = "tor")]
            (_, _, Ok(onionv3)) => Ok(Self::from(onionv3)),
            (_, _, Err(err)) => Err(err.into()),
            #[cfg(not(feature = "tor"))]
            _ => Err(AddrParseError::WrongAddrFormat(s.to_owned())),
        }
    }
}

#[cfg(feature = "parse_arg")]
impl parse_arg::ParseArgFromStr for PartialSocketAddr {
    fn describe_type<W: std::fmt::Write>(mut writer: W) -> std::fmt::Result {
        #[cfg(not(feature = "tor"))]
        {
            write!(writer, "IPv4 or IPv6 address with optional port")
        }
        #[cfg(feature = "tor")]
        {
            write!(
                writer,
                "IPv4, IPv6, or Tor (onion) address with optional port"
            )
        }
    }
}

/// Transport protocols that may be part of [`InetSocketAddrExt`]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Display)]
#[cfg_attr(
    feature = "serde",
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate", rename = "lowercase")
)]
#[non_exhaustive]
#[repr(u8)]
pub enum Transport {
    /// Normal TCP
    #[display("tcp")]
    Tcp = 1,

    /// Normal UDP
    #[display("udp")]
    Udp = 2,

    /// Multipath TCP version
    #[display("mtcp")]
    Mtcp = 3,

    /// More efficient UDP version under developent by Google and consortium of
    /// other internet companies
    #[display("quic")]
    Quic = 4,
    /* There are other rarely used protocols. Do not see any reason to add
     * them to the crate for now, but it may appear in the future,
     * so keeping them for referencing purposes: */
    /*
    UdpLite,
    Sctp,
    Dccp,
    Rudp,
    */
}

impl Default for Transport {
    #[inline]
    fn default() -> Self { Transport::Tcp }
}

impl FromStr for Transport {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Ok(match s.to_lowercase().as_str() {
            "tcp" => Transport::Tcp,
            "udp" => Transport::Udp,
            "mtcp" => Transport::Mtcp,
            "quic" => Transport::Quic,
            _ => {
                return Err(AddrParseError::UnknownProtocolError(s.to_owned()))
            }
        })
    }
}

/// Internet socket address, which consists of [`InetAddr`] IP or Tor address
/// and a port number (without protocol specification, i.e. TCP/UDP etc). If you
/// need to include transport-level protocol information into the socket
/// details, pls check [`InetSocketAddrExt`]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Display, From)]
#[cfg_attr(
    all(feature = "serde", feature = "serde_str_helpers"),
    derive(Serialize, Deserialize),
    serde(
        try_from = "serde_str_helpers::DeserBorrowStr",
        into = "String",
        crate = "serde_crate"
    )
)]
#[cfg_attr(
    all(feature = "serde", not(feature = "serde_str_helpers")),
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
#[display(inner)]
#[non_exhaustive] // Required since we use feature-gated enum variants
pub enum InetSocketAddr {
    /// IP socket address of V4 standard
    #[from]
    IPv4(SocketAddrV4),

    /// IP socket address of V6 standard
    #[from]
    IPv6(SocketAddrV6),

    /// Tor address of V3 standard
    #[cfg(feature = "tor")]
    #[from]
    Tor(TorPublicKeyV3),
}

impl PartialOrd for InetSocketAddr {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self, other) {
            (InetSocketAddr::IPv4(addr1), InetSocketAddr::IPv4(addr2)) => {
                addr1.partial_cmp(addr2)
            }
            (InetSocketAddr::IPv6(addr1), InetSocketAddr::IPv6(addr2)) => {
                addr1.partial_cmp(addr2)
            }
            #[cfg(feature = "tor")]
            (InetSocketAddr::Tor(addr1), InetSocketAddr::Tor(addr2)) => {
                addr1.partial_cmp(addr2)
            }
            (InetSocketAddr::IPv4(_), _) => Some(Ordering::Greater),
            (_, InetSocketAddr::IPv4(_)) => Some(Ordering::Less),
            #[cfg(feature = "tor")]
            (InetSocketAddr::IPv6(_), _) => Some(Ordering::Greater),
            #[cfg(feature = "tor")]
            (_, InetSocketAddr::IPv6(_)) => Some(Ordering::Less),
        }
    }
}

impl Ord for InetSocketAddr {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap_or(Ordering::Equal)
    }
}

// We need this since TorPublicKeyV3 does not implement Hash
#[allow(clippy::derive_hash_xor_eq)]
impl std::hash::Hash for InetSocketAddr {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        match self {
            InetSocketAddr::IPv4(socketv4) => socketv4.hash(state),
            InetSocketAddr::IPv6(socketv6) => socketv6.hash(state),
            #[cfg(feature = "tor")]
            InetSocketAddr::Tor(torv3) => torv3.as_bytes().hash(state),
        }
    }
}

impl Default for InetSocketAddr {
    #[inline]
    fn default() -> Self {
        InetSocketAddr::IPv4(SocketAddrV4::new(Ipv4Addr::from(0), 0))
    }
}

impl InetSocketAddr {
    /// Constructs new socket address matching the provided Tor v3 address
    #[cfg(feature = "tor")]
    #[inline]
    pub fn tor3(tor: TorPublicKeyV3) -> Self { InetSocketAddr::Tor(tor) }

    /// Constructs new socket address from an internet address and a port
    /// information
    #[inline]
    pub fn socket(ip: IpAddr, port: u16) -> Self {
        match ip {
            IpAddr::V4(ipv4) => {
                InetSocketAddr::IPv4(SocketAddrV4::new(ipv4, port))
            }
            IpAddr::V6(ipv6) => {
                InetSocketAddr::IPv6(SocketAddrV6::new(ipv6, port, 0, 0))
            }
        }
    }

    /// Determines whether provided address is a Tor address
    #[inline]
    pub fn is_tor(&self) -> bool {
        match self {
            InetSocketAddr::IPv4(_) | InetSocketAddr::IPv6(_) => false,
            #[cfg(feature = "tor")]
            InetSocketAddr::Tor(_) => true,
        }
    }

    /// Returns [`InetAddr`] address of the socket
    #[inline]
    pub fn address(self) -> InetAddr {
        match self {
            InetSocketAddr::IPv4(socket) => InetAddr::IPv4(*socket.ip()),
            InetSocketAddr::IPv6(socket) => InetAddr::IPv6(*socket.ip()),
            #[cfg(feature = "tor")]
            InetSocketAddr::Tor(tor) => InetAddr::Tor(tor),
        }
    }

    /// Returns port for the socket, if address allows different ports.
    ///
    /// Returns `None` for portless addresses (Tor etc).
    #[inline]
    pub fn port(self) -> Option<u16> {
        match self {
            InetSocketAddr::IPv4(socket) => Some(socket.port()),
            InetSocketAddr::IPv6(socket) => Some(socket.port()),
            #[cfg(feature = "tor")]
            InetSocketAddr::Tor(_) => None,
        }
    }
}

#[cfg(feature = "stringly_conversions")]
impl_try_from_stringly_standard!(InetSocketAddr);
#[cfg(feature = "stringly_conversions")]
impl_into_stringly_standard!(InetSocketAddr);

impl FromStr for InetSocketAddr {
    type Err = AddrParseError;

    #[allow(unreachable_code)]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if let Ok(socket_addr) = SocketAddrV6::from_str(s) {
            Ok(InetSocketAddr::IPv6(socket_addr))
        } else if let Ok(socket_addr) = SocketAddrV4::from_str(s) {
            Ok(InetSocketAddr::IPv4(socket_addr))
        } else {
            #[cfg(not(feature = "tor"))]
            {
                Err(AddrParseError::NeedsTorFeature)
            }
            #[cfg(feature = "tor")]
            if let Ok(addr) = OnionAddressV3::from_str(s) {
                Ok(InetSocketAddr::Tor(addr.get_public_key()))
            } else {
                Err(AddrParseError::WrongAddrFormat(s.to_owned()))
            }
        }
    }
}

#[cfg(feature = "parse_arg")]
impl parse_arg::ParseArgFromStr for InetSocketAddr {
    fn describe_type<W: std::fmt::Write>(mut writer: W) -> std::fmt::Result {
        #[cfg(not(feature = "tor"))]
        {
            write!(writer, "IPv4 or IPv6 socket address")
        }
        #[cfg(feature = "tor")]
        {
            write!(writer, "IPv4, IPv6, or Tor (onion) socket address")
        }
    }
}

#[cfg(feature = "tor")]
impl TryFrom<InetSocketAddr> for SocketAddr {
    type Error = NoOnionSupportError;
    #[inline]
    fn try_from(socket_addr: InetSocketAddr) -> Result<Self, Self::Error> {
        match socket_addr {
            InetSocketAddr::IPv4(socket) => Ok(SocketAddr::V4(socket)),
            InetSocketAddr::IPv6(socket) => Ok(SocketAddr::V6(socket)),
            InetSocketAddr::Tor(_) => Err(NoOnionSupportError),
        }
    }
}

#[cfg(not(feature = "tor"))]
impl From<InetSocketAddr> for SocketAddr {
    #[inline]
    fn from(socket_addr: InetSocketAddr) -> Self {
        match socket_addr {
            InetSocketAddr::IPv4(socket) => SocketAddr::V4(socket),
            InetSocketAddr::IPv6(socket) => SocketAddr::V6(socket),
            #[cfg(feature = "tor")]
            InetSocketAddr::Tor(_) => unreachable!(),
        }
    }
}

impl From<SocketAddr> for InetSocketAddr {
    #[inline]
    fn from(socket: SocketAddr) -> Self {
        match socket {
            SocketAddr::V4(socket) => InetSocketAddr::IPv4(socket),
            SocketAddr::V6(socket) => InetSocketAddr::IPv6(socket),
        }
    }
}

/// Internet socket address of [`InetSocketAddr`] type, extended with a
/// transport-level protocol information (see [`Transport`])
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[cfg_attr(
    all(feature = "serde", feature = "serde_str_helpers"),
    derive(Serialize, Deserialize),
    serde(
        try_from = "serde_str_helpers::DeserBorrowStr",
        into = "String",
        crate = "serde_crate"
    )
)]
#[cfg_attr(
    all(feature = "serde", not(feature = "serde_str_helpers")),
    derive(Serialize, Deserialize),
    serde(crate = "serde_crate")
)]
pub struct InetSocketAddrExt(
    /// Transport-level protocol details (like TCP, UDP etc)
    pub Transport,
    /// Details of the socket address, i.e internet address and port
    /// information
    pub InetSocketAddr,
);

#[cfg(feature = "stringly_conversions")]
impl_try_from_stringly_standard!(InetSocketAddrExt);
#[cfg(feature = "stringly_conversions")]
impl_into_stringly_standard!(InetSocketAddrExt);

impl InetSocketAddrExt {
    /// Constructs [`InetSocketAddrExt`] for a given socket address and TCP
    /// port
    #[inline]
    pub fn tcp(socket: SocketAddr) -> Self {
        Self(Transport::Tcp, socket.into())
    }

    /// Constructs [`InetSocketAddrExt`] for a given internet address and UDP
    /// port
    #[inline]
    pub fn udp(address: IpAddr, port: u16) -> Self {
        Self(Transport::Udp, SocketAddr::new(address, port).into())
    }
}

impl fmt::Display for InetSocketAddrExt {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}://{}", self.0, self.1)
    }
}

impl FromStr for InetSocketAddrExt {
    type Err = AddrParseError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut vals = s.split("://");
        if let (Some(transport), Some(addr), None) =
            (vals.next(), vals.next(), vals.next())
        {
            Ok(Self(transport.parse()?, addr.parse()?))
        } else {
            Err(AddrParseError::WrongSocketExtFormat(s.to_owned()))
        }
    }
}

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

    // TODO: Add tests for Tor

    #[test]
    fn test_inet_addr() {
        let ip4a = "127.0.0.1".parse().unwrap();
        let ip6a = "::1".parse().unwrap();

        let ip4 = InetAddr::IPv4(ip4a);
        let ip6 = InetAddr::IPv6(ip6a);
        assert_eq!(
            ip4.ipv6_addr().unwrap(),
            Ipv6Addr::from_str("::ffff:127.0.0.1").unwrap()
        );
        assert_eq!(ip6.ipv6_addr().unwrap(), ip6a);
        assert_eq!(InetAddr::from(IpAddr::V4(ip4a)), ip4);
        assert_eq!(InetAddr::from(IpAddr::V6(ip6a)), ip6);
        assert_eq!(InetAddr::from(ip4a), ip4);
        assert_eq!(InetAddr::from(ip6a), ip6);

        assert_eq!(InetAddr::default(), InetAddr::from_str("0.0.0.0").unwrap());

        #[cfg(feature = "tor")]
        assert_eq!(IpAddr::try_from(ip4).unwrap(), IpAddr::V4(ip4a));
        #[cfg(feature = "tor")]
        assert_eq!(IpAddr::try_from(ip6).unwrap(), IpAddr::V6(ip6a));

        #[cfg(not(feature = "tor"))]
        assert_eq!(IpAddr::from(ip4.clone()), IpAddr::V4(ip4a));
        #[cfg(not(feature = "tor"))]
        assert_eq!(IpAddr::from(ip6.clone()), IpAddr::V6(ip6a));

        assert_eq!(InetAddr::from_str("127.0.0.1").unwrap(), ip4);
        assert_eq!(InetAddr::from_str("::1").unwrap(), ip6);
        assert_eq!(format!("{}", ip4), "127.0.0.1");
        assert_eq!(format!("{}", ip6), "::1");

        assert!(!ip4.is_tor());
        assert!(!ip6.is_tor());
    }

    #[test]
    fn test_transport() {
        assert_eq!(format!("{}", Transport::Tcp), "tcp");
        assert_eq!(format!("{}", Transport::Udp), "udp");
        assert_eq!(format!("{}", Transport::Quic), "quic");
        assert_eq!(format!("{}", Transport::Mtcp), "mtcp");

        assert_eq!(Transport::from_str("tcp").unwrap(), Transport::Tcp);
        assert_eq!(Transport::from_str("Tcp").unwrap(), Transport::Tcp);
        assert_eq!(Transport::from_str("TCP").unwrap(), Transport::Tcp);
        assert_eq!(Transport::from_str("udp").unwrap(), Transport::Udp);
        assert_eq!(Transport::from_str("quic").unwrap(), Transport::Quic);
        assert_eq!(Transport::from_str("mtcp").unwrap(), Transport::Mtcp);
        assert!(Transport::from_str("xtp").is_err());
    }

    #[test]
    fn test_inet_socket_addr() {
        let ip4a = "127.0.0.1".parse().unwrap();
        let ip6a = "::1".parse().unwrap();
        let socket4a = "127.0.0.1:6865".parse().unwrap();
        let socket6a = "[::1]:6865".parse().unwrap();

        let ip4 = InetSocketAddr::socket(ip4a, 6865);
        let ip6 = InetSocketAddr::socket(ip6a, 6865);
        assert_eq!(InetSocketAddr::from(SocketAddr::V4(socket4a)), ip4);
        assert_eq!(InetSocketAddr::from(SocketAddr::V6(socket6a)), ip6);
        assert_eq!(InetSocketAddr::from(socket4a), ip4);
        assert_eq!(InetSocketAddr::from(socket6a), ip6);

        assert_eq!(
            InetSocketAddr::default(),
            InetSocketAddr::from_str("0.0.0.0:0").unwrap()
        );

        #[cfg(feature = "tor")]
        assert_eq!(
            SocketAddr::try_from(ip4).unwrap(),
            SocketAddr::V4(socket4a)
        );
        #[cfg(feature = "tor")]
        assert_eq!(
            SocketAddr::try_from(ip6).unwrap(),
            SocketAddr::V6(socket6a)
        );

        #[cfg(not(feature = "tor"))]
        assert_eq!(SocketAddr::from(ip4.clone()), SocketAddr::V4(socket4a));
        #[cfg(not(feature = "tor"))]
        assert_eq!(SocketAddr::from(ip6.clone()), SocketAddr::V6(socket6a));

        assert_eq!(InetSocketAddr::from_str("127.0.0.1:6865").unwrap(), ip4);
        assert_eq!(InetSocketAddr::from_str("[::1]:6865").unwrap(), ip6);
        assert_eq!(format!("{}", ip4), "127.0.0.1:6865");
        assert_eq!(format!("{}", ip6), "[::1]:6865");

        assert!(!ip4.is_tor());
        assert!(!ip6.is_tor());
    }

    #[test]
    fn test_inet_socket_addr_ext() {
        let ip4a = "127.0.0.1".parse().unwrap();
        let ip6a = "::1".parse().unwrap();

        let ip4 = InetSocketAddrExt::tcp(SocketAddr::new(ip4a, 6865));
        let ip6 = InetSocketAddrExt::udp(ip6a, 6865);

        assert_eq!(
            InetSocketAddrExt::default(),
            InetSocketAddrExt::from_str("tcp://0.0.0.0:0").unwrap()
        );

        #[cfg(feature = "tor")]
        assert_eq!(
            InetSocketAddrExt::from_str("tcp://127.0.0.1:6865").unwrap(),
            ip4
        );
        #[cfg(feature = "tor")]
        assert_eq!(
            InetSocketAddrExt::from_str("udp://[::1]:6865").unwrap(),
            ip6
        );
        assert_eq!(format!("{}", ip4), "tcp://127.0.0.1:6865");
        assert_eq!(format!("{}", ip6), "udp://[::1]:6865");
    }
}