bitcoin/network/
address.rs

1// Rust Bitcoin Library
2// Written in 2014 by
3//     Andrew Poelstra <apoelstra@wpsoftware.net>
4//
5// To the extent possible under law, the author(s) have dedicated all
6// copyright and related and neighboring rights to this software to
7// the public domain worldwide. This software is distributed without
8// any warranty.
9//
10// You should have received a copy of the CC0 Public Domain Dedication
11// along with this software.
12// If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
13//
14
15//! Bitcoin network addresses
16//!
17//! This module defines the structures and functions needed to encode
18//! network addresses in Bitcoin messages.
19//!
20
21use std::io;
22use std::fmt;
23use std::net::{SocketAddr, Ipv6Addr, SocketAddrV4, SocketAddrV6};
24
25use consensus::encode::{self, Encoder, Decoder};
26use consensus::encode::{Decodable, Encodable};
27
28/// A message which can be sent on the Bitcoin network
29pub struct Address {
30    /// Services provided by the peer whose address this is
31    pub services: u64,
32    /// Network byte-order ipv6 address, or ipv4-mapped ipv6 address
33    pub address: [u16; 8],
34    /// Network port
35    pub port: u16
36}
37
38const ONION : [u16; 3] = [0xFD87, 0xD87E, 0xEB43];
39
40impl Address {
41    /// Create an address message for a socket
42    pub fn new (socket :&SocketAddr, services: u64) -> Address {
43        let (address, port) = match socket {
44            &SocketAddr::V4(ref addr) => (addr.ip().to_ipv6_mapped().segments(), addr.port()),
45            &SocketAddr::V6(ref addr) => (addr.ip().segments(), addr.port())
46        };
47        Address { address: address, port: port, services: services }
48    }
49
50    /// extract socket address from an address message
51    /// This will return io::Error ErrorKind::AddrNotAvailable if the message contains a Tor address.
52    pub fn socket_addr (&self) -> Result<SocketAddr, io::Error> {
53        let addr = &self.address;
54        if addr[0..3] == ONION {
55            return Err(io::Error::from(io::ErrorKind::AddrNotAvailable));
56        }
57        let ipv6 = Ipv6Addr::new(
58            addr[0],addr[1],addr[2],addr[3],
59            addr[4],addr[5],addr[6],addr[7]
60        );
61        if let Some(ipv4) = ipv6.to_ipv4() {
62            Ok(SocketAddr::V4(SocketAddrV4::new(ipv4, self.port)))
63        }
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<S: Encoder> Encodable<S> for Address {
76    #[inline]
77    fn consensus_encode(&self, s: &mut S) -> Result<(), encode::Error> {
78        self.services.consensus_encode(s)?;
79        addr_to_be(self.address).consensus_encode(s)?;
80        self.port.to_be().consensus_encode(s)
81    }
82}
83
84impl<D: Decoder> Decodable<D> for Address {
85    #[inline]
86    fn consensus_decode(d: &mut D) -> Result<Address, encode::Error> {
87        Ok(Address {
88            services: Decodable::consensus_decode(d)?,
89            address: addr_to_be(Decodable::consensus_decode(d)?),
90            port: u16::from_be(Decodable::consensus_decode(d)?)
91        })
92    }
93}
94
95impl fmt::Debug for Address {
96    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
97        // TODO: render services and hex-ize address
98        write!(f, "Address {{services: {:?}, address: {:?}, port: {:?}}}",
99               self.services, &self.address[..], self.port)
100    }
101}
102
103impl Clone for Address {
104    fn clone(&self) -> Address {
105        Address {
106            services: self.services,
107            address: self.address,
108            port: self.port,
109        }
110    }
111}
112
113impl PartialEq for Address {
114    fn eq(&self, other: &Address) -> bool {
115        self.services == other.services &&
116        &self.address[..] == &other.address[..] &&
117        self.port == other.port
118    }
119}
120
121impl Eq for Address {}
122
123#[cfg(test)]
124mod test {
125    use std::str::FromStr;
126    use super::Address;
127    use std::net::{SocketAddr, IpAddr, Ipv4Addr, Ipv6Addr};
128
129    use consensus::encode::{deserialize, serialize};
130
131    #[test]
132    fn serialize_address_test() {
133        assert_eq!(serialize(&Address {
134            services: 1,
135            address: [0, 0, 0, 0, 0, 0xffff, 0x0a00, 0x0001],
136            port: 8333
137        }),
138        vec![1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
139             0, 0, 0, 0xff, 0xff, 0x0a, 0, 0, 1, 0x20, 0x8d]);
140    }
141
142    #[test]
143    fn deserialize_address_test() {
144        let mut addr: Result<Address, _> = deserialize(&[1u8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
145                                                       0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x0a, 0,
146                                                       0, 1, 0x20, 0x8d]);
147        assert!(addr.is_ok());
148        let full = addr.unwrap();
149        assert!(match full.socket_addr().unwrap() {
150                    SocketAddr::V4(_) => true,
151                    _ => false
152                }
153            );
154        assert_eq!(full.services, 1);
155        assert_eq!(full.address, [0, 0, 0, 0, 0, 0xffff, 0x0a00, 0x0001]);
156        assert_eq!(full.port, 8333);
157
158        addr = deserialize(&[1u8, 0, 0, 0, 0, 0, 0, 0, 0,
159                             0, 0, 0, 0, 0, 0, 0, 0, 0, 0xff, 0xff, 0x0a, 0, 0, 1]);
160        assert!(addr.is_err());
161    }
162
163    #[test]
164    fn test_socket_addr () {
165        let s4 = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(111,222,123,4)), 5555);
166        let a4 = Address::new(&s4, 9);
167        assert_eq!(a4.socket_addr().unwrap(), s4);
168        let s6 = SocketAddr::new(IpAddr::V6(Ipv6Addr::new(0x1111, 0x2222, 0x3333, 0x4444,
169        0x5555, 0x6666, 0x7777, 0x8888)), 9999);
170        let a6 = Address::new(&s6, 9);
171        assert_eq!(a6.socket_addr().unwrap(), s6);
172    }
173
174    #[test]
175    fn onion_test () {
176        let onionaddr = SocketAddr::new(
177            IpAddr::V6(
178            Ipv6Addr::from_str("FD87:D87E:EB43:edb1:8e4:3588:e546:35ca").unwrap()), 1111);
179        let addr = Address::new(&onionaddr, 0);
180        assert!(addr.socket_addr().is_err());
181    }
182}
183