2 use std::net::{SocketAddr, IpAddr};
3 use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
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;
12 use tokio::prelude::*;
14 use tokio::codec::Framed;
15 use tokio::net::TcpStream;
16 use tokio::io::read_exact;
17 use tokio::timer::Delay;
19 use futures::sync::mpsc;
21 use crate::printer::Printer;
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);
29 fn flush(&mut self) -> Result<(), std::io::Error> {
33 struct BytesDecoder<'a> {
34 buf: &'a mut bytes::BytesMut,
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]);
46 struct MsgCoder<'a>(&'a Printer);
47 impl<'a> codec::Decoder for MsgCoder<'a> {
48 type Item = Option<NetworkMessage>;
49 type Error = encode::Error;
51 fn decode(&mut self, bytes: &mut bytes::BytesMut) -> Result<Option<Option<NetworkMessage>>, encode::Error> {
52 let mut decoder = BytesDecoder {
56 match RawNetworkMessage::consensus_decode(&mut decoder) {
58 decoder.buf.advance(decoder.pos);
59 if res.magic == Network::Bitcoin.magic() {
60 Ok(Some(Some(res.payload)))
62 Err(encode::Error::UnexpectedNetworkMagic {
63 expected: Network::Bitcoin.magic(),
69 encode::Error::Io(_) => Ok(None),
71 self.0.add_line(format!("Error decoding message: {:?}", e), true);
78 impl<'a> codec::Encoder for MsgCoder<'a> {
79 type Item = NetworkMessage;
80 type Error = std::io::Error;
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(),
86 }.consensus_encode(&mut BytesCoder(res))) {
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);
100 let alphabet = "abcdefghijklmnopqrstuvwxyz234567";
101 let mut acc: u16 = 0;
102 let mut bits: u8 = 0;
104 acc = ((acc << 8) | *i as u16) & ((1 << (8 + 5 - 1)) - 1);
108 let idx = ((acc >> bits) & ((1 << 5) - 1)) as usize;
109 ret += &alphabet[idx..idx + 1];
113 let idx = ((acc << (5 - bits)) & ((1 << 5) - 1)) as usize;
114 ret += &alphabet[idx..idx + 1];
116 while ret.len() % 8 != 0 { ret += "=" };
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);
127 // My seednode's onion addr:
128 assert_eq!(&encode_base32(&[0x6a, 0x8b, 0xd2, 0x78, 0x3f, 0x7a, 0xf8, 0x92, 0x8f, 0x80]), "nkf5e6b7pl4jfd4a");
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) {
137 Err(e) => return future::Either::A(future::err(e)),
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"))
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"))))
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")))
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))))
174 future::Either::B(future::err(std::io::Error::new(std::io::ErrorKind::InvalidData, "Bogus proxy address value")))
181 ).and_then(|(stream, _)| future::ok(stream)).or_else(|(e, _)| future::err(e)))
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)
192 let _ = sender.try_send(NetworkMessage::Version(VersionMessage {
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),
199 user_agent: "/rust-bitcoin:0.18/bluematt-tokio-client:0.1/".to_string(),
203 future::ok((sender, read))
206 Delay::new(Instant::now() + timeout / 10).then(|_| future::err(()))