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.
101 * The background thread will call the PeerManager's timer_tick_occured() function for you on an appropriate schedule.
103 * @param manager The LDK PeerManager which connection data will be provided to.
104 * @throws IOException If an internal java.nio error occurs.
106 public NioPeerHandler(PeerManager manager) throws IOException {
107 this.peer_manager = manager;
108 this.selector = Selector.open();
109 io_thread = new Thread(() -> {
110 ByteBuffer buf = ByteBuffer.allocate(8192);
111 long lastTimerTick = System.currentTimeMillis();
116 synchronized (this.selector) {
117 if (!wakeup_selector) {
118 this.selector.select(1000);
124 this.selector.select(1000);
126 } catch (IOException ignored) {
127 System.err.println("java.nio threw an unexpected IOException. Stopping PeerHandler thread!");
130 if (shutdown) return;
131 if (Thread.interrupted()) return;
132 for (SelectionKey key : this.selector.selectedKeys()) {
134 if ((key.interestOps() & SelectionKey.OP_ACCEPT) != 0) {
135 if (key.isAcceptable()) {
138 chan = ((ServerSocketChannel) key.channel()).accept();
139 } catch (IOException ignored) {
143 if (chan == null) continue;
145 Peer peer = setup_socket(chan);
146 Result_NonePeerHandleErrorZ res = this.peer_manager.new_inbound_connection(peer.descriptor);
147 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_OK) {
148 peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
150 } catch (IOException ignored) { }
152 continue; // There is no attachment so the rest of the loop is useless
154 Peer peer = (Peer) key.attachment();
156 if (key.isValid() && (key.interestOps() & SelectionKey.OP_WRITE) != 0 && key.isWritable()) {
157 Result_NonePeerHandleErrorZ res = this.peer_manager.write_buffer_space_avail(peer.descriptor);
158 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_Err) {
159 key.channel().close();
163 if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
164 ((Buffer)buf).clear();
165 int read = ((SocketChannel) key.channel()).read(buf);
167 this.peer_manager.socket_disconnected(peer.descriptor);
169 } else if (read > 0) {
170 ((Buffer)buf).flip();
171 byte[] read_bytes = new byte[read];
172 buf.get(read_bytes, 0, read);
173 Result_boolPeerHandleErrorZ res = this.peer_manager.read_event(peer.descriptor, read_bytes);
174 if (res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) {
175 if (((Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) res).res) {
176 key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
179 key.channel().close();
184 } catch (IOException ignored) {
185 try { key.channel().close(); } catch (IOException ignored2) { }
187 peer_manager.socket_disconnected(peer.descriptor);
189 } catch (CancelledKeyException e) {
190 try { key.channel().close(); } catch (IOException ignored) { }
191 // The key is only cancelled when we have notified the PeerManager that the socket is closed, so
192 // no need to do anything here with the PeerManager.
195 if (lastTimerTick < System.currentTimeMillis() - 30 * 1000) {
196 peer_manager.timer_tick_occurred();
197 lastTimerTick = System.currentTimeMillis();
199 peer_manager.process_events();
201 }, "NioPeerHandler NIO Thread");
206 * Connect to a peer given their node id and socket address. Blocks until a connection is established (or returns
207 * IOException) and then the connection handling runs in the background.
209 * @param their_node_id A valid 33-byte public key representing the peer's Lightning Node ID. If this is invalid,
210 * undefined behavior (read: Segfault, etc) may occur.
211 * @param remote The socket address to connect to.
212 * @param timeout_ms The amount of time, in milliseconds, up to which we will wait for connection to complete.
213 * @throws IOException If connecting to the remote endpoint fails or internal java.nio errors occur.
215 public void connect(byte[] their_node_id, SocketAddress remote, int timeout_ms) throws IOException {
216 SocketChannel chan = SocketChannel.open();
217 chan.configureBlocking(false);
218 Selector open_selector = Selector.open();
219 chan.register(open_selector, SelectionKey.OP_CONNECT);
220 if (!chan.connect(remote)) {
221 open_selector.select(timeout_ms);
223 if (!chan.finishConnect()) { // Note that this may throw its own IOException if we failed for another reason
224 throw new IOException("Timed out");
226 Peer peer = setup_socket(chan);
227 Result_CVec_u8ZPeerHandleErrorZ res = this.peer_manager.new_outbound_connection(their_node_id, peer.descriptor);
228 if (res instanceof Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) {
229 byte[] initial_bytes = ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) res).res;
230 if (chan.write(ByteBuffer.wrap(initial_bytes)) != initial_bytes.length) {
231 throw new IOException("We assume TCP socket buffer is at least a single packet in length");
233 do_selector_action(() -> peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer));
235 throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
240 * Disconnects any connections currently open with the peer with the given node id.
242 * @param their_node_id must be a valid 33-byte public key
244 public void disconnect(byte[] their_node_id) {
245 this.peer_manager.disconnect_by_node_id(their_node_id, false);
249 * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
252 * @param socket_address The address to bind the listening socket to.
253 * @throws IOException if binding the listening socket fail.
255 public void bind_listener(SocketAddress socket_address) throws IOException {
256 ServerSocketChannel listen_channel = ServerSocketChannel.open();
257 listen_channel.bind(socket_address);
258 listen_channel.configureBlocking(false);
259 do_selector_action(() -> listen_channel.register(this.selector, SelectionKey.OP_ACCEPT));
263 * Interrupt the background thread, stopping all peer handling. Disconnection events to the PeerHandler are not made,
264 * potentially leaving the PeerHandler in an inconsistent state.
266 public void interrupt() {
271 } catch (InterruptedException ignored) { }
275 * Calls process_events on the PeerManager immediately. Normally process_events is polled regularly to check for new
276 * messages which need to be sent, but you can interrupt the poll and check immediately by calling this function.
278 public void check_events() {