xmr-btc-swap/swap/src/tor.rs

118 lines
3.9 KiB
Rust
Raw Normal View History

use anyhow::{anyhow, bail, Result};
use std::{
future::Future,
net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4},
};
use tokio::net::TcpStream;
use torut::{
control::{AsyncEvent, AuthenticatedConn, ConnError, UnauthenticatedConn},
onion::TorSecretKeyV3,
};
#[derive(Debug, Clone, Copy)]
pub struct UnauthenticatedConnection {
2020-10-20 01:14:10 -04:00
tor_proxy_address: SocketAddrV4,
tor_control_port_address: SocketAddr,
}
impl Default for UnauthenticatedConnection {
2020-10-20 01:14:10 -04:00
fn default() -> Self {
Self {
tor_proxy_address: SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9050),
tor_control_port_address: SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::LOCALHOST, 9051)),
}
}
}
impl UnauthenticatedConnection {
pub fn with_ports(proxy_port: u16, control_port: u16) -> Self {
Self {
tor_proxy_address: SocketAddrV4::new(Ipv4Addr::LOCALHOST, proxy_port),
tor_control_port_address: SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::LOCALHOST,
control_port,
)),
}
}
2020-10-20 01:14:10 -04:00
/// checks if tor is running
2020-10-20 18:55:47 -04:00
async fn assert_tor_running(&self) -> Result<()> {
2020-10-20 01:14:10 -04:00
// Make sure you are running tor and this is your socks port
let proxy = reqwest::Proxy::all(format!("socks5h://{}", self.tor_proxy_address).as_str())
2020-10-20 18:55:47 -04:00
.map_err(|_| anyhow!("tor proxy should be there"))?;
let client = reqwest::Client::builder().proxy(proxy).build()?;
2020-10-20 01:14:10 -04:00
let res = client.get("https://check.torproject.org").send().await?;
let text = res.text().await?;
2020-10-20 18:55:47 -04:00
if !text.contains("Congratulations. This browser is configured to use Tor.") {
2020-10-20 01:14:10 -04:00
bail!("Tor is currently not running")
}
2020-10-20 18:55:47 -04:00
Ok(())
2020-10-20 01:14:10 -04:00
}
async fn init_unauthenticated_connection(&self) -> Result<UnauthenticatedConn<TcpStream>> {
// Connect to local tor service via control port
2020-10-20 01:14:10 -04:00
let sock = TcpStream::connect(self.tor_control_port_address).await?;
2020-10-20 18:55:47 -04:00
let uc = UnauthenticatedConn::new(sock);
Ok(uc)
}
/// Create a new authenticated connection to your local Tor service
pub async fn init_authenticated_connection(self) -> Result<AuthenticatedConnection> {
2020-10-20 18:55:47 -04:00
self.assert_tor_running().await?;
let mut uc = self
.init_unauthenticated_connection()
.await
.map_err(|_| anyhow!("Tor instance not running."))?;
2020-10-20 18:55:47 -04:00
let tor_info = uc
.load_protocol_info()
.await
.map_err(|_| anyhow!("Failed to load protocol info from Tor."))?;
let tor_auth_data = tor_info
.make_auth_data()?
2020-10-20 18:55:47 -04:00
.ok_or_else(|| anyhow!("Failed to make auth data."))?;
// Get an authenticated connection to the Tor via the Tor Controller protocol.
2020-10-20 18:55:47 -04:00
uc.authenticate(&tor_auth_data)
.await
2020-10-20 18:55:47 -04:00
.map_err(|_| anyhow!("Failed to authenticate with Tor"))?;
2020-10-20 01:14:10 -04:00
Ok(AuthenticatedConnection {
2020-10-20 18:55:47 -04:00
authenticated_connection: uc.into_authenticated().await,
2020-10-20 01:14:10 -04:00
})
}
}
type Handler = fn(AsyncEvent<'_>) -> Box<dyn Future<Output = Result<(), ConnError>> + Unpin>;
#[allow(missing_debug_implementations)]
pub struct AuthenticatedConnection {
authenticated_connection: AuthenticatedConn<TcpStream, Handler>,
}
impl AuthenticatedConnection {
/// Add an ephemeral tor service on localhost with the provided key
pub async fn add_service(&mut self, port: u16, tor_key: &TorSecretKeyV3) -> Result<()> {
self.authenticated_connection
.add_onion_v3(
tor_key,
false,
false,
false,
None,
&mut [(
port,
SocketAddr::new(IpAddr::from(Ipv4Addr::new(127, 0, 0, 1)), port),
)]
.iter(),
)
.await
2020-10-21 02:53:49 -04:00
.map_err(|e| anyhow!("Could not add onion service.: {:#?}", e))
}
}