1use std::{fmt, io, iter};
22use std::net::{SocketAddr, Ipv6Addr, SocketAddrV4, SocketAddrV6, Ipv4Addr, ToSocketAddrs};
23
24use network::constants::ServiceFlags;
25use consensus::encode::{self, Decodable, Encodable, VarInt, ReadExt, WriteExt};
26
27#[derive(Clone, PartialEq, Eq, Hash)]
29pub struct Address {
30 pub services: ServiceFlags,
32 pub address: [u16; 8],
34 pub port: u16
36}
37
38const ONION : [u16; 3] = [0xFD87, 0xD87E, 0xEB43];
39
40impl Address {
41 pub fn new(socket :&SocketAddr, services: ServiceFlags) -> Address {
43 let (address, port) = match *socket {
44 SocketAddr::V4(addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()),
45 SocketAddr::V6(addr) => (addr.ip().segments(), addr.port())
46 };
47 Address { address: address, port: port, services: services }
48 }
49
50 pub fn socket_addr(&self) -> Result<SocketAddr, io::Error> {
54 let addr = &self.address;
55 if addr[0..3] == ONION {
56 return Err(io::Error::from(io::ErrorKind::AddrNotAvailable));
57 }
58 let ipv6 = Ipv6Addr::new(
59 addr[0],addr[1],addr[2],addr[3],
60 addr[4],addr[5],addr[6],addr[7]
61 );
62 if let Some(ipv4) = ipv6.to_ipv4() {
63 Ok(SocketAddr::V4(SocketAddrV4::new(ipv4, self.port)))
64 } else {
65 Ok(SocketAddr::V6(SocketAddrV6::new(ipv6, self.port, 0, 0)))
66 }
67 }
68}
69
70fn addr_to_be(addr: [u16; 8]) -> [u16; 8] {
71 [addr[0].to_be(), addr[1].to_be(), addr[2].to_be(), addr[3].to_be(),
72 addr[4].to_be(), addr[5].to_be(), addr[6].to_be(), addr[7].to_be()]
73}
74
75impl Encodable for Address {
76 #[inline]
77 fn consensus_encode<S: io::Write>(
78 &self,
79 mut s: S,
80 ) -> Result<usize, io::Error> {
81 let len = self.services.consensus_encode(&mut s)?
82 + addr_to_be(self.address).consensus_encode(&mut s)?
83 + self.port.to_be().consensus_encode(s)?;
84 Ok(len)
85 }
86}
87
88impl Decodable for Address {
89 #[inline]
90 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> {
91 Ok(Address {
92 services: Decodable::consensus_decode(&mut d)?,
93 address: addr_to_be(Decodable::consensus_decode(&mut d)?),
94 port: u16::from_be(Decodable::consensus_decode(d)?)
95 })
96 }
97}
98
99impl fmt::Debug for Address {
100 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
101 let ipv6 = Ipv6Addr::from(self.address);
102
103 match ipv6.to_ipv4() {
104 Some(addr) => write!(f, "Address {{services: {}, address: {}, port: {}}}",
105 self.services, addr, self.port),
106 None => write!(f, "Address {{services: {}, address: {}, port: {}}}",
107 self.services, ipv6, self.port)
108 }
109 }
110}
111
112impl ToSocketAddrs for Address {
113 type Iter = iter::Once<SocketAddr>;
114 fn to_socket_addrs(&self) -> Result<Self::Iter, io::Error> {
115 Ok(iter::once(self.socket_addr()?))
116 }
117}
118
119#[derive(Clone, PartialEq, Eq, Hash, Debug)]
121pub enum AddrV2 {
122 Ipv4(Ipv4Addr),
124 Ipv6(Ipv6Addr),
126 TorV2([u8; 10]),
128 TorV3([u8; 32]),
130 I2p([u8; 32]),
132 Cjdns(Ipv6Addr),
134 Unknown(u8, Vec<u8>),
136}
137
138impl Encodable for AddrV2 {
139 fn consensus_encode<W: io::Write>(&self, e: W) -> Result<usize, io::Error> {
140 fn encode_addr<W: io::Write>(mut e: W, network: u8, bytes: &[u8]) -> Result<usize, io::Error> {
141 let len =
142 network.consensus_encode(&mut e)? +
143 VarInt(bytes.len() as u64).consensus_encode(&mut e)? +
144 bytes.len();
145 e.emit_slice(bytes)?;
146 Ok(len)
147 }
148 Ok(match *self {
149 AddrV2::Ipv4(ref addr) => encode_addr(e, 1, &addr.octets())?,
150 AddrV2::Ipv6(ref addr) => encode_addr(e, 2, &addr.octets())?,
151 AddrV2::TorV2(ref bytes) => encode_addr(e, 3, bytes)?,
152 AddrV2::TorV3(ref bytes) => encode_addr(e, 4, bytes)?,
153 AddrV2::I2p(ref bytes) => encode_addr(e, 5, bytes)?,
154 AddrV2::Cjdns(ref addr) => encode_addr(e, 6, &addr.octets())?,
155 AddrV2::Unknown(network, ref bytes) => encode_addr(e, network, bytes)?
156 })
157 }
158}
159
160impl Decodable for AddrV2 {
161 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> {
162 let network_id = u8::consensus_decode(&mut d)?;
163 let len = VarInt::consensus_decode(&mut d)?.0;
164 if len > 512 {
165 return Err(encode::Error::ParseFailed("IP must be <= 512 bytes"));
166 }
167 Ok(match network_id {
168 1 => {
169 if len != 4 {
170 return Err(encode::Error::ParseFailed("Invalid IPv4 address"));
171 }
172 let addr: [u8; 4] = Decodable::consensus_decode(&mut d)?;
173 AddrV2::Ipv4(Ipv4Addr::new(addr[0], addr[1], addr[2], addr[3]))
174 },
175 2 => {
176 if len != 16 {
177 return Err(encode::Error::ParseFailed("Invalid IPv6 address"));
178 }
179 let addr: [u16; 8] = addr_to_be(Decodable::consensus_decode(&mut d)?);
180 if addr[0..3] == ONION {
181 return Err(encode::Error::ParseFailed("OnionCat address sent with IPv6 network id"));
182 }
183 if addr[0..6] == [0x0000, 0x0000, 0x0000, 0x0000, 0x0000, 0xFFFF] {
184 return Err(encode::Error::ParseFailed("IPV4 wrapped address sent with IPv6 network id"));
185 }
186 AddrV2::Ipv6(Ipv6Addr::new(
187 addr[0],addr[1],addr[2],addr[3],
188 addr[4],addr[5],addr[6],addr[7]
189 ))
190 },
191 3 => {
192 if len != 10 {
193 return Err(encode::Error::ParseFailed("Invalid TorV2 address"));
194 }
195 let id = Decodable::consensus_decode(&mut d)?;
196 AddrV2::TorV2(id)
197 },
198 4 => {
199 if len != 32 {
200 return Err(encode::Error::ParseFailed("Invalid TorV3 address"));
201 }
202 let pubkey = Decodable::consensus_decode(&mut d)?;
203 AddrV2::TorV3(pubkey)
204 },
205 5 => {
206 if len != 32 {
207 return Err(encode::Error::ParseFailed("Invalid I2P address"));
208 }
209 let hash = Decodable::consensus_decode(&mut d)?;
210 AddrV2::I2p(hash)
211 },
212 6 => {
213 if len != 16 {
214 return Err(encode::Error::ParseFailed("Invalid CJDNS address"));
215 }
216 let addr: [u16; 8] = Decodable::consensus_decode(&mut d)?;
217 if addr[0] as u8 != 0xFC {
219 return Err(encode::Error::ParseFailed("Invalid CJDNS address"));
220 }
221 let addr = addr_to_be(addr);
222 AddrV2::Cjdns(Ipv6Addr::new(
223 addr[0],addr[1],addr[2],addr[3],
224 addr[4],addr[5],addr[6],addr[7]
225 ))
226 },
227 _ => {
228 let mut addr = vec![0u8; len as usize];
230 d.read_slice(&mut addr)?;
231 AddrV2::Unknown(network_id, addr)
232 }
233 })
234 }
235}
236
237#[derive(Clone, PartialEq, Eq, Hash, Debug)]
239pub struct AddrV2Message {
240 pub time: u32,
242 pub services: ServiceFlags,
244 pub addr: AddrV2,
246 pub port: u16
248}
249
250impl AddrV2Message {
251 pub fn socket_addr(&self) -> Result<SocketAddr, io::Error> {
255 match self.addr {
256 AddrV2::Ipv4(addr) => Ok(SocketAddr::V4(SocketAddrV4::new(addr, self.port))),
257 AddrV2::Ipv6(addr) => Ok(SocketAddr::V6(SocketAddrV6::new(addr, self.port, 0, 0))),
258 _ => return Err(io::Error::from(io::ErrorKind::AddrNotAvailable)),
259 }
260 }
261}
262
263impl Encodable for AddrV2Message {
264 fn consensus_encode<W: io::Write>(&self, mut e: W) -> Result<usize, io::Error> {
265 let mut len = 0;
266 len += self.time.consensus_encode(&mut e)?;
267 len += VarInt(self.services.as_u64()).consensus_encode(&mut e)?;
268 len += self.addr.consensus_encode(&mut e)?;
269 len += self.port.to_be().consensus_encode(e)?;
270 Ok(len)
271 }
272}
273
274impl Decodable for AddrV2Message {
275 fn consensus_decode<D: io::Read>(mut d: D) -> Result<Self, encode::Error> {
276 Ok(AddrV2Message{
277 time: Decodable::consensus_decode(&mut d)?,
278 services: ServiceFlags::from(VarInt::consensus_decode(&mut d)?.0),
279 addr: Decodable::consensus_decode(&mut d)?,
280 port: u16::from_be(Decodable::consensus_decode(d)?),
281 })
282 }
283}
284
285impl ToSocketAddrs for AddrV2Message {
286 type Iter = iter::Once<SocketAddr>;
287 fn to_socket_addrs(&self) -> Result<Self::Iter, io::Error> {
288 Ok(iter::once(self.socket_addr()?))
289 }
290}
291
292#[cfg(test)]
293mod test {
294 use std::str::FromStr;
295 use super::{AddrV2Message, AddrV2, Address};
296 use network::constants::ServiceFlags;
297 use std::net::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr};
298 use hashes::hex::FromHex;
299
300 use consensus::encode::{deserialize, serialize};
301
302 #[test]
303 fn serialize_address_test() {
304 assert_eq!(serialize(&Address {
305 services: ServiceFlags::NETWORK,
306 address: [0, 0, 0, 0, 0, 0xffff, 0x0a00, 0x0001],
307 port: 8333
308 }),
309 vec![1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
310 0, 0, 0, 0xff, 0xff, 0x0a, 0, 0, 1, 0x20, 0x8d]);
311 }
312
313 #[test]
314 fn debug_format_test() {
315 let mut flags = ServiceFlags::NETWORK;
316 assert_eq!(
317 format!("The address is: {:?}", Address {
318 services: flags.add(ServiceFlags::WITNESS),
319 address: [0, 0, 0, 0, 0, 0xffff, 0x0a00, 0x0001],
320 port: 8333
321 }),
322 "The address is: Address {services: ServiceFlags(NETWORK|WITNESS), address: 10.0.0.1, port: 8333}"
323 );
324
325 assert_eq!(
326 format!("The address is: {:?}", Address {
327 services: ServiceFlags::NETWORK_LIMITED,
328 address: [0xFD87, 0xD87E, 0xEB43, 0, 0, 0xffff, 0x0a00, 0x0001],
329 port: 8333
330 }),
331 "The address is: Address {services: ServiceFlags(NETWORK_LIMITED), address: fd87:d87e:eb43::ffff:a00:1, port: 8333}"
332 );
333 }
334
335 #[test]
336 fn deserialize_address_test() {
337 let mut addr: Result<Address, _> = deserialize(&[1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
338 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x0a, 0,
339 0, 1, 0x20, 0x8d]);
340 assert!(addr.is_ok());
341 let full = addr.unwrap();
342 assert!(match full.socket_addr().unwrap() {
343 SocketAddr::V4(_) => true,
344 _ => false
345 }
346 );
347 assert_eq!(full.services, ServiceFlags::NETWORK);
348 assert_eq!(full.address, [0, 0, 0, 0, 0, 0xffff, 0x0a00, 0x0001]);
349 assert_eq!(full.port, 8333);
350
351 addr = deserialize(&[1u8, 0, 0, 0, 0, 0, 0, 0, 0,
352 0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x0a, 0, 0, 1]);
353 assert!(addr.is_err());
354 }
355
356 #[test]
357 fn test_socket_addr () {
358 let s4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(111,222,123,4)), 5555);
359 let a4 = Address::new(&s4, ServiceFlags::NETWORK | ServiceFlags::WITNESS);
360 assert_eq!(a4.socket_addr().unwrap(), s4);
361 let s6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0x1111, 0x2222, 0x3333, 0x4444,
362 0x5555, 0x6666, 0x7777, 0x8888)), 9999);
363 let a6 = Address::new(&s6, ServiceFlags::NETWORK | ServiceFlags::WITNESS);
364 assert_eq!(a6.socket_addr().unwrap(), s6);
365 }
366
367 #[test]
368 fn onion_test () {
369 let onionaddr = SocketAddr::new(
370 IpAddr::V6(
371 Ipv6Addr::from_str("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").unwrap()), 1111);
372 let addr = Address::new(&onionaddr, ServiceFlags::NONE);
373 assert!(addr.socket_addr().is_err());
374 }
375
376 #[test]
377 fn serialize_addrv2_test() {
378 let ip = AddrV2::Ipv4(Ipv4Addr::new(1, 2, 3, 4));
381 assert_eq!(serialize(&ip), Vec::from_hex("010401020304").unwrap());
382
383 let ip = AddrV2::Ipv6(Ipv6Addr::from_str("1a1b:2a2b:3a3b:4a4b:5a5b:6a6b:7a7b:8a8b").unwrap());
384 assert_eq!(serialize(&ip), Vec::from_hex("02101a1b2a2b3a3b4a4b5a5b6a6b7a7b8a8b").unwrap());
385
386 let ip = AddrV2::TorV2(FromHex::from_hex("f1f2f3f4f5f6f7f8f9fa").unwrap());
387 assert_eq!(serialize(&ip), Vec::from_hex("030af1f2f3f4f5f6f7f8f9fa").unwrap());
388
389 let ip = AddrV2::TorV3(FromHex::from_hex("53cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88").unwrap());
390 assert_eq!(serialize(&ip), Vec::from_hex("042053cd5648488c4707914182655b7664034e09e66f7e8cbf1084e654eb56c5bd88").unwrap());
391
392 let ip = AddrV2::I2p(FromHex::from_hex("a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87").unwrap());
393 assert_eq!(serialize(&ip), Vec::from_hex("0520a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87").unwrap());
394
395 let ip = AddrV2::Cjdns(Ipv6Addr::from_str("fc00:1:2:3:4:5:6:7").unwrap());
396 assert_eq!(serialize(&ip), Vec::from_hex("0610fc000001000200030004000500060007").unwrap());
397
398 let ip = AddrV2::Unknown(170, Vec::from_hex("01020304").unwrap());
399 assert_eq!(serialize(&ip), Vec::from_hex("aa0401020304").unwrap());
400 }
401
402 #[test]
403 fn deserialize_addrv2_test() {
404 let ip: AddrV2 = deserialize(&Vec::from_hex("010401020304").unwrap()).unwrap();
408 assert_eq!(ip, AddrV2::Ipv4(Ipv4Addr::new(1, 2, 3, 4)));
409
410 deserialize::<AddrV2>(&Vec::from_hex("01040102").unwrap()).unwrap_err();
412
413 assert!(deserialize::<AddrV2>(&Vec::from_hex("010501020304").unwrap()).is_err());
415
416 assert!(deserialize::<AddrV2>(&Vec::from_hex("01fd010201020304").unwrap()).is_err());
418
419 let ip: AddrV2 = deserialize(&Vec::from_hex("02100102030405060708090a0b0c0d0e0f10").unwrap()).unwrap();
421 assert_eq!(ip, AddrV2::Ipv6(Ipv6Addr::from_str("102:304:506:708:90a:b0c:d0e:f10").unwrap()));
422
423 assert!(deserialize::<AddrV2>(&Vec::from_hex("020400").unwrap()).is_err());
425
426 assert!(deserialize::<AddrV2>(&Vec::from_hex("021000000000000000000000ffff01020304").unwrap()).is_err());
428
429 assert!(deserialize::<AddrV2>(&Vec::from_hex("0210fd87d87eeb430102030405060708090a").unwrap()).is_err());
431
432 let ip: AddrV2 = deserialize(&Vec::from_hex("030af1f2f3f4f5f6f7f8f9fa").unwrap()).unwrap();
434 assert_eq!(ip, AddrV2::TorV2(FromHex::from_hex("f1f2f3f4f5f6f7f8f9fa").unwrap()));
435
436 assert!(deserialize::<AddrV2>(&Vec::from_hex("030700").unwrap()).is_err());
438
439 let ip: AddrV2 = deserialize(&Vec::from_hex("042079bcc625184b05194975c28b66b66b0469f7f6556fb1ac3189a79b40dda32f1f").unwrap()).unwrap();
441 assert_eq!(ip, AddrV2::TorV3(FromHex::from_hex("79bcc625184b05194975c28b66b66b0469f7f6556fb1ac3189a79b40dda32f1f").unwrap()));
442
443 assert!(deserialize::<AddrV2>(&Vec::from_hex("040000").unwrap()).is_err());
445
446 let ip: AddrV2 = deserialize(&Vec::from_hex("0520a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87").unwrap()).unwrap();
448 assert_eq!(ip, AddrV2::I2p(FromHex::from_hex("a2894dabaec08c0051a481a6dac88b64f98232ae42d4b6fd2fa81952dfe36a87").unwrap()));
449
450 assert!(deserialize::<AddrV2>(&Vec::from_hex("050300").unwrap()).is_err());
452
453 let ip: AddrV2 = deserialize(&Vec::from_hex("0610fc000001000200030004000500060007").unwrap()).unwrap();
455 assert_eq!(ip, AddrV2::Cjdns(Ipv6Addr::from_str("fc00:1:2:3:4:5:6:7").unwrap()));
456
457 assert!(deserialize::<AddrV2>(&Vec::from_hex("0610fd000001000200030004000500060007").unwrap()).is_err());
459
460 assert!(deserialize::<AddrV2>(&Vec::from_hex("060100").unwrap()).is_err());
462
463 assert!(deserialize::<AddrV2>(&Vec::from_hex("aafe0000000201020304050607").unwrap()).is_err());
465
466 let ip: AddrV2 = deserialize(&Vec::from_hex("aa0401020304").unwrap()).unwrap();
468 assert_eq!(ip, AddrV2::Unknown(170, Vec::from_hex("01020304").unwrap()));
469
470 let ip: AddrV2 = deserialize(&Vec::from_hex("aa00").unwrap()).unwrap();
472 assert_eq!(ip, AddrV2::Unknown(170, vec![]));
473 }
474
475 #[test]
476 fn addrv2message_test() {
477 let raw = Vec::from_hex("0261bc6649019902abab208d79627683fd4804010409090909208d").unwrap();
478 let addresses: Vec<AddrV2Message> = deserialize(&raw).unwrap();
479
480 assert_eq!(addresses, vec![
481 AddrV2Message{services: ServiceFlags::NETWORK, time: 0x4966bc61, port: 8333, addr: AddrV2::Unknown(153, Vec::from_hex("abab").unwrap())},
482 AddrV2Message{services: ServiceFlags::NETWORK_LIMITED | ServiceFlags::WITNESS | ServiceFlags::COMPACT_FILTERS, time: 0x83766279, port: 8333, addr: AddrV2::Ipv4(Ipv4Addr::new(9, 9, 9, 9))},
483 ]);
484
485 assert_eq!(serialize(&addresses), raw);
486 }
487}