1 package org.ldk.batteries;
3 import org.ldk.structs.*;
5 import java.io.IOException;
6 import java.net.SocketAddress;
7 import java.net.StandardSocketOptions;
8 import java.nio.Buffer;
9 import java.nio.ByteBuffer;
10 import java.nio.channels.*;
13 * A NioPeerHandler maps LDK's PeerHandler to Java's NIO I/O interface. It spawns a single background thread which
14 * processes socket events and provides the data to LDK for decryption and processing.
16 public class NioPeerHandler {
17 private static class Peer {
18 SocketDescriptor descriptor;
22 // Android's java.nio implementation has a big lock inside the selector, preventing any concurrent access to it.
23 // This appears to largely defeat the entire purpose of java.nio, but we work around it here by explicitly checking
24 // for an Android environment and passing any selector access on any thread other than our internal one through
25 // do_selector_action, which wakes up the selector before accessing it.
26 private static boolean IS_ANDROID;
28 IS_ANDROID = System.getProperty("java.vendor").toLowerCase().contains("android");
30 private boolean wakeup_selector = false;
31 private interface SelectorCall {
32 void meth() throws IOException;
34 private void do_selector_action(SelectorCall meth) throws IOException {
36 wakeup_selector = true;
37 this.selector.wakeup();
38 synchronized (this.selector) {
40 wakeup_selector = false;
47 private Peer setup_socket(SocketChannel chan) throws IOException {
48 chan.configureBlocking(false);
49 // Lightning tends to send a number of small messages back and forth between peers quickly, which Nagle is
50 // particularly bad at handling, so we disable it here.
51 chan.setOption(StandardSocketOptions.TCP_NODELAY, true);
54 this.socket_id = this.socket_id + 1;
55 our_id = this.socket_id;
58 final Peer peer = new Peer();
59 SocketDescriptor descriptor = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
61 public long send_data(byte[] data, boolean resume_read) {
64 do_selector_action(() -> peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_READ));
66 long written = chan.write(ByteBuffer.wrap(data));
67 if (written != data.length) {
68 do_selector_action(() -> peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_WRITE));
71 } catch (IOException e) {
72 // Most likely the socket is disconnected, let the background thread handle it.
78 public void disconnect_socket() {
80 do_selector_action(() -> {
82 peer.key.channel().close();
84 } catch (IOException ignored) { }
86 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == our_id; }
87 @Override public long hash() { return our_id; }
89 peer.descriptor = descriptor;
93 PeerManager peer_manager;
95 final Selector selector;
97 volatile boolean shutdown = false;
100 * Constructs a new peer handler, spawning a thread to monitor for socket events.
102 * @param manager The LDK PeerManager which connection data will be provided to.
103 * @throws IOException If an internal java.nio error occurs.
105 public NioPeerHandler(PeerManager manager) throws IOException {
106 this.peer_manager = manager;
107 this.selector = Selector.open();
108 io_thread = new Thread(() -> {
109 ByteBuffer buf = ByteBuffer.allocate(8192);
114 synchronized (this.selector) {
115 if (!wakeup_selector) {
116 this.selector.select(1000);
122 this.selector.select(1000);
124 } catch (IOException ignored) {
125 System.err.println("java.nio threw an unexpected IOException. Stopping PeerHandler thread!");
128 if (shutdown) return;
129 if (Thread.interrupted()) return;
130 for (SelectionKey key : this.selector.selectedKeys()) {
132 if ((key.interestOps() & SelectionKey.OP_ACCEPT) != 0) {
133 if (key.isAcceptable()) {
136 chan = ((ServerSocketChannel) key.channel()).accept();
137 } catch (IOException ignored) {
141 if (chan == null) continue;
143 Peer peer = setup_socket(chan);
144 Result_NonePeerHandleErrorZ res = this.peer_manager.new_inbound_connection(peer.descriptor);
145 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_OK) {
146 peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
148 } catch (IOException ignored) { }
150 continue; // There is no attachment so the rest of the loop is useless
152 Peer peer = (Peer) key.attachment();
154 if (key.isValid() && (key.interestOps() & SelectionKey.OP_WRITE) != 0 && key.isWritable()) {
155 Result_NonePeerHandleErrorZ res = this.peer_manager.write_buffer_space_avail(peer.descriptor);
156 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_Err) {
157 key.channel().close();
161 if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
162 ((Buffer)buf).clear();
163 int read = ((SocketChannel) key.channel()).read(buf);
165 this.peer_manager.socket_disconnected(peer.descriptor);
167 } else if (read > 0) {
168 ((Buffer)buf).flip();
169 byte[] read_bytes = new byte[read];
170 buf.get(read_bytes, 0, read);
171 Result_boolPeerHandleErrorZ res = this.peer_manager.read_event(peer.descriptor, read_bytes);
172 if (res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) {
173 if (((Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) res).res) {
174 key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
177 key.channel().close();
182 } catch (IOException ignored) {
183 try { key.channel().close(); } catch (IOException ignored2) { }
185 peer_manager.socket_disconnected(peer.descriptor);
187 } catch (CancelledKeyException e) {
188 try { key.channel().close(); } catch (IOException ignored) { }
189 // The key is only cancelled when we have notified the PeerManager that the socket is closed, so
190 // no need to do anything here with the PeerManager.
193 peer_manager.process_events();
195 }, "NioPeerHandler NIO Thread");
200 * Connect to a peer given their node id and socket address. Blocks until a connection is established (or returns
201 * IOException) and then the connection handling runs in the background.
203 * @param their_node_id A valid 33-byte public key representing the peer's Lightning Node ID. If this is invalid,
204 * undefined behavior (read: Segfault, etc) may occur.
205 * @param remote The socket address to connect to.
206 * @param timeout_ms The amount of time, in milliseconds, up to which we will wait for connection to complete.
207 * @throws IOException If connecting to the remote endpoint fails or internal java.nio errors occur.
209 public void connect(byte[] their_node_id, SocketAddress remote, int timeout_ms) throws IOException {
210 SocketChannel chan = SocketChannel.open();
211 chan.configureBlocking(false);
212 Selector open_selector = Selector.open();
213 chan.register(open_selector, SelectionKey.OP_CONNECT);
214 if (!chan.connect(remote)) {
215 open_selector.select(timeout_ms);
217 if (!chan.finishConnect()) { // Note that this may throw its own IOException if we failed for another reason
218 throw new IOException("Timed out");
220 Peer peer = setup_socket(chan);
221 Result_CVec_u8ZPeerHandleErrorZ res = this.peer_manager.new_outbound_connection(their_node_id, peer.descriptor);
222 if (res instanceof Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) {
223 byte[] initial_bytes = ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) res).res;
224 if (chan.write(ByteBuffer.wrap(initial_bytes)) != initial_bytes.length) {
225 throw new IOException("We assume TCP socket buffer is at least a single packet in length");
227 do_selector_action(() -> peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer));
229 throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
234 * Disconnects any connections currently open with the peer with the given node id.
236 * @param their_node_id must be a valid 33-byte public key
238 public void disconnect(byte[] their_node_id) {
239 this.peer_manager.disconnect_by_node_id(their_node_id, false);
243 * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
246 * @param socket_address The address to bind the listening socket to.
247 * @throws IOException if binding the listening socket fail.
249 public void bind_listener(SocketAddress socket_address) throws IOException {
250 ServerSocketChannel listen_channel = ServerSocketChannel.open();
251 listen_channel.bind(socket_address);
252 listen_channel.configureBlocking(false);
253 do_selector_action(() -> listen_channel.register(this.selector, SelectionKey.OP_ACCEPT));
257 * Interrupt the background thread, stopping all peer handling. Disconnection events to the PeerHandler are not made,
258 * potentially leaving the PeerHandler in an inconsistent state.
260 public void interrupt() {
265 } catch (InterruptedException ignored) { }
269 * Calls process_events on the PeerManager immediately. Normally process_events is polled regularly to check for new
270 * messages which need to be sent, but you can interrupt the poll and check immediately by calling this function.
272 public void check_events() {