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;
14 public class NioPeerHandler {
15 private static class Peer {
16 SocketDescriptor descriptor;
17 // When we are told by LDK to disconnect, we can't return to LDK until we are sure
18 // won't call any more read/write PeerManager functions with the same connection.
19 // This is set to true if we're in such a condition (with disconnect checked
20 // before with the Peer monitor lock held) and false when we can return.
21 boolean block_disconnect_socket = false;
25 private Peer setup_socket(SocketChannel chan) throws IOException {
26 chan.configureBlocking(false);
27 // Lightning tends to send a number of small messages back and forth between peers quickly, which Nagle is
28 // particularly bad at handling, so we disable it here.
29 chan.setOption(StandardSocketOptions.TCP_NODELAY, true);
32 this.socket_id = this.socket_id + 1;
33 our_id = this.socket_id;
36 final Peer peer = new Peer();
37 SocketDescriptor descriptor = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
39 public long send_data(byte[] data, boolean resume_read) {
41 peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_READ);
44 long written = chan.write(ByteBuffer.wrap(data));
45 if (written != data.length) {
46 peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_WRITE);
49 } catch (IOException e) {
50 // Most likely the socket is disconnected, let the background thread handle it.
56 public void disconnect_socket() {
59 peer.key.channel().close();
61 } catch (IOException ignored) { }
63 while (peer.block_disconnect_socket) {
66 } catch (InterruptedException ignored) { }
70 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == our_id; }
71 @Override public long hash() { return our_id; }
73 peer.descriptor = descriptor;
77 PeerManager peer_manager;
81 volatile boolean shutdown = false;
84 * Constructs a new peer handler, spawning a thread to monitor for socket events.
85 * The background thread will call the PeerManager's timer_tick_occured() function for you on an appropriate schedule.
87 * @param manager The LDK PeerManager which connection data will be provided to.
88 * @throws IOException If an internal java.nio error occurs.
90 public NioPeerHandler(PeerManager manager) throws IOException {
91 long id = manager._test_only_get_ptr();
92 this.peer_manager = manager;
93 this.selector = Selector.open();
94 io_thread = new Thread(() -> {
95 ByteBuffer buf = ByteBuffer.allocate(8192);
96 long lastTimerTick = System.currentTimeMillis();
99 this.selector.select(1000);
100 } catch (IOException ignored) {
101 System.err.println("java.nio threw an unexpected IOException. Stopping PeerHandler thread!");
104 if (shutdown) return;
105 if (Thread.interrupted()) return;
106 for (SelectionKey key : this.selector.selectedKeys()) {
107 if ((key.interestOps() & SelectionKey.OP_ACCEPT) != 0) {
108 if (key.isAcceptable()) {
111 chan = ((ServerSocketChannel) key.channel()).accept();
112 } catch (IOException ignored) {
116 if (chan == null) continue;
118 Peer peer = setup_socket(chan);
119 Result_NonePeerHandleErrorZ res = this.peer_manager.new_inbound_connection(peer.descriptor);
120 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_OK) {
121 peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
123 } catch (IOException ignored) { }
125 continue; // There is no attachment so the rest of the loop is useless
127 Peer peer = (Peer) key.attachment();
128 synchronized (peer) {
129 peer.block_disconnect_socket = true;
132 if (key.isValid() && (key.interestOps() & SelectionKey.OP_WRITE) != 0 && key.isWritable()) {
133 Result_NonePeerHandleErrorZ res = this.peer_manager.write_buffer_space_avail(peer.descriptor);
134 if (res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_Err) {
135 key.channel().close();
139 if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
141 int read = ((SocketChannel) key.channel()).read(buf);
143 this.peer_manager.socket_disconnected(peer.descriptor);
145 } else if (read > 0) {
147 byte[] read_bytes = new byte[read];
148 buf.get(read_bytes, 0, read);
149 Result_boolPeerHandleErrorZ res = this.peer_manager.read_event(peer.descriptor, read_bytes);
150 if (res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) {
151 if (((Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK) res).res) {
152 key.interestOps(key.interestOps() & (~SelectionKey.OP_READ));
155 key.channel().close();
160 } catch (IOException ignored) {
161 try { key.channel().close(); } catch (IOException ignored2) { }
163 peer_manager.socket_disconnected(peer.descriptor);
165 synchronized (peer) {
166 peer.block_disconnect_socket = false;
170 if (lastTimerTick < System.currentTimeMillis() - 30 * 1000) {
171 peer_manager.timer_tick_occured();
172 lastTimerTick = System.currentTimeMillis();
174 peer_manager.process_events();
176 }, "NioPeerHandler NIO Thread");
181 * Connect to a peer given their node id and socket address. Blocks until a connection is established (or returns
182 * IOException) and then the connection handling runs in the background.
184 * @param their_node_id A valid 33-byte public key representing the peer's Lightning Node ID. If this is invalid,
185 * undefined behavior (read: Segfault, etc) may occur.
186 * @param remote The socket address to connect to.
187 * @throws IOException If connecting to the remote endpoint fails or internal java.nio errors occur.
189 public void connect(byte[] their_node_id, SocketAddress remote) throws IOException {
190 SocketChannel chan = SocketChannel.open(remote);
191 Peer peer = setup_socket(chan);
192 Result_CVec_u8ZPeerHandleErrorZ res = this.peer_manager.new_outbound_connection(their_node_id, peer.descriptor);
193 if (res instanceof Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) {
194 byte[] initial_bytes = ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) res).res;
195 if (chan.write(ByteBuffer.wrap(initial_bytes)) != initial_bytes.length) {
196 throw new IOException("We assume TCP socket buffer is at least a single packet in length");
198 peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
199 this.selector.wakeup();
201 throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
206 * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
209 * @param socket_address The address to bind the listening socket to.
210 * @throws IOException if binding the listening socket fail.
212 public void bind_listener(SocketAddress socket_address) throws IOException {
213 ServerSocketChannel listen_channel = ServerSocketChannel.open();
214 listen_channel.bind(socket_address);
215 listen_channel.configureBlocking(false);
216 listen_channel.register(this.selector, SelectionKey.OP_ACCEPT);
217 this.selector.wakeup();
221 * Interrupt the background thread, stopping all peer handling. Disconnection events to the PeerHandler are not made,
222 * potentially leaving the PeerHandler in an inconsistent state.
224 public void interrupt() {
229 } catch (InterruptedException ignored) { }
233 * Calls process_events on the PeerManager immediately. Normally process_events is polled regularly to check for new
234 * messages which need to be sent, but you can interrupt the poll and check immediately by calling this function.
236 public void check_events() {