From e696c6f8d23e41e228cec2e74759a2d2868912c7 Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Tue, 9 Mar 2021 23:48:31 -0500 Subject: [PATCH] Add a timeout to NioPeerHandler.connect --- .../java/org/ldk/batteries/NioPeerHandler.java | 14 ++++++++++++-- src/test/java/org/ldk/HumanObjectPeerTest.java | 2 +- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/main/java/org/ldk/batteries/NioPeerHandler.java b/src/main/java/org/ldk/batteries/NioPeerHandler.java index 14c5611d..a77f1f0f 100644 --- a/src/main/java/org/ldk/batteries/NioPeerHandler.java +++ b/src/main/java/org/ldk/batteries/NioPeerHandler.java @@ -189,10 +189,20 @@ public class NioPeerHandler { * @param their_node_id A valid 33-byte public key representing the peer's Lightning Node ID. If this is invalid, * undefined behavior (read: Segfault, etc) may occur. * @param remote The socket address to connect to. + * @param timeout_ms The amount of time, in milliseconds, up to which we will wait for connection to complete. * @throws IOException If connecting to the remote endpoint fails or internal java.nio errors occur. */ - public void connect(byte[] their_node_id, SocketAddress remote) throws IOException { - SocketChannel chan = SocketChannel.open(remote); + public void connect(byte[] their_node_id, SocketAddress remote, int timeout_ms) throws IOException { + SocketChannel chan = SocketChannel.open(); + chan.configureBlocking(false); + Selector open_selector = Selector.open(); + chan.register(open_selector, SelectionKey.OP_CONNECT); + if (!chan.connect(remote)) { + open_selector.select(timeout_ms); + } + if (!chan.finishConnect()) { // Note that this may throw its own IOException if we failed for another reason + throw new IOException("Timed out"); + } Peer peer = setup_socket(chan); Result_CVec_u8ZPeerHandleErrorZ res = this.peer_manager.new_outbound_connection(their_node_id, peer.descriptor); if (res instanceof Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) { diff --git a/src/test/java/org/ldk/HumanObjectPeerTest.java b/src/test/java/org/ldk/HumanObjectPeerTest.java index 2cc67a00..a8d439ec 100644 --- a/src/test/java/org/ldk/HumanObjectPeerTest.java +++ b/src/test/java/org/ldk/HumanObjectPeerTest.java @@ -463,7 +463,7 @@ class HumanObjectPeerTestInstance { void connect_peers(final Peer peer1, final Peer peer2) { if (use_nio_peer_handler) { try { - peer1.nio_peer_handler.connect(peer2.chan_manager.get_our_node_id(), new InetSocketAddress("127.0.0.1", peer2.nio_port)); + peer1.nio_peer_handler.connect(peer2.chan_manager.get_our_node_id(), new InetSocketAddress("127.0.0.1", peer2.nio_port), 100); } catch (IOException e) { assert false; } } else { DescriptorHolder descriptor1 = new DescriptorHolder(); -- 2.39.5