Add NioPeerHandler and associated test
[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 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;
22         SelectionKey key;
23     }
24
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);
30         long our_id;
31         synchronized (this) {
32             this.socket_id = this.socket_id + 1;
33             our_id = this.socket_id;
34         }
35
36         final Peer peer = new Peer();
37         SocketDescriptor descriptor = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
38             @Override
39             public long send_data(byte[] data, boolean resume_read) {
40                 if (resume_read) {
41                     peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_READ);
42                 }
43                 try {
44                     long written = chan.write(ByteBuffer.wrap(data));
45                     if (written != data.length) {
46                         peer.key.interestOps(peer.key.interestOps() | SelectionKey.OP_WRITE);
47                     }
48                     return written;
49                 } catch (IOException e) {
50                     // Most likely the socket is disconnected, let the background thread handle it.
51                     return 0;
52                 }
53             }
54
55             @Override
56             public void disconnect_socket() {
57                 try {
58                     peer.key.cancel();
59                     peer.key.channel().close();
60                     selector.wakeup();
61                 } catch (IOException ignored) { }
62                 synchronized (peer) {
63                     while (peer.block_disconnect_socket) {
64                         try {
65                             peer.wait();
66                         } catch (InterruptedException ignored) { }
67                     }
68                 }
69             }
70             @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == our_id; }
71             @Override public long hash() { return our_id; }
72         });
73         peer.descriptor = descriptor;
74         return peer;
75     }
76
77     PeerManager peer_manager;
78     Thread io_thread;
79     Selector selector;
80     long socket_id;
81     volatile boolean shutdown = false;
82
83     /**
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.
86      *
87      * @param manager The LDK PeerManager which connection data will be provided to.
88      * @throws IOException If an internal java.nio error occurs.
89      */
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();
97             while (true) {
98                 try {
99                     this.selector.select(1000);
100                 } catch (IOException ignored) {
101                     System.err.println("java.nio threw an unexpected IOException. Stopping PeerHandler thread!");
102                     return;
103                 }
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()) {
109                             SocketChannel chan;
110                             try {
111                                 chan = ((ServerSocketChannel) key.channel()).accept();
112                             } catch (IOException ignored) {
113                                 key.cancel();
114                                 continue;
115                             }
116                             if (chan == null) continue;
117                             try {
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);
122                                 }
123                             } catch (IOException ignored) { }
124                         }
125                         continue; // There is no attachment so the rest of the loop is useless
126                     }
127                     Peer peer = (Peer) key.attachment();
128                     synchronized (peer) {
129                         peer.block_disconnect_socket = true;
130                     }
131                     try {
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();
136                                 key.cancel();
137                             }
138                         }
139                         if (key.isValid() && (key.interestOps() & SelectionKey.OP_READ) != 0 && key.isReadable()) {
140                             buf.clear();
141                             int read = ((SocketChannel) key.channel()).read(buf);
142                             if (read == -1) {
143                                 this.peer_manager.socket_disconnected(peer.descriptor);
144                                 key.cancel();
145                             } else if (read > 0) {
146                                 buf.flip();
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));
153                                     }
154                                 } else {
155                                     key.channel().close();
156                                     key.cancel();
157                                 }
158                             }
159                         }
160                     } catch (IOException ignored) {
161                         try { key.channel().close(); } catch (IOException ignored2) { }
162                         key.cancel();
163                         peer_manager.socket_disconnected(peer.descriptor);
164                     }
165                     synchronized (peer) {
166                         peer.block_disconnect_socket = false;
167                         peer.notifyAll();
168                     }
169                 }
170                 if (lastTimerTick < System.currentTimeMillis() - 30 * 1000) {
171                     peer_manager.timer_tick_occured();
172                     lastTimerTick = System.currentTimeMillis();
173                 }
174                 peer_manager.process_events();
175             }
176         }, "NioPeerHandler NIO Thread");
177         io_thread.start();
178     }
179
180     /**
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.
183      *
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.
188      */
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");
197             }
198             peer.key = chan.register(this.selector, SelectionKey.OP_READ, peer);
199             this.selector.wakeup();
200         } else {
201             throw new IOException("LDK rejected outbound connection. This likely shouldn't ever happen.");
202         }
203     }
204
205     /**
206      * Binds a listening socket to the given address, accepting incoming connections and handling them on the background
207      * thread.
208      *
209      * @param socket_address The address to bind the listening socket to.
210      * @throws IOException if binding the listening socket fail.
211      */
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();
218     }
219
220     /**
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.
223      */
224     public void interrupt() {
225         shutdown = true;
226         selector.wakeup();
227         try {
228             io_thread.join();
229         } catch (InterruptedException ignored) { }
230     }
231
232     /**
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.
235      */
236     public void check_events() {
237         selector.wakeup();
238     }
239 }