cuprate_wire/
network_address.rs1use std::{hash::Hash, net, net::SocketAddr};
21
22use bytes::BufMut;
23
24use cuprate_epee_encoding::EpeeObject;
25
26mod epee_builder;
27use epee_builder::*;
28
29#[derive(Debug, PartialEq, Eq, Clone, Copy)]
30pub enum NetZone {
31 Public,
32 Tor,
33 I2p,
34}
35
36#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
39pub enum NetworkAddress {
40 Clear(SocketAddr),
41}
42
43impl EpeeObject for NetworkAddress {
44 type Builder = TaggedNetworkAddress;
45
46 fn number_of_fields(&self) -> u64 {
47 2
48 }
49
50 fn write_fields<B: BufMut>(self, w: &mut B) -> cuprate_epee_encoding::Result<()> {
51 TaggedNetworkAddress::from(self).write_fields(w)
52 }
53}
54
55impl NetworkAddress {
56 pub const fn get_zone(&self) -> NetZone {
57 match self {
58 Self::Clear(_) => NetZone::Public,
59 }
60 }
61
62 pub const fn is_loopback(&self) -> bool {
63 false
65 }
66
67 pub const fn is_local(&self) -> bool {
68 false
70 }
71
72 pub const fn port(&self) -> u16 {
73 match self {
74 Self::Clear(ip) => ip.port(),
75 }
76 }
77}
78
79impl From<net::SocketAddrV4> for NetworkAddress {
80 fn from(value: net::SocketAddrV4) -> Self {
81 Self::Clear(value.into())
82 }
83}
84
85impl From<net::SocketAddrV6> for NetworkAddress {
86 fn from(value: net::SocketAddrV6) -> Self {
87 Self::Clear(value.into())
88 }
89}
90
91impl From<SocketAddr> for NetworkAddress {
92 fn from(value: SocketAddr) -> Self {
93 match value {
94 SocketAddr::V4(v4) => v4.into(),
95 SocketAddr::V6(v6) => v6.into(),
96 }
97 }
98}
99
100#[derive(Debug, Copy, Clone, Eq, PartialEq, thiserror::Error)]
101#[error("Network address is not in the correct zone")]
102pub struct NetworkAddressIncorrectZone;
103
104impl TryFrom<NetworkAddress> for SocketAddr {
105 type Error = NetworkAddressIncorrectZone;
106 fn try_from(value: NetworkAddress) -> Result<Self, Self::Error> {
107 match value {
108 NetworkAddress::Clear(addr) => Ok(addr),
109 }
111 }
112}