use bytes::BufMut;
use cuprate_epee_encoding::EpeeObject;
use std::{hash::Hash, net, net::SocketAddr};
mod epee_builder;
use epee_builder::*;
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum NetZone {
Public,
Tor,
I2p,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NetworkAddress {
Clear(SocketAddr),
}
impl EpeeObject for NetworkAddress {
type Builder = TaggedNetworkAddress;
fn number_of_fields(&self) -> u64 {
2
}
fn write_fields<B: BufMut>(self, w: &mut B) -> cuprate_epee_encoding::Result<()> {
TaggedNetworkAddress::from(self).write_fields(w)
}
}
impl NetworkAddress {
pub fn get_zone(&self) -> NetZone {
match self {
NetworkAddress::Clear(_) => NetZone::Public,
}
}
pub fn is_loopback(&self) -> bool {
false
}
pub fn is_local(&self) -> bool {
false
}
pub fn port(&self) -> u16 {
match self {
NetworkAddress::Clear(ip) => ip.port(),
}
}
}
impl From<net::SocketAddrV4> for NetworkAddress {
fn from(value: net::SocketAddrV4) -> Self {
NetworkAddress::Clear(value.into())
}
}
impl From<net::SocketAddrV6> for NetworkAddress {
fn from(value: net::SocketAddrV6) -> Self {
NetworkAddress::Clear(value.into())
}
}
impl From<SocketAddr> for NetworkAddress {
fn from(value: SocketAddr) -> Self {
match value {
SocketAddr::V4(v4) => v4.into(),
SocketAddr::V6(v6) => v6.into(),
}
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq, thiserror::Error)]
#[error("Network address is not in the correct zone")]
pub struct NetworkAddressIncorrectZone;
impl TryFrom<NetworkAddress> for SocketAddr {
type Error = NetworkAddressIncorrectZone;
fn try_from(value: NetworkAddress) -> Result<Self, Self::Error> {
match value {
NetworkAddress::Clear(addr) => Ok(addr),
}
}
}