Skip to content

Commit 6f315f2

Browse files
committed
Pass the addr field of tor_connect_outbound to connection setup
When `setup_outbound` was used to setup a connection proxied over Tor, it previously set the remote address of the peer to the address of the Tor proxy. This address of the Tor proxy was assigned to the `PeerDetails::socket_address` for that peer in `PeerManager::list_peers`, and if it was not a private IPv4 or IPv6 address, it was also reported to the peer in our init message. This commit refactors `tor_connect_outbound` to pass its own peer address parameter directly to the connection setup code. This peer address will now appear in `PeerManager::list_peers` for outbound Tor connections made using `tor_connect_outbound`, and will be reported to the peer in our init message if it is not a private IPv4 or IPv6 address.
1 parent 8679d8d commit 6f315f2

File tree

1 file changed

+157
-13
lines changed

1 file changed

+157
-13
lines changed

lightning-net-tokio/src/lib.rs

Lines changed: 157 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -384,6 +384,16 @@ where
384384
PM::Target: APeerManager<Descriptor = SocketDescriptor>,
385385
{
386386
let remote_addr = get_addr_from_stream(&stream);
387+
setup_outbound_internal(peer_manager, their_node_id, stream, remote_addr)
388+
}
389+
390+
fn setup_outbound_internal<PM: Deref + 'static + Send + Sync + Clone>(
391+
peer_manager: PM, their_node_id: PublicKey, stream: StdTcpStream,
392+
remote_addr: Option<SocketAddress>,
393+
) -> impl std::future::Future<Output = ()>
394+
where
395+
PM::Target: APeerManager<Descriptor = SocketDescriptor>,
396+
{
387397
let (reader, mut write_receiver, read_receiver, us) = Connection::new(stream);
388398
#[cfg(test)]
389399
let last_us = Arc::clone(&us);
@@ -478,8 +488,15 @@ where
478488
/// Routes [`connect_outbound`] through Tor. Implements stream isolation for each connection
479489
/// using a stream isolation parameter sourced from [`EntropySource::get_secure_random_bytes`].
480490
///
491+
/// The `addr` parameter will be set to the [`PeerDetails::socket_address`] for that peer in
492+
/// [`PeerManager::list_peers`], and if it is not a private IPv4 or IPv6 address, it will also
493+
/// reported to the peer in our init message.
494+
///
481495
/// Returns a future (as the fn is async) that yields another future, see [`connect_outbound`] for
482496
/// details on this return value.
497+
///
498+
/// [`PeerDetails::socket_address`]: lightning::ln::peer_handler::PeerDetails::socket_address
499+
/// [`PeerManager::list_peers`]: lightning::ln::peer_handler::PeerManager::list_peers
483500
pub async fn tor_connect_outbound<PM: Deref + 'static + Send + Sync + Clone, ES: EntropySource>(
484501
peer_manager: PM, their_node_id: PublicKey, addr: SocketAddress, tor_proxy_addr: SocketAddr,
485502
entropy_source: ES,
@@ -488,12 +505,14 @@ where
488505
PM::Target: APeerManager<Descriptor = SocketDescriptor>,
489506
{
490507
let connect_fut = async {
491-
tor_connect(addr, tor_proxy_addr, entropy_source).await.map(|s| s.into_std().unwrap())
508+
tor_connect(addr.clone(), tor_proxy_addr, entropy_source)
509+
.await
510+
.map(|s| s.into_std().unwrap())
492511
};
493512
if let Ok(Ok(stream)) =
494513
time::timeout(Duration::from_secs(TOR_CONNECT_OUTBOUND_TIMEOUT), connect_fut).await
495514
{
496-
Some(setup_outbound(peer_manager, their_node_id, stream))
515+
Some(setup_outbound_internal(peer_manager, their_node_id, stream, Some(addr)))
497516
} else {
498517
None
499518
}
@@ -772,7 +791,7 @@ mod tests {
772791
use lightning::ln::types::ChannelId;
773792
use lightning::routing::gossip::NodeId;
774793
use lightning::types::features::*;
775-
use lightning::util::test_utils::TestNodeSigner;
794+
use lightning::util::test_utils::{TestLogger, TestNodeSigner};
776795

777796
use tokio::sync::mpsc;
778797

@@ -781,13 +800,6 @@ mod tests {
781800
use std::sync::{Arc, Mutex};
782801
use std::time::Duration;
783802

784-
pub struct TestLogger();
785-
impl lightning::util::logger::Logger for TestLogger {
786-
fn log(&self, record: lightning::util::logger::Record) {
787-
println!("{}", record);
788-
}
789-
}
790-
791803
struct MsgHandler {
792804
expected_pubkey: PublicKey,
793805
pubkey_connected: mpsc::Sender<()>,
@@ -981,7 +993,7 @@ mod tests {
981993
a_msg_handler,
982994
0,
983995
&[1; 32],
984-
Arc::new(TestLogger()),
996+
Arc::new(TestLogger::new()),
985997
Arc::new(TestNodeSigner::new(a_key)),
986998
));
987999

@@ -1005,7 +1017,7 @@ mod tests {
10051017
b_msg_handler,
10061018
0,
10071019
&[2; 32],
1008-
Arc::new(TestLogger()),
1020+
Arc::new(TestLogger::new()),
10091021
Arc::new(TestNodeSigner::new(b_key)),
10101022
));
10111023

@@ -1068,7 +1080,7 @@ mod tests {
10681080
a_msg_handler,
10691081
0,
10701082
&[1; 32],
1071-
Arc::new(TestLogger()),
1083+
Arc::new(TestLogger::new()),
10721084
Arc::new(TestNodeSigner::new(a_key)),
10731085
));
10741086

@@ -1154,4 +1166,136 @@ mod tests {
11541166
assert!(tor_connect(addr, tor_proxy_addr, &entropy_source).await.is_err());
11551167
}
11561168
}
1169+
1170+
async fn test_remote_address_with_override(b_addr_override: Option<SocketAddress>) {
1171+
let secp_ctx = Secp256k1::new();
1172+
let a_key = SecretKey::from_slice(&[1; 32]).unwrap();
1173+
let b_key = SecretKey::from_slice(&[1; 32]).unwrap();
1174+
let a_pub = PublicKey::from_secret_key(&secp_ctx, &a_key);
1175+
let b_pub = PublicKey::from_secret_key(&secp_ctx, &b_key);
1176+
1177+
let (a_connected_sender, mut a_connected) = mpsc::channel(1);
1178+
let (a_disconnected_sender, _a_disconnected) = mpsc::channel(1);
1179+
let a_handler = Arc::new(MsgHandler {
1180+
expected_pubkey: b_pub,
1181+
pubkey_connected: a_connected_sender,
1182+
pubkey_disconnected: a_disconnected_sender,
1183+
disconnected_flag: AtomicBool::new(false),
1184+
msg_events: Mutex::new(Vec::new()),
1185+
});
1186+
let a_msg_handler = MessageHandler {
1187+
chan_handler: Arc::clone(&a_handler),
1188+
route_handler: Arc::clone(&a_handler),
1189+
onion_message_handler: Arc::new(IgnoringMessageHandler {}),
1190+
custom_message_handler: Arc::new(IgnoringMessageHandler {}),
1191+
send_only_message_handler: Arc::new(IgnoringMessageHandler {}),
1192+
};
1193+
let a_logger = Arc::new(TestLogger::new());
1194+
let a_manager = Arc::new(PeerManager::new(
1195+
a_msg_handler,
1196+
0,
1197+
&[1; 32],
1198+
Arc::clone(&a_logger),
1199+
Arc::new(TestNodeSigner::new(a_key)),
1200+
));
1201+
1202+
let (b_connected_sender, mut b_connected) = mpsc::channel(1);
1203+
let (b_disconnected_sender, _b_disconnected) = mpsc::channel(1);
1204+
let b_handler = Arc::new(MsgHandler {
1205+
expected_pubkey: a_pub,
1206+
pubkey_connected: b_connected_sender,
1207+
pubkey_disconnected: b_disconnected_sender,
1208+
disconnected_flag: AtomicBool::new(false),
1209+
msg_events: Mutex::new(Vec::new()),
1210+
});
1211+
let b_msg_handler = MessageHandler {
1212+
chan_handler: Arc::clone(&b_handler),
1213+
route_handler: Arc::clone(&b_handler),
1214+
onion_message_handler: Arc::new(IgnoringMessageHandler {}),
1215+
custom_message_handler: Arc::new(IgnoringMessageHandler {}),
1216+
send_only_message_handler: Arc::new(IgnoringMessageHandler {}),
1217+
};
1218+
let b_logger = Arc::new(TestLogger::new());
1219+
let b_manager = Arc::new(PeerManager::new(
1220+
b_msg_handler,
1221+
0,
1222+
&[2; 32],
1223+
Arc::clone(&b_logger),
1224+
Arc::new(TestNodeSigner::new(b_key)),
1225+
));
1226+
1227+
// We bind on localhost, hoping the environment is properly configured with a local
1228+
// address. This may not always be the case in containers and the like, so if this test is
1229+
// failing for you check that you have a loopback interface and it is configured with
1230+
// 127.0.0.1.
1231+
let (conn_a, conn_b) = make_tcp_connection();
1232+
1233+
// Given that `make_tcp_connection` binds the peer to 127.0.0.1,
1234+
// `get_addr_from_stream` always returns a private address, and will not be reported to the peer
1235+
// in the init message.
1236+
let b_addr = b_addr_override
1237+
.clone()
1238+
.unwrap_or_else(|| super::get_addr_from_stream(&conn_a).unwrap());
1239+
let _fut_a = super::setup_outbound_internal(
1240+
Arc::clone(&a_manager),
1241+
b_pub,
1242+
conn_a,
1243+
Some(b_addr.clone()),
1244+
);
1245+
let _fut_b = super::setup_inbound(Arc::clone(&b_manager), conn_b);
1246+
1247+
tokio::time::timeout(Duration::from_secs(10), a_connected.recv()).await.unwrap();
1248+
tokio::time::timeout(Duration::from_secs(1), b_connected.recv()).await.unwrap();
1249+
1250+
// Check `PeerDetails::socket_address`
1251+
1252+
let mut peers = a_manager.list_peers();
1253+
assert_eq!(peers.len(), 1);
1254+
let peer = peers.pop().unwrap();
1255+
assert_eq!(peer.socket_address, Some(b_addr));
1256+
1257+
// Check the init message sent to the peer
1258+
1259+
let mainnet_hash = ChainHash::using_genesis_block(Network::Testnet);
1260+
let a_init_msg = Init {
1261+
features: InitFeatures::empty(),
1262+
networks: Some(vec![mainnet_hash]),
1263+
// We set it to the override here because addresses from the stream are private addresses,
1264+
// so they are filtered out and not reported to the peer
1265+
remote_network_address: b_addr_override,
1266+
};
1267+
a_logger.assert_log(
1268+
"lightning::ln::peer_handler",
1269+
format!("Enqueueing message Init({:?})", a_init_msg),
1270+
1,
1271+
);
1272+
}
1273+
1274+
#[tokio::test]
1275+
async fn test_remote_address() {
1276+
// Test that the remote address of the peer passed to `setup_outbound_internal` is set correctly in the
1277+
// corresponding `PeerDetails::socket_address` returned from `PeerManager::list_peers`, and if it is
1278+
// not a private address, that it is reported to the peer in the init message.
1279+
1280+
// This tests a private address read from `get_addr_from_stream`
1281+
test_remote_address_with_override(None).await;
1282+
// Make sure these are not private IPv4 or IPv6 addresses; we assert they are present in the init message
1283+
test_remote_address_with_override(Some(SocketAddress::TcpIpV4 {
1284+
addr: [0xab; 4],
1285+
port: 0xabab,
1286+
}))
1287+
.await;
1288+
test_remote_address_with_override(Some(SocketAddress::TcpIpV6 {
1289+
addr: [0x2a; 16],
1290+
port: 0x2a2a,
1291+
}))
1292+
.await;
1293+
let torproject_onion_addr_str =
1294+
"2gzyxa5ihm7nsggfxnu52rck2vv4rvmdlkiu3zzui5du4xyclen53wid.onion:80";
1295+
let torproject_onion_addr: SocketAddress = torproject_onion_addr_str.parse().unwrap();
1296+
test_remote_address_with_override(Some(torproject_onion_addr)).await;
1297+
let torproject_addr_str = "torproject.org:80";
1298+
let torproject_addr: SocketAddress = torproject_addr_str.parse().unwrap();
1299+
test_remote_address_with_override(Some(torproject_addr)).await;
1300+
}
11571301
}

0 commit comments

Comments
 (0)