Merge pull request #10 from galderz/t_compilation_error
[ldk-java] / src / main / java / org / ldk / batteries / NioPeerHandler.java
1 package org.ldk.batteries;
2
3 import org.ldk.structs.*;
4
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;
13
14 /**
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.
17  */
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;
26         SelectionKey key;
27     }
28
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);
34         long our_id;
35         synchronized (this) {
36             this.socket_id = this.socket_id + 1;
37             our_id = this.socket_id;
38         }
39
40         final Peer peer = new Peer();
41         SocketDescriptor descriptor = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
42             @Override
43             public long send_data(byte[] data, boolean resume_read) {
44                 if (resume_read) {
45                     peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_READ);
46                     selector.wakeup();
47                 }
48                 try {
49                     long written = chan.write(ByteBuffer.wrap(data));
50                     if (written != data.length) {
51                         peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_WRITE);
52                         selector.wakeup();
53                     }
54                     return written;
55                 } catch (IOException e) {
56                     // Most likely the socket is disconnected, let the background thread handle it.
57                     return 0;
58                 }
59             }
60
61             @Override
62             public void disconnect_socket() {
63                 try {
64                     peer.key.cancel();
65                     peer.key.channel().close();
66                     selector.wakeup();
67                 } catch (IOException ignored) { }
68                 synchronized (peer) {
69                     while (peer.block_disconnect_socket) {
70                         try {
71                             peer.wait();
72                         } catch (InterruptedException ignored) { }
73                     }
74                 }
75             }
76             @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == our_id; }
77             @Override public long hash() { return our_id; }
78         });
79         peer.descriptor = descriptor;
80         return peer;
81     }
82
83     PeerManager peer_manager;
84     Thread io_thread;
85     Selector selector;
86     long socket_id;
87     volatile boolean shutdown = false;
88
89     /**
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.
92      *
93      * @param manager The LDK PeerManager which connection data will be provided to.
94      * @throws IOException If an internal java.nio error occurs.
95      */
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();
102             while (true) {
103                 try {
104                     this.selector.select(1000);
105                 } catch (IOException ignored) {
106                     System.err.println("java.nio threw an unexpected IOException. Stopping PeerHandler thread!");
107                     return;
108                 }
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()) {
114                             SocketChannel chan;
115                             try {
116                                 chan = ((ServerSocketChannel) key.channel()).accept();
117                             } catch (IOException ignored) {
118                                 key.cancel();
119                                 continue;
120                             }
121                             if (chan == null) continue;
122                             try {
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);
127                                 }
128                             } catch (IOException ignored) { }
129                         }
130                         continue; // There is no attachment so the rest of the loop is useless
131                     }
132                     Peer peer = (Peer) key.attachment();
133                     synchronized (peer) {
134                         peer.block_disconnect_socket = true;
135                     }
136                     try {
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();
141                                 key.cancel();
142                             }
143                         }
144                         if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
145                             buf.clear();
146                             int read = ((SocketChannel) key.channel()).read(buf);
147                             if (read == -1) {
148                                 this.peer_manager.socket_disconnected(peer.descriptor);
149                                 key.cancel();
150                             } else if (read > 0) {
151                                 buf.flip();
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));
158                                     }
159                                 } else {
160                                     key.channel().close();
161                                     key.cancel();
162                                 }
163                             }
164                         }
165                     } catch (IOException ignored) {
166                         try { key.channel().close(); } catch (IOException ignored2) { }
167                         key.cancel();
168                         peer_manager.socket_disconnected(peer.descriptor);
169                     }
170                     synchronized (peer) {
171                         peer.block_disconnect_socket = false;
172                         peer.notifyAll();
173                     }
174                 }
175                 if (lastTimerTick < System.currentTimeMillis() - 30 * 1000) {
176                     peer_manager.timer_tick_occurred();
177                     lastTimerTick = System.currentTimeMillis();
178                 }
179                 peer_manager.process_events();
180             }
181         }, "NioPeerHandler NIO Thread");
182         io_thread.start();
183     }
184
185     /**
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.
188      *
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      * @param timeout_ms The amount of time, in milliseconds, up to which we will wait for connection to complete.
193      * @throws IOException If connecting to the remote endpoint fails or internal java.nio errors occur.
194      */
195     public void connect(byte[] their_node_id, SocketAddress remote, int timeout_ms) throws IOException {
196         SocketChannel chan = SocketChannel.open();
197         chan.configureBlocking(false);
198         Selector open_selector = Selector.open();
199         chan.register(open_selector, SelectionKey.OP_CONNECT);
200         if (!chan.connect(remote)) {
201             open_selector.select(timeout_ms);
202         }
203         if (!chan.finishConnect()) { // Note that this may throw its own IOException if we failed for another reason
204             throw new IOException("Timed out");
205         }
206         Peer peer = setup_socket(chan);
207         Result_CVec_u8ZPeerHandleErrorZ res = this.peer_manager.new_outbound_connection(their_node_id, peer.descriptor);
208         if (res instanceof  Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) {
209             byte[] initial_bytes = ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) res).res;
210             if (chan.write(ByteBuffer.wrap(initial_bytes)) != initial_bytes.length) {
211                 throw new IOException("We assume TCP socket buffer is at least a single packet in length");
212             }
213             peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
214             this.selector.wakeup();
215         } else {
216             throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
217         }
218     }
219
220     /**
221      * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
222      * thread.
223      *
224      * @param socket_address The address to bind the listening socket to.
225      * @throws IOException if binding the listening socket fail.
226      */
227     public void bind_listener(SocketAddress socket_address) throws IOException {
228         ServerSocketChannel listen_channel = ServerSocketChannel.open();
229         listen_channel.bind(socket_address);
230         listen_channel.configureBlocking(false);
231         listen_channel.register(this.selector, SelectionKey.OP_ACCEPT);
232         this.selector.wakeup();
233     }
234
235     /**
236      * Interrupt the background thread, stopping all peer handling. Disconnection events to the PeerHandler are not made,
237      * potentially leaving the PeerHandler in an inconsistent state.
238      */
239     public void interrupt() {
240         shutdown = true;
241         selector.wakeup();
242         try {
243             io_thread.join();
244         } catch (InterruptedException ignored) { }
245     }
246
247     /**
248      * Calls process_events on the PeerManager immediately. Normally process_events is polled regularly to check for new
249      * messages which need to be sent, but you can interrupt the poll and check immediately by calling this function.
250      */
251     public void check_events() {
252         selector.wakeup();
253     }
254 }