Bump rust-bitcoin, add addrv2
[dnsseed-rust] / src / peer.rs
1 use std::cmp;
2 use std::net::{SocketAddr, IpAddr};
3 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
4
5 use bitcoin::consensus::encode;
6 use bitcoin::consensus::encode::{Decodable, Encodable};
7 use bitcoin::network::address::Address;
8 use bitcoin::network::constants::{Network, ServiceFlags};
9 use bitcoin::network::message::{RawNetworkMessage, NetworkMessage};
10 use bitcoin::network::message_network::VersionMessage;
11
12 use tokio::prelude::*;
13 use tokio::codec;
14 use tokio::codec::Framed;
15 use tokio::net::TcpStream;
16 use tokio::io::read_exact;
17 use tokio::timer::Delay;
18
19 use futures::sync::mpsc;
20
21 use crate::printer::Printer;
22
23 struct BytesCoder<'a>(&'a mut bytes::BytesMut);
24 impl<'a> std::io::Write for BytesCoder<'a> {
25         fn write(&mut self, b: &[u8]) -> Result<usize, std::io::Error> {
26                 self.0.extend_from_slice(&b);
27                 Ok(b.len())
28         }
29         fn flush(&mut self) -> Result<(), std::io::Error> {
30                 Ok(())
31         }
32 }
33 struct BytesDecoder<'a> {
34         buf: &'a mut bytes::BytesMut,
35         pos: usize,
36 }
37 impl<'a> std::io::Read for BytesDecoder<'a> {
38         fn read(&mut self, b: &mut [u8]) -> Result<usize, std::io::Error> {
39                 let copy_len = cmp::min(b.len(), self.buf.len() - self.pos);
40                 b[..copy_len].copy_from_slice(&self.buf[self.pos..self.pos + copy_len]);
41                 self.pos += copy_len;
42                 Ok(copy_len)
43         }
44 }
45
46 struct MsgCoder<'a>(&'a Printer);
47 impl<'a> codec::Decoder for MsgCoder<'a> {
48         type Item = Option<NetworkMessage>;
49         type Error = encode::Error;
50
51         fn decode(&mut self, bytes: &mut bytes::BytesMut) -> Result<Option<Option<NetworkMessage>>, encode::Error> {
52                 let mut decoder = BytesDecoder {
53                         buf: bytes,
54                         pos: 0
55                 };
56                 match RawNetworkMessage::consensus_decode(&mut decoder) {
57                         Ok(res) => {
58                                 decoder.buf.advance(decoder.pos);
59                                 if res.magic == Network::Bitcoin.magic() {
60                                         Ok(Some(Some(res.payload)))
61                                 } else {
62                                         Err(encode::Error::UnexpectedNetworkMagic {
63                                                 expected: Network::Bitcoin.magic(),
64                                                 actual: res.magic
65                                         })
66                                 }
67                         },
68                         Err(e) => match e {
69                                 encode::Error::Io(_) => Ok(None),
70                                 _ => {
71                                         self.0.add_line(format!("Error decoding message: {:?}", e), true);
72                                         Err(e)
73                                 },
74                         }
75                 }
76         }
77 }
78 impl<'a> codec::Encoder for MsgCoder<'a> {
79         type Item = NetworkMessage;
80         type Error = std::io::Error;
81
82         fn encode(&mut self, msg: NetworkMessage, res: &mut bytes::BytesMut) -> Result<(), std::io::Error> {
83                 if let Err(_) = (RawNetworkMessage {
84                         magic: Network::Bitcoin.magic(),
85                         payload: msg,
86                 }.consensus_encode(&mut BytesCoder(res))) {
87                         //XXX
88                 }
89                 Ok(())
90         }
91 }
92
93 // base32 encoder and tests stolen (transliterated) from Bitcoin Core
94 // Copyright (c) 2012-2019 The Bitcoin Core developers
95 // Distributed under the MIT software license, see
96 // http://www.opensource.org/licenses/mit-license.php.
97 fn encode_base32(inp: &[u8]) -> String {
98         let mut ret = String::with_capacity(((inp.len() + 4) / 5) * 8);
99
100         let alphabet = "abcdefghijklmnopqrstuvwxyz234567";
101         let mut acc: u16 = 0;
102         let mut bits: u8 = 0;
103         for i in inp {
104                 acc = ((acc << 8) | *i as u16) & ((1 << (8 + 5 - 1)) - 1);
105                 bits += 8;
106                 while bits >= 5 {
107                         bits -= 5;
108                         let idx = ((acc >> bits) & ((1 << 5) - 1)) as usize;
109                         ret += &alphabet[idx..idx + 1];
110                 }
111         }
112         if bits != 0 {
113                 let idx = ((acc << (5 - bits)) & ((1 << 5) - 1)) as usize;
114                 ret += &alphabet[idx..idx + 1];
115         }
116         while ret.len() % 8 != 0 { ret += "=" };
117         return ret;
118 }
119
120 #[test]
121 fn test_encode_base32() {
122         let tests_in = ["","f","fo","foo","foob","fooba","foobar"];
123         let tests_out = ["","my======","mzxq====","mzxw6===","mzxw6yq=","mzxw6ytb","mzxw6ytboi======"];
124         for (inp, out) in tests_in.iter().zip(tests_out.iter()) {
125                 assert_eq!(&encode_base32(inp.as_bytes()), out);
126         }
127         // My seednode's onion addr:
128         assert_eq!(&encode_base32(&[0x6a, 0x8b, 0xd2, 0x78, 0x3f, 0x7a, 0xf8, 0x92, 0x8f, 0x80]), "nkf5e6b7pl4jfd4a");
129 }
130
131 /// Note that this should only be used for really small chunks, ie small enough to *definitely* fit
132 /// in the outbound TCP buffer, and shouldn't (practically) block.
133 macro_rules! try_write_small {
134         ($sock: expr, $obj: expr) => { {
135                 match $sock.write_all($obj) {
136                         Ok(()) => {},
137                         Err(e) => return future::Either::A(future::err(e)),
138                 }
139         } }
140 }
141
142 pub struct Peer {}
143 impl Peer {
144         pub fn new(addr: SocketAddr, tor_proxy: &SocketAddr, timeout: Duration, printer: &'static Printer) -> impl Future<Error=(), Item=(mpsc::Sender<NetworkMessage>, impl Stream<Item=Option<NetworkMessage>, Error=encode::Error>)> {
145                 let connect_timeout = Delay::new(Instant::now() + timeout.clone()).then(|_| {
146                         future::err(std::io::Error::new(std::io::ErrorKind::TimedOut, "timeout reached"))
147                 });
148                 match addr.ip() {
149                         IpAddr::V6(v6addr) if v6addr.octets()[..6] == [0xFD,0x87,0xD8,0x7E,0xEB,0x43][..] => {
150                                 future::Either::A(connect_timeout.select(TcpStream::connect(&tor_proxy)
151                                         .and_then(move |mut stream: TcpStream| {
152                                                 try_write_small!(stream, &[5u8, 1u8, 0u8]); // SOCKS5 with 1 method and no auth
153                                                 future::Either::B(read_exact(stream, [0u8; 2]).and_then(move |(mut stream, response)| {
154                                                         if response != [5, 0] { // SOCKS5 with no auth successful
155                                                                 future::Either::B(future::Either::A(future::err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Failed to authenticate"))))
156                                                         } else {
157                                                                 let hostname = encode_base32(&v6addr.octets()[6..]) + ".onion";
158                                                                 let mut connect_msg = Vec::with_capacity(7 + hostname.len());
159                                                                 // SOCKS5 command CONNECT (+ reserved byte) to hostname with given len
160                                                                 connect_msg.extend_from_slice(&[5u8, 1u8, 0u8, 3u8, hostname.len() as u8]);
161                                                                 connect_msg.extend_from_slice(hostname.as_bytes());
162                                                                 connect_msg.push((addr.port() >> 8) as u8);
163                                                                 connect_msg.push((addr.port() >> 0) as u8);
164                                                                 try_write_small!(stream, &connect_msg);
165                                                                 future::Either::B(future::Either::B(read_exact(stream, [0u8; 4]).and_then(move |(stream, response)| {
166                                                                         if response[..3] != [5, 0, 0] {
167                                                                                 future::Either::B(future::err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Failed to authenticate")))
168                                                                         } else {
169                                                                                 if response[3] == 1 {
170                                                                                         future::Either::A(future::Either::A(read_exact(stream, [0; 6]).and_then(|(stream, _)| future::ok(stream))))
171                                                                                 } else if response[3] == 4 {
172                                                                                         future::Either::A(future::Either::B(read_exact(stream, [0; 18]).and_then(|(stream, _)| future::ok(stream))))
173                                                                                 } else {
174                                                                                         future::Either::B(future::err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Bogus proxy address value")))
175                                                                                 }
176                                                                         }
177                                                                 })))
178                                                         }
179                                                 }))
180                                         })
181                                 ).and_then(|(stream, _)| future::ok(stream)).or_else(|(e, _)| future::err(e)))
182                         },
183                         _ => future::Either::B(connect_timeout.select(TcpStream::connect(&addr))
184                                 .and_then(|(stream, _)| future::ok(stream)).or_else(|(e, _)| future::err(e))),
185                 }.and_then(move |stream| {
186                                 let (write, read) = Framed::new(stream, MsgCoder(printer)).split();
187                                 let (mut sender, receiver) = mpsc::channel(10); // We never really should send more than 10 messages unless they're dumb
188                                 tokio::spawn(write.sink_map_err(|_| { () }).send_all(receiver)
189                                         .then(|_| {
190                                                 future::err(())
191                                         }));
192                                 let _ = sender.try_send(NetworkMessage::Version(VersionMessage {
193                                         version: 70015,
194                                         services: ServiceFlags::WITNESS,
195                                         timestamp: SystemTime::now().duration_since(UNIX_EPOCH).expect("time > 1970").as_secs() as i64,
196                                         receiver: Address::new(&addr, ServiceFlags::NONE),
197                                         sender: Address::new(&"0.0.0.0:0".parse().unwrap(), ServiceFlags::WITNESS),
198                                         nonce: 0xdeadbeef,
199                                         user_agent: "/rust-bitcoin:0.18/bluematt-tokio-client:0.1/".to_string(),
200                                         start_height: 0,
201                                         relay: false,
202                                 }));
203                                 future::ok((sender, read))
204                         })
205                 .or_else(move |_| {
206                         Delay::new(Instant::now() + timeout / 10).then(|_| future::err(()))
207                 })
208         }
209 }