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
use multiaddr::{self, Multiaddr, ToMultiaddr};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use std::{
    cmp::{Ord, Ordering},
    fmt,
};

/// the address of any given nodes
///
/// The underlying object is, for now, a [`Multiaddr`] to allow
/// compatibility with the different type of network and identification.
///
/// [`Multiaddr`]: https://docs.rs/multiaddr/latest/multiaddr/struct.Multiaddr.html
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
pub struct Address(Multiaddr);

impl Address {
    /// create a new address from any given [`ToMultiaddr`] implementors
    ///
    /// # Examples
    ///
    /// TODO: simple example with SockAddr from standard lib
    /// TODO: simple example with a multiaddr object and a string
    ///
    /// TODO: [`ToMultiaddr`]
    pub fn new<Addr>(addr: Addr) -> Result<Self, multiaddr::Error>
    where
        Addr: ToMultiaddr,
    {
        addr.to_multiaddr().map(Address)
    }

    pub fn to_socketaddr(&self) -> Option<std::net::SocketAddr> {
        let components = self.0.iter().collect::<Vec<_>>();

        match components.get(0)? {
            multiaddr::AddrComponent::IP4(ipv4) => {
                if let multiaddr::AddrComponent::TCP(port) = components.get(1)? {
                    Some(std::net::SocketAddr::V4(std::net::SocketAddrV4::new(
                        *ipv4, *port,
                    )))
                } else {
                    None
                }
            }
            multiaddr::AddrComponent::IP6(ipv6) => {
                if let multiaddr::AddrComponent::TCP(port) = components.get(1)? {
                    Some(std::net::SocketAddr::V6(std::net::SocketAddrV6::new(
                        *ipv6, *port, 0, 0,
                    )))
                } else {
                    None
                }
            }
            _ => None,
        }
    }

    pub fn to_bytes(&self) -> Vec<u8> {
        self.0.to_bytes()
    }

    fn as_slice(&self) -> &[u8] {
        self.0.as_slice()
    }
}

impl From<Multiaddr> for Address {
    fn from(multiaddr: Multiaddr) -> Self {
        Address(multiaddr)
    }
}

impl From<Address> for Multiaddr {
    #[inline]
    fn from(address: Address) -> Self {
        address.0
    }
}

impl std::str::FromStr for Address {
    type Err = <Multiaddr as std::str::FromStr>::Err;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        s.parse().map(Address)
    }
}

impl fmt::Display for Address {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(&self.0, f)
    }
}

impl PartialOrd for Address {
    fn partial_cmp(&self, rhs: &Self) -> Option<Ordering> {
        PartialOrd::partial_cmp(self.0.as_slice(), rhs.0.as_slice())
    }
}
impl Ord for Address {
    fn cmp(&self, rhs: &Self) -> Ordering {
        Ord::cmp(self.0.as_slice(), rhs.0.as_slice())
    }
}

impl Serialize for Address {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        if serializer.is_human_readable() {
            serializer.serialize_str(&format!("{}", self))
        } else {
            serializer.serialize_bytes(&self.as_slice())
        }
    }
}
impl<'de> Deserialize<'de> for Address {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::{self, Unexpected, Visitor};
        use std::fmt::Formatter;

        struct AddressVisitor;
        impl<'de> Visitor<'de> for AddressVisitor {
            type Value = Address;

            fn expecting(&self, f: &mut Formatter) -> Result<(), std::fmt::Error> {
                write!(
                    f,
                    "expected a multi format address (e.g.: `/ip4/127.0.0.1/tcp/8081')"
                )
            }

            fn visit_str<E>(self, s: &str) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                match s.parse::<multiaddr::Multiaddr>() {
                    Ok(address) => Ok(Address::from(address)),
                    Err(_err) => Err(de::Error::invalid_value(Unexpected::Str(s), &self)),
                }
            }
            fn visit_bytes<E>(self, s: &[u8]) -> Result<Self::Value, E>
            where
                E: de::Error,
            {
                match multiaddr::Multiaddr::from_bytes(s.to_owned()) {
                    Ok(address) => Ok(Address::from(address)),
                    Err(_err) => Err(de::Error::invalid_value(Unexpected::Bytes(s), &self)),
                }
            }
        }

        if deserializer.is_human_readable() {
            deserializer.deserialize_str(AddressVisitor)
        } else {
            deserializer.deserialize_bytes(AddressVisitor)
        }
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use quickcheck::{Arbitrary, Gen};

    impl Arbitrary for Address {
        fn arbitrary<G: Gen>(g: &mut G) -> Self {
            let ip: (u8, u8, u8, u8) = Arbitrary::arbitrary(g);
            let port: u16 = Arbitrary::arbitrary(g);
            let address = format!("/ip4/{}.{}.{}.{}/tcp/{}", ip.0, ip.1, ip.2, ip.3, port);
            address.parse().unwrap()
        }
    }

    #[quickcheck]
    fn address_encode_decode_json(address: Address) -> bool {
        let encoded = serde_json::to_string(&address).unwrap();
        let decoded: Address = serde_json::from_str(&encoded).unwrap();
        decoded == address
    }

    #[quickcheck]
    fn address_encode_decode_bincode(address: Address) -> bool {
        let encoded = bincode::serialize(&address).unwrap();
        let decoded: Address = bincode::deserialize(&encoded).unwrap();
        decoded == address
    }
}