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.ByteBuffer;
9 import java.nio.channels.SelectionKey;
10 import java.nio.channels.Selector;
11 import java.nio.channels.ServerSocketChannel;
12 import java.nio.channels.SocketChannel;
15 * A NioPeerHandler maps LDK's PeerHandler to Java's NIO I/O interface. It spawns a single background thread which
16 * processes socket events and provides the data to LDK for decryption and processing.
18 public class NioPeerHandler {
19 private static class Peer {
20 SocketDescriptor descriptor;
21 // When we are told by LDK to disconnect, we can't return to LDK until we are sure
22 // won't call any more read/write PeerManager functions with the same connection.
23 // This is set to true if we're in such a condition (with disconnect checked
24 // before with the Peer monitor lock held) and false when we can return.
25 boolean block_disconnect_socket = false;
29 private Peer setup_socket(SocketChannel chan) throws IOException {
30 chan.configureBlocking(false);
31 // Lightning tends to send a number of small messages back and forth between peers quickly, which Nagle is
32 // particularly bad at handling, so we disable it here.
33 chan.setOption(StandardSocketOptions.TCP_NODELAY, true);
36 this.socket_id = this.socket_id + 1;
37 our_id = this.socket_id;
40 final Peer peer = new Peer();
41 SocketDescriptor descriptor = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
43 public long send_data(byte[] data, boolean resume_read) {
45 peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_READ);
49 long written = chan.write(ByteBuffer.wrap(data));
50 if (written != data.length) {
51 peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_WRITE);
55 } catch (IOException e) {
56 // Most likely the socket is disconnected, let the background thread handle it.
62 public void disconnect_socket() {
65 peer.key.channel().close();
67 } catch (IOException ignored) { }
69 while (peer.block_disconnect_socket) {
72 } catch (InterruptedException ignored) { }
76 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == our_id; }
77 @Override public long hash() { return our_id; }
79 peer.descriptor = descriptor;
83 PeerManager peer_manager;
87 volatile boolean shutdown = false;
90 * Constructs a new peer handler, spawning a thread to monitor for socket events.
91 * The background thread will call the PeerManager's timer_tick_occured() function for you on an appropriate schedule.
93 * @param manager The LDK PeerManager which connection data will be provided to.
94 * @throws IOException If an internal java.nio error occurs.
96 public NioPeerHandler(PeerManager manager) throws IOException {
97 this.peer_manager = manager;
98 this.selector = Selector.open();
99 io_thread = new Thread(() -> {
100 ByteBuffer buf = ByteBuffer.allocate(8192);
101 long lastTimerTick = System.currentTimeMillis();
104 this.selector.select(1000);
105 } catch (IOException ignored) {
106 System.err.println("java.nio threw an unexpected IOException. Stopping PeerHandler thread!");
109 if (shutdown) return;
110 if (Thread.interrupted()) return;
111 for (SelectionKey key : this.selector.selectedKeys()) {
112 if ((key.interestOps() & SelectionKey.OP_ACCEPT) != 0) {
113 if (key.isAcceptable()) {
116 chan = ((ServerSocketChannel) key.channel()).accept();
117 } catch (IOException ignored) {
121 if (chan == null) continue;
123 Peer peer = setup_socket(chan);
124 Result_NonePeerHandleErrorZ res = this.peer_manager.new_inbound_connection(peer.descriptor);
125 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_OK) {
126 peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
128 } catch (IOException ignored) { }
130 continue; // There is no attachment so the rest of the loop is useless
132 Peer peer = (Peer) key.attachment();
133 synchronized (peer) {
134 peer.block_disconnect_socket = true;
137 if (key.isValid() && (key.interestOps() & SelectionKey.OP_WRITE) != 0 && key.isWritable()) {
138 Result_NonePeerHandleErrorZ res = this.peer_manager.write_buffer_space_avail(peer.descriptor);
139 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_Err) {
140 key.channel().close();
144 if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
146 int read = ((SocketChannel) key.channel()).read(buf);
148 this.peer_manager.socket_disconnected(peer.descriptor);
150 } else if (read > 0) {
152 byte[] read_bytes = new byte[read];
153 buf.get(read_bytes, 0, read);
154 Result_boolPeerHandleErrorZ res = this.peer_manager.read_event(peer.descriptor, read_bytes);
155 if (res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) {
156 if (((Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) res).res) {
157 key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
160 key.channel().close();
165 } catch (IOException ignored) {
166 try { key.channel().close(); } catch (IOException ignored2) { }
168 peer_manager.socket_disconnected(peer.descriptor);
170 synchronized (peer) {
171 peer.block_disconnect_socket = false;
175 if (lastTimerTick < System.currentTimeMillis() - 30 * 1000) {
176 peer_manager.timer_tick_occured();
177 lastTimerTick = System.currentTimeMillis();
179 peer_manager.process_events();
181 }, "NioPeerHandler NIO Thread");
186 * Connect to a peer given their node id and socket address. Blocks until a connection is established (or returns
187 * IOException) and then the connection handling runs in the background.
189 * @param their_node_id A valid 33-byte public key representing the peer's Lightning Node ID. If this is invalid,
190 * undefined behavior (read: Segfault, etc) may occur.
191 * @param remote The socket address to connect to.
192 * @throws IOException If connecting to the remote endpoint fails or internal java.nio errors occur.
194 public void connect(byte[] their_node_id, SocketAddress remote) throws IOException {
195 SocketChannel chan = SocketChannel.open(remote);
196 Peer peer = setup_socket(chan);
197 Result_CVec_u8ZPeerHandleErrorZ res = this.peer_manager.new_outbound_connection(their_node_id, peer.descriptor);
198 if (res instanceof Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) {
199 byte[] initial_bytes = ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) res).res;
200 if (chan.write(ByteBuffer.wrap(initial_bytes)) != initial_bytes.length) {
201 throw new IOException("We assume TCP socket buffer is at least a single packet in length");
203 peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
204 this.selector.wakeup();
206 throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
211 * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
214 * @param socket_address The address to bind the listening socket to.
215 * @throws IOException if binding the listening socket fail.
217 public void bind_listener(SocketAddress socket_address) throws IOException {
218 ServerSocketChannel listen_channel = ServerSocketChannel.open();
219 listen_channel.bind(socket_address);
220 listen_channel.configureBlocking(false);
221 listen_channel.register(this.selector, SelectionKey.OP_ACCEPT);
222 this.selector.wakeup();
226 * Interrupt the background thread, stopping all peer handling. Disconnection events to the PeerHandler are not made,
227 * potentially leaving the PeerHandler in an inconsistent state.
229 public void interrupt() {
234 } catch (InterruptedException ignored) { }
238 * Calls process_events on the PeerManager immediately. Normally process_events is polled regularly to check for new
239 * messages which need to be sent, but you can interrupt the poll and check immediately by calling this function.
241 public void check_events() {