Drop dup PeerManager tiemr_tick_occurred calls from NioPeerHandler
[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.Buffer;
9 import java.nio.ByteBuffer;
10 import java.nio.channels.*;
11
12 /**
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.
15  */
16 public class NioPeerHandler {
17     private static class Peer {
18         SocketDescriptor descriptor;
19         SelectionKey key;
20     }
21
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;
27     static {
28         IS_ANDROID = System.getProperty("java.vendor").toLowerCase().contains("android");
29     }
30     private boolean wakeup_selector = false;
31     private interface SelectorCall {
32         void meth() throws IOException;
33     }
34     private void do_selector_action(SelectorCall meth) throws IOException {
35         if (IS_ANDROID) {
36             wakeup_selector = true;
37             this.selector.wakeup();
38             synchronized (this.selector) {
39                 meth.meth();
40                 wakeup_selector = false;
41             }
42         } else {
43             meth.meth();
44         }
45     }
46
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);
52         long our_id;
53         synchronized (this) {
54             this.socket_id = this.socket_id + 1;
55             our_id = this.socket_id;
56         }
57
58         final Peer peer = new Peer();
59         SocketDescriptor descriptor = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
60             @Override
61             public long send_data(byte[] data, boolean resume_read) {
62                 try {
63                     if (resume_read) {
64                         do_selector_action(() -> peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_READ));
65                     }
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));
69                     }
70                     return written;
71                 } catch (IOException e) {
72                     // Most likely the socket is disconnected, let the background thread handle it.
73                     return 0;
74                 }
75             }
76
77             @Override
78             public void disconnect_socket() {
79                 try {
80                     do_selector_action(() -> {
81                         peer.key.cancel();
82                         peer.key.channel().close();
83                     });
84                 } catch (IOException ignored) { }
85             }
86             @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == our_id; }
87             @Override public long hash() { return our_id; }
88         });
89         peer.descriptor = descriptor;
90         return peer;
91     }
92
93     PeerManager peer_manager;
94     Thread io_thread;
95     final Selector selector;
96     long socket_id;
97     volatile boolean shutdown = false;
98
99     /**
100      * Constructs a new peer handler, spawning a thread to monitor for socket events.
101      *
102      * @param manager The LDK PeerManager which connection data will be provided to.
103      * @throws IOException If an internal java.nio error occurs.
104      */
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);
110             while (true) {
111                 try {
112                     if (IS_ANDROID) {
113                         while (true) {
114                             synchronized (this.selector) {
115                                 if (!wakeup_selector) {
116                                     this.selector.select(1000);
117                                     break;
118                                 }
119                             }
120                         }
121                     } else {
122                         this.selector.select(1000);
123                     }
124                 } catch (IOException ignored) {
125                     System.err.println("java.nio threw an unexpected IOException. Stopping PeerHandler thread!");
126                     return;
127                 }
128                 if (shutdown) return;
129                 if (Thread.interrupted()) return;
130                 for (SelectionKey key : this.selector.selectedKeys()) {
131                     try {
132                         if ((key.interestOps() & SelectionKey.OP_ACCEPT) != 0) {
133                             if (key.isAcceptable()) {
134                                 SocketChannel chan;
135                                 try {
136                                     chan = ((ServerSocketChannel) key.channel()).accept();
137                                 } catch (IOException ignored) {
138                                     key.cancel();
139                                     continue;
140                                 }
141                                 if (chan == null) continue;
142                                 try {
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);
147                                     }
148                                 } catch (IOException ignored) { }
149                             }
150                             continue; // There is no attachment so the rest of the loop is useless
151                         }
152                         Peer peer = (Peer) key.attachment();
153                         try {
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();
158                                     key.cancel();
159                                 }
160                             }
161                             if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
162                                 ((Buffer)buf).clear();
163                                 int read = ((SocketChannel) key.channel()).read(buf);
164                                 if (read == -1) {
165                                     this.peer_manager.socket_disconnected(peer.descriptor);
166                                     key.cancel();
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));
175                                         }
176                                     } else {
177                                         key.channel().close();
178                                         key.cancel();
179                                     }
180                                 }
181                             }
182                         } catch (IOException ignored) {
183                             try { key.channel().close(); } catch (IOException ignored2) { }
184                             key.cancel();
185                             peer_manager.socket_disconnected(peer.descriptor);
186                         }
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.
191                     }
192                 }
193                 peer_manager.process_events();
194             }
195         }, "NioPeerHandler NIO Thread");
196         io_thread.start();
197     }
198
199     /**
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.
202      *
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.
208      */
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);
216         }
217         if (!chan.finishConnect()) { // Note that this may throw its own IOException if we failed for another reason
218             throw new IOException("Timed out");
219         }
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");
226             }
227             do_selector_action(() -> peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer));
228         } else {
229             throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
230         }
231     }
232
233     /**
234      * Disconnects any connections currently open with the peer with the given node id.
235      *
236      * @param their_node_id must be a valid 33-byte public key
237      */
238     public void disconnect(byte[] their_node_id) {
239         this.peer_manager.disconnect_by_node_id(their_node_id, false);
240     }
241
242     /**
243      * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
244      * thread.
245      *
246      * @param socket_address The address to bind the listening socket to.
247      * @throws IOException if binding the listening socket fail.
248      */
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));
254     }
255
256     /**
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.
259      */
260     public void interrupt() {
261         shutdown = true;
262         selector.wakeup();
263         try {
264             io_thread.join();
265         } catch (InterruptedException ignored) { }
266     }
267
268     /**
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.
271      */
272     public void check_events() {
273         selector.wakeup();
274     }
275 }