Use newly-exposed get_route in HumanObjectPeerTest
[ldk-java] / src / test / java / org / ldk / HumanObjectPeerTest.java
1 package org.ldk;
2
3 import org.bitcoinj.core.*;
4 import org.bitcoinj.script.Script;
5 import org.junit.jupiter.api.Test;
6 import org.ldk.batteries.ChannelManagerConstructor;
7 import org.ldk.batteries.NioPeerHandler;
8 import org.ldk.enums.Currency;
9 import org.ldk.enums.Network;
10 import org.ldk.impl.bindings;
11 import org.ldk.structs.*;
12 import org.ldk.util.TwoTuple;
13
14 import java.io.IOException;
15 import java.lang.ref.WeakReference;
16 import java.net.InetSocketAddress;
17 import java.util.*;
18
19 class HumanObjectPeerTestInstance {
20     private final boolean nice_close;
21     private final boolean use_km_wrapper;
22     private final boolean use_manual_watch;
23     private final boolean reload_peers;
24     private final boolean break_cross_peer_refs;
25     private final boolean use_nio_peer_handler;
26     private final boolean use_filter;
27     private final boolean use_chan_manager_constructor;
28
29     HumanObjectPeerTestInstance(boolean nice_close, boolean use_km_wrapper, boolean use_manual_watch, boolean reload_peers, boolean break_cross_peer_refs, boolean use_nio_peer_handler, boolean use_filter, boolean use_chan_manager_constructor) {
30         this.nice_close = nice_close;
31         this.use_km_wrapper = use_km_wrapper;
32         this.use_manual_watch = use_manual_watch;
33         this.reload_peers = reload_peers;
34         this.break_cross_peer_refs = break_cross_peer_refs;
35         this.use_nio_peer_handler = use_nio_peer_handler;
36         this.use_filter = use_filter;
37         this.use_chan_manager_constructor = use_chan_manager_constructor;
38     }
39
40     class Peer {
41         KeysInterface manual_keysif(KeysInterface underlying_if) {
42             return KeysInterface.new_impl(new KeysInterface.KeysInterfaceInterface() {
43                 @Override public byte[] get_node_secret() { return underlying_if.get_node_secret(); }
44                 @Override public byte[] get_destination_script() { return underlying_if.get_destination_script(); }
45                 @Override public byte[] get_shutdown_pubkey() { return underlying_if.get_shutdown_pubkey(); }
46
47                 @Override
48                 public Sign get_channel_signer(boolean inbound, long channel_value_satoshis) {
49                     Sign underlying_ck = underlying_if.get_channel_signer(inbound, channel_value_satoshis);
50                     // TODO: Expose the underlying signer from a Sign
51                     /*BaseSign.BaseSignInterface si = new BaseSign.BaseSignInterface() {
52                         @Override
53                         public byte[] get_per_commitment_point(long idx) {
54                             return underlying_ck.get_per_commitment_point(idx);
55                         }
56
57                         @Override
58                         public byte[] release_commitment_secret(long idx) {
59                             return underlying_ck.release_commitment_secret(idx);
60                         }
61
62                         @Override
63                         public byte[] channel_keys_id() {
64                             return new byte[32];
65                         }
66
67                         @Override
68                         public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_counterparty_commitment(CommitmentTransaction commitment_tx) {
69                             return underlying_ck.sign_counterparty_commitment(commitment_tx);
70                         }
71
72                         @Override
73                         public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_holder_commitment_and_htlcs(HolderCommitmentTransaction holder_commitment_tx) {
74                             return underlying_ck.sign_holder_commitment_and_htlcs(holder_commitment_tx);
75                         }
76
77                         @Override
78                         public Result_SignatureNoneZ sign_justice_transaction(byte[] justice_tx, long input, long amount, byte[] per_commitment_key, HTLCOutputInCommitment htlc) {
79                             return underlying_ck.sign_justice_transaction(justice_tx, input, amount, per_commitment_key, htlc);
80                         }
81
82                         @Override
83                         public Result_SignatureNoneZ sign_counterparty_htlc_transaction(byte[] htlc_tx, long input, long amount, byte[] per_commitment_point, HTLCOutputInCommitment htlc) {
84                             return underlying_ck.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc);
85                         }
86
87                         @Override
88                         public Result_SignatureNoneZ sign_closing_transaction(byte[] closing_tx) {
89                             return underlying_ck.sign_closing_transaction(closing_tx);
90                         }
91
92                         @Override
93                         public Result_SignatureNoneZ sign_channel_announcement(UnsignedChannelAnnouncement msg) {
94                             return underlying_ck.sign_channel_announcement(msg);
95                         }
96
97                         @Override
98                         public void ready_channel(ChannelTransactionParameters params) {
99                             underlying_ck.ready_channel(params);
100                         }
101
102                         @Override
103                         public byte[] write() {
104                             return underlying_ck.write();
105                         }
106                     };*/
107                     //Sign resp = Sign.new_impl(si, underlying_ck.get_pubkeys());
108                     //must_free_objs.add(new WeakReference<>(si));
109                     //must_free_objs.add(new WeakReference<>(resp));
110                     must_free_objs.add(new WeakReference<>(underlying_ck));
111                     //return resp;
112                     return underlying_ck;
113                 }
114
115                 @Override
116                 public byte[] get_secure_random_bytes() {
117                     return underlying_if.get_secure_random_bytes();
118                 }
119
120                 @Override
121                 public Result_SignDecodeErrorZ read_chan_signer(byte[] reader) {
122                     return underlying_if.read_chan_signer(reader);
123                 }
124
125                 @Override
126                 public Result_RecoverableSignatureNoneZ sign_invoice(byte[] invoice_preimage) {
127                     return underlying_if.sign_invoice(invoice_preimage);
128                 }
129             });
130         }
131
132         Watch get_manual_watch() {
133             Watch.WatchInterface watch_impl = new Watch.WatchInterface() {
134                 public Result_NoneChannelMonitorUpdateErrZ watch_channel(OutPoint funding_txo, ChannelMonitor monitor) {
135                     synchronized (monitors) {
136                         assert monitors.put(Arrays.toString(funding_txo.get_txid()), monitor) == null;
137                     }
138                     return Result_NoneChannelMonitorUpdateErrZ.ok();
139                 }
140
141                 public Result_NoneChannelMonitorUpdateErrZ update_channel(OutPoint funding_txo, ChannelMonitorUpdate update) {
142                     synchronized (monitors) {
143                         String txid = Arrays.toString(funding_txo.get_txid());
144                         assert monitors.containsKey(txid);
145                         Result_NoneMonitorUpdateErrorZ update_res = monitors.get(txid).update_monitor(update, tx_broadcaster, fee_estimator, logger);
146                         assert update_res instanceof Result_NoneMonitorUpdateErrorZ.Result_NoneMonitorUpdateErrorZ_OK;
147                     }
148                     return Result_NoneChannelMonitorUpdateErrZ.ok();
149                 }
150
151                 @Override
152                 public MonitorEvent[] release_pending_monitor_events() {
153                     synchronized (monitors) {
154                         assert monitors.size() <= 1;
155                         for (ChannelMonitor mon : monitors.values()) {
156                             return mon.get_and_clear_pending_monitor_events();
157                         }
158                     }
159                     return new MonitorEvent[0];
160                 }
161             };
162             Watch watch = Watch.new_impl(watch_impl);
163             must_free_objs.add(new WeakReference<>(watch_impl));
164             must_free_objs.add(new WeakReference<>(watch));
165             return watch;
166         }
167
168         NioPeerHandler nio_peer_handler;
169         short nio_port;
170         final byte seed;
171         final Logger logger;
172         final FeeEstimator fee_estimator;
173         final BroadcasterInterface tx_broadcaster;
174         final KeysManager explicit_keys_manager;
175         final KeysInterface keys_interface;
176         final ChainMonitor chain_monitor;
177         final NetGraphMsgHandler router;
178         final Watch chain_watch;
179         final HashSet<String> filter_additions;
180         final Filter filter;
181         ChannelManager chan_manager;
182         PeerManager peer_manager;
183         final HashMap<String, ChannelMonitor> monitors; // Wow I forgot just how terrible Java is - we can't put a byte array here.
184         byte[] node_id;
185         final LinkedList<byte[]> broadcast_set = new LinkedList<>();
186         final LinkedList<Event> pending_manager_events = new LinkedList<>();
187         ChannelManagerConstructor constructor = null;
188         GcCheck obj = new GcCheck();
189
190         private TwoTuple<OutPoint, byte[]> test_mon_roundtrip(ChannelMonitor mon) {
191             // Because get_funding_txo() returns an OutPoint in a tuple that is a reference to an OutPoint inside the
192             // ChannelMonitor, its a good test to ensure that the OutPoint isn't freed (or is cloned) before the
193             // ChannelMonitor is. This used to be broken.
194             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_monitor = UtilMethods.BlockHashChannelMonitorZ_read(mon.write(), keys_interface);
195             assert roundtrip_monitor instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
196             TwoTuple<OutPoint, byte[]> funding_txo = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_monitor).res.b.get_funding_txo();
197             System.gc(); System.runFinalization(); // Give the GC a chance to run.
198             return funding_txo;
199         }
200
201         private Peer(Object _dummy, byte seed) {
202             logger = Logger.new_impl((String arg) -> System.out.println(seed + ": " + arg));
203             fee_estimator = FeeEstimator.new_impl((confirmation_target -> 253));
204             tx_broadcaster = BroadcasterInterface.new_impl(tx -> {
205                 broadcast_set.add(tx);
206             });
207             monitors = new HashMap<>();
208             this.seed = seed;
209             Persist persister = Persist.new_impl(new Persist.PersistInterface() {
210                 @Override
211                 public Result_NoneChannelMonitorUpdateErrZ persist_new_channel(OutPoint id, ChannelMonitor data) {
212                     synchronized (monitors) {
213                         String key = Arrays.toString(id.to_channel_id());
214                         assert monitors.put(key, data) == null;
215                         TwoTuple<OutPoint, byte[]> res = test_mon_roundtrip(data);
216                         assert Arrays.equals(res.a.get_txid(), id.get_txid());
217                         assert res.a.get_index() == id.get_index();
218                     }
219                     return Result_NoneChannelMonitorUpdateErrZ.ok();
220                 }
221
222                 @Override
223                 public Result_NoneChannelMonitorUpdateErrZ update_persisted_channel(OutPoint id, ChannelMonitorUpdate update, ChannelMonitor data) {
224                     synchronized (monitors) {
225                         String key = Arrays.toString(id.to_channel_id());
226                         assert monitors.put(key, data) != null;
227                         TwoTuple<OutPoint, byte[]> res = test_mon_roundtrip(data);
228                         assert Arrays.equals(res.a.get_txid(), id.get_txid());
229                         assert res.a.get_index() == id.get_index();
230                     }
231                     return Result_NoneChannelMonitorUpdateErrZ.ok();
232                 }
233             });
234
235             filter_additions = new HashSet<>();
236             if (use_filter) {
237                 this.filter = Filter.new_impl(new Filter.FilterInterface() {
238                     @Override public void register_tx(byte[] txid, byte[] script_pubkey) {
239                         filter_additions.add(Arrays.toString(txid));
240                     }
241                     @Override public Option_C2Tuple_usizeTransactionZZ register_output(WatchedOutput output) {
242                         filter_additions.add(Arrays.toString(output.get_outpoint().get_txid()) + ":" + output.get_outpoint().get_index());
243                         return Option_C2Tuple_usizeTransactionZZ.none();
244                     }
245                 });
246             } else {
247                 this.filter = null;
248             }
249
250             if (use_manual_watch) {
251                 chain_watch = get_manual_watch();
252                 chain_monitor = null;
253             } else {
254                 chain_monitor = ChainMonitor.of(filter, tx_broadcaster, logger, fee_estimator, persister);
255                 chain_watch = chain_monitor.as_Watch();
256             }
257
258             byte[] key_seed = new byte[32];
259             for (byte i = 0; i < 32; i++) {
260                 key_seed[i] = (byte) (i ^ seed);
261             }
262             KeysManager keys = KeysManager.of(key_seed, System.currentTimeMillis() / 1000, (int) (System.currentTimeMillis() * 1000));
263             if (use_km_wrapper) {
264                 this.keys_interface = manual_keysif(keys.as_KeysInterface());
265                 this.explicit_keys_manager = null;
266             } else {
267                 this.keys_interface = keys.as_KeysInterface();
268                 this.explicit_keys_manager = keys;
269             }
270             this.router = NetGraphMsgHandler.of(new byte[32], null, logger);
271         }
272         private void bind_nio() {
273             if (!use_nio_peer_handler) return;
274             if (use_chan_manager_constructor) {
275                 this.nio_peer_handler = this.constructor.nio_peer_handler;
276             } else {
277                 try { this.nio_peer_handler = new NioPeerHandler(peer_manager); } catch (IOException e) { assert false; }
278             }
279             for (short i = 10_000; true; i++) {
280                 try {
281                     nio_peer_handler.bind_listener(new InetSocketAddress("127.0.0.1", i));
282                     nio_port = i;
283                     break;
284                 } catch (IOException e) { assert i < 10_500; }
285             }
286         }
287         Peer(byte seed) {
288             this(null, seed);
289             if (use_chan_manager_constructor) {
290                 this.constructor = new ChannelManagerConstructor(Network.LDKNetwork_Bitcoin, UserConfig.with_default(), new byte[32], 0,
291                         this.keys_interface, this.fee_estimator, this.chain_monitor, this.router, this.tx_broadcaster, this.logger);
292                 constructor.chain_sync_completed(new ChannelManagerConstructor.ChannelManagerPersister() {
293                     @Override public void handle_event(Event event) {
294                         synchronized (pending_manager_events) {
295                             pending_manager_events.add(event);
296                             pending_manager_events.notifyAll();
297                         }
298                     }
299                     @Override public void persist_manager(byte[] channel_manager_bytes) { }
300                 });
301                 this.chan_manager = constructor.channel_manager;
302                 this.peer_manager = constructor.peer_manager;
303                 must_free_objs.add(new WeakReference<>(this.chan_manager));
304             } else {
305                 ChainParameters params = ChainParameters.of(Network.LDKNetwork_Bitcoin, BestBlock.of(new byte[32], 0));
306                 this.chan_manager = ChannelManager.of(this.fee_estimator, chain_watch, tx_broadcaster, logger, this.keys_interface, UserConfig.with_default(), params);
307                 byte[] random_data = keys_interface.get_secure_random_bytes();
308                 this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
309             }
310
311             this.node_id = chan_manager.get_our_node_id();
312             bind_nio();
313             System.gc();
314         }
315
316         Object ptr_to;
317         Peer(Peer orig) {
318             this(null, orig.seed);
319             if (use_chan_manager_constructor) {
320                 byte[][] monitors = {orig.monitors.values().stream().iterator().next().write()};
321                 byte[] serialized = orig.chan_manager.write();
322                 try {
323                     this.constructor = new ChannelManagerConstructor(serialized, monitors, this.keys_interface,
324                             this.fee_estimator, this.chain_monitor, this.filter, this.router, this.tx_broadcaster, this.logger);
325                     constructor.chain_sync_completed(new ChannelManagerConstructor.ChannelManagerPersister() {
326                         @Override public void handle_event(Event event) {
327                             synchronized (pending_manager_events) {
328                                 pending_manager_events.add(event);
329                                 pending_manager_events.notifyAll();
330                             }
331                         }
332                         @Override public void persist_manager(byte[] channel_manager_bytes) { }
333                     });
334                     this.chan_manager = constructor.channel_manager;
335                     this.peer_manager = constructor.peer_manager;
336                     must_free_objs.add(new WeakReference<>(this.chan_manager));
337                     // If we are using a ChannelManagerConstructor, we may have pending events waiting on the old peer
338                     // which have been removed from the ChannelManager but which we still need to handle.
339                     this.pending_manager_events.addAll(orig.pending_manager_events);
340                     if (!this.pending_manager_events.isEmpty()) {
341                         // However, this implies cross_reload_ref_pollution
342                         cross_reload_ref_pollution = true;
343                     }
344                 } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {
345                     assert false;
346                 }
347             } else {
348                 ChannelMonitor[] monitors = new ChannelMonitor[1];
349                 assert orig.monitors.size() == 1;
350                 if (!break_cross_peer_refs) {
351                     monitors[0] = orig.monitors.values().stream().iterator().next();
352                 } else {
353                     byte[] serialized = orig.monitors.values().stream().iterator().next().write();
354                     Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res =
355                             UtilMethods.BlockHashChannelMonitorZ_read(serialized, this.keys_interface);
356                     assert res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
357                     monitors[0] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.b;
358                 }
359                 byte[] serialized = orig.chan_manager.write();
360                 Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ read_res =
361                         UtilMethods.BlockHashChannelManagerZ_read(serialized, this.keys_interface, this.fee_estimator, this.chain_watch, this.tx_broadcaster, this.logger, UserConfig.with_default(), monitors);
362                 assert read_res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK;
363                 this.chan_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK) read_res).res.b;
364                 this.chain_watch.watch_channel(monitors[0].get_funding_txo().a, monitors[0]);
365                 byte[] random_data = keys_interface.get_secure_random_bytes();
366                 this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), router.as_RoutingMessageHandler(), keys_interface.get_node_secret(), random_data, logger);
367                 if (!break_cross_peer_refs && (use_manual_watch || use_km_wrapper)) {
368                     // When we pass monitors[0] into chain_watch.watch_channel we create a reference from the new Peer to a
369                     // field in the old peer, preventing freeing of the original Peer until the new Peer is freed. Thus, we
370                     // shouldn't bother waiting for the original to be freed later on.
371                     cross_reload_ref_pollution = true;
372                 }
373             }
374             this.node_id = chan_manager.get_our_node_id();
375             bind_nio();
376
377             if (cross_reload_ref_pollution) {
378                 // This really, really needs to be handled at the bindings layer, but its rather complicated -
379                 // ChannelSigners can be cloned and passed around without java being involved, resulting in them being
380                 // owned by both one or more ChannelMonitors and a ChannelManager, with only one having proper pointers
381                 // to the ChannelSigner. Ideally, the ChannelSigner would have a global reference to the Java
382                 // implementation class, but that results in circular references. Instead, we need some ability to,
383                 // while cloning ChannelSigners, add new references in the calling Java struct (ie ChannelMonitor) to
384                 // the ChannelSigner.
385                 this.ptr_to = orig.chan_manager;
386             }
387         }
388
389         TwoTuple<byte[], TwoTuple<Integer, TxOut>[]>[] connect_block(Block b, int height, long expected_monitor_update_len) {
390             byte[] header = Arrays.copyOfRange(b.bitcoinSerialize(), 0, 80);
391             TwoTuple<Long, byte[]>[] txn;
392             if (b.hasTransactions()) {
393                 assert b.getTransactions().size() == 1;
394                 TwoTuple<Long, byte[]> txp = new TwoTuple<>((long) 0, b.getTransactions().get(0).bitcoinSerialize());
395                 txn = new TwoTuple[]{txp};
396             } else
397                 txn = new TwoTuple[0];
398             if (chain_monitor != null) {
399                 chan_manager.as_Listen().block_connected(b.bitcoinSerialize(), height);
400                 chain_monitor.as_Listen().block_connected(b.bitcoinSerialize(), height);
401             } else {
402                 chan_manager.as_Confirm().transactions_confirmed(header, txn, height);
403                 chan_manager.as_Confirm().best_block_updated(header, height);
404                 // Connect manually if we aren't using a ChainMonitor and are implementing Watch ourselves
405                 synchronized (monitors) {
406                     assert monitors.size() == 1;
407                     for (ChannelMonitor mon : monitors.values()) {
408                         TwoTuple<byte[], TwoTuple<Integer, TxOut>[]>[] ret = mon.block_connected(header, txn, height, tx_broadcaster, fee_estimator, logger);
409                         assert ret.length == expected_monitor_update_len;
410                         return ret;
411                     }
412                 }
413             }
414             return null;
415         }
416
417         Event[] get_monitor_events(int expected_len) {
418             if (use_chan_manager_constructor) {
419                 while (true) {
420                     synchronized (this.pending_manager_events) {
421                         if (expected_len != 0 && this.pending_manager_events.size() != expected_len) {
422                             break;
423                         }
424                     }
425                     try { Thread.sleep(500); } catch (InterruptedException e) { assert false; }
426                     break;
427                 }
428                 synchronized (this.pending_manager_events) {
429                     Event[] res = this.pending_manager_events.toArray(new Event[0]);
430                     this.pending_manager_events.clear();
431                     assert res.length == expected_len;
432                     return res;
433                 }
434             } else if (chain_monitor != null) {
435                 ArrayList<Event> l = new ArrayList<Event>();
436                 chain_monitor.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
437                 assert l.size() == expected_len;
438                 return l.toArray(new Event[0]);
439             } else {
440                 synchronized (monitors) {
441                     assert monitors.size() == 1;
442                     for (ChannelMonitor mon : monitors.values()) {
443                         Event[] res = mon.get_and_clear_pending_events();
444                         assert res.length == expected_len;
445                         return res;
446                     }
447                     return null;
448                 }
449             }
450         }
451
452         Event[] get_manager_events(int expected_len) {
453             Event[] res = new Event[0];
454             if (use_chan_manager_constructor) {
455                 while (res.length < expected_len) {
456                     synchronized (this.pending_manager_events) {
457                         res = this.pending_manager_events.toArray(res);
458                         assert res.length == expected_len || res.length == 0; // We don't handle partial results
459                         this.pending_manager_events.clear();
460                         if (res.length < expected_len) {
461                             try { this.pending_manager_events.wait(); } catch (InterruptedException e) { assert false; }
462                         }
463                     }
464                 }
465             } else {
466                 ArrayList<Event> l = new ArrayList<Event>();
467                 chan_manager.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
468                 return l.toArray(new Event[0]);
469             }
470             assert res.length == expected_len;
471             return res;
472         }
473     }
474
475     static class DescriptorHolder { SocketDescriptor val; }
476
477     boolean running = false;
478     final LinkedList<Runnable> runqueue = new LinkedList();
479     boolean ran = false;
480     Thread t = new Thread(() -> {
481             while (true) {
482                 try {
483                     Runnable r;
484                     synchronized (runqueue) {
485                         while (runqueue.isEmpty()) {
486                             runqueue.wait();
487                         }
488                         running = true;
489                         r = runqueue.pollFirst();
490                     }
491                     r.run();
492                     synchronized (runqueue) {
493                         running = false;
494                         runqueue.notifyAll();
495                     }
496                 } catch (InterruptedException e) {
497                     return;
498                 }
499             }
500     });
501     void wait_events_processed(Peer peer1, Peer peer2) {
502         if (use_nio_peer_handler) {
503             peer1.nio_peer_handler.check_events();
504             peer2.nio_peer_handler.check_events();
505             try { Thread.sleep(500); } catch (InterruptedException e) { assert false; }
506         } else {
507             synchronized (runqueue) {
508                 ran = false;
509             }
510             while (true) {
511                 peer1.peer_manager.process_events();
512                 peer2.peer_manager.process_events();
513                 synchronized (runqueue) {
514                     if (runqueue.isEmpty() && !running) {
515                         if (ran) {
516                             ran = false;
517                             continue;
518                         } else { break; }
519                     }
520                     try { runqueue.wait(); } catch (InterruptedException e) { assert false; }
521                 }
522             }
523         }
524     }
525     void do_read_event(PeerManager pm, SocketDescriptor descriptor, byte[] data) {
526         if (!t.isAlive()) t.start();
527         synchronized (runqueue) {
528             ran = true;
529             runqueue.add(() -> {
530                 Result_boolPeerHandleErrorZ res = pm.read_event(descriptor, data);
531                 assert res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK;
532             });
533             runqueue.notifyAll();
534         }
535         must_free_objs.add(new WeakReference<>(data));
536     }
537
538     void connect_peers(final Peer peer1, final Peer peer2) {
539         if (use_nio_peer_handler) {
540             try {
541                 peer1.nio_peer_handler.connect(peer2.chan_manager.get_our_node_id(), new InetSocketAddress("127.0.0.1", peer2.nio_port), 100);
542             } catch (IOException e) { assert false; }
543         } else {
544             DescriptorHolder descriptor1 = new DescriptorHolder();
545             DescriptorHolder descriptor1ref = descriptor1;
546             SocketDescriptor descriptor2 = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
547                 @Override
548                 public long send_data(byte[] data, boolean resume_read) {
549                     do_read_event(peer1.peer_manager, descriptor1ref.val, data);
550                     return data.length;
551                 }
552
553                 @Override public void disconnect_socket() { assert false; }
554                 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == 2; }
555                 @Override public long hash() { return 2; }
556             });
557
558             descriptor1.val = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
559                 @Override
560                 public long send_data(byte[] data, boolean resume_read) {
561                     do_read_event(peer2.peer_manager, descriptor2, data);
562                     return data.length;
563                 }
564
565                 @Override public void disconnect_socket() { assert false; }
566                 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == 1; }
567                 @Override public long hash() { return 1; }
568             });
569
570             Result_CVec_u8ZPeerHandleErrorZ conn_res = peer1.peer_manager.new_outbound_connection(peer2.node_id, descriptor1.val);
571             assert conn_res instanceof Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK;
572
573             Result_NonePeerHandleErrorZ inbound_conn_res = peer2.peer_manager.new_inbound_connection(descriptor2);
574             assert inbound_conn_res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_OK;
575             do_read_event(peer2.peer_manager, descriptor2, ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) conn_res).res);
576         }
577     }
578
579     TestState do_test_message_handler() throws InterruptedException {
580         Peer peer1 = new Peer((byte) 1);
581         Peer peer2 = new Peer((byte) 2);
582
583         connect_peers(peer1, peer2);
584         wait_events_processed(peer1, peer2);
585
586         Result_NoneAPIErrorZ cc_res = peer1.chan_manager.create_channel(peer2.node_id, 10000, 1000, 42, null);
587         assert cc_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
588         wait_events_processed(peer1, peer2);
589
590         Event[] events = peer1.get_manager_events(1);
591         assert events[0] instanceof Event.FundingGenerationReady;
592         assert ((Event.FundingGenerationReady) events[0]).channel_value_satoshis == 10000;
593         assert ((Event.FundingGenerationReady) events[0]).user_channel_id == 42;
594         byte[] funding_spk = ((Event.FundingGenerationReady) events[0]).output_script;
595         assert funding_spk.length == 34 && funding_spk[0] == 0 && funding_spk[1] == 32; // P2WSH
596         byte[] chan_id = ((Event.FundingGenerationReady) events[0]).temporary_channel_id;
597
598         NetworkParameters bitcoinj_net = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
599
600         Transaction funding = new Transaction(bitcoinj_net);
601         funding.addInput(new TransactionInput(bitcoinj_net, funding, new byte[0]));
602         funding.getInputs().get(0).setWitness(new TransactionWitness(2)); // Make sure we don't complain about lack of witness
603         funding.getInput(0).getWitness().setPush(0, new byte[]{0x1});
604         funding.addOutput(Coin.SATOSHI.multiply(10000), new Script(funding_spk));
605         Result_NoneAPIErrorZ funding_res = peer1.chan_manager.funding_transaction_generated(chan_id, funding.bitcoinSerialize());
606         assert funding_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
607         wait_events_processed(peer1, peer2);
608
609         assert peer1.broadcast_set.size() == 1;
610         assert Arrays.equals(peer1.broadcast_set.get(0), funding.bitcoinSerialize());
611         peer1.broadcast_set.clear();
612
613         Block b = new Block(bitcoinj_net, 2, Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[]{funding}));
614         peer1.connect_block(b, 1, 0);
615         peer2.connect_block(b, 1, 0);
616
617         for (int height = 2; height < 10; height++) {
618             b = new Block(bitcoinj_net, 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[0]));
619             peer1.connect_block(b, height, 0);
620             peer2.connect_block(b, height, 0);
621         }
622         wait_events_processed(peer1, peer2);
623
624         peer1.chan_manager.list_channels();
625         ChannelDetails[] peer1_chans = peer1.chan_manager.list_usable_channels();
626         ChannelDetails[] peer2_chans = peer2.chan_manager.list_usable_channels();
627         assert peer1_chans.length == 1;
628         assert peer2_chans.length == 1;
629         assert peer1_chans[0].get_channel_value_satoshis() == 10000;
630         assert peer1_chans[0].get_is_usable();
631         Option_u64Z short_chan_id = peer1_chans[0].get_short_channel_id();
632         assert short_chan_id instanceof Option_u64Z.Some;
633         assert ((Option_u64Z.Some)short_chan_id).some == (1L << 40); // 0th output in the 0th transaction in the 1st block
634         assert Arrays.equals(peer1_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
635         assert Arrays.equals(peer2_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
636
637         Result_InvoiceSignOrCreationErrorZ invoice = UtilMethods.create_invoice_from_channelmanager(peer2.chan_manager, peer2.keys_interface, Currency.LDKCurrency_Bitcoin, Option_u64Z.none(), "Invoice Description");
638         assert invoice instanceof Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK;
639         System.out.println("Got invoice: " + ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
640
641         Result_InvoiceNoneZ parsed_invoice = Invoice.from_str(((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
642         assert parsed_invoice instanceof Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK;
643         assert Arrays.equals(((Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK) parsed_invoice).res.payment_hash(), ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_hash());
644         SignedRawInvoice signed_raw = ((Result_InvoiceNoneZ.Result_InvoiceNoneZ_OK) parsed_invoice).res.into_signed_raw();
645         RawInvoice raw_invoice = signed_raw.raw_invoice();
646         byte[] desc_hash = raw_invoice.hash();
647         Description raw_invoice_description = raw_invoice.description();
648         String description_string = raw_invoice_description.into_inner();
649         assert description_string.equals("Invoice Description");
650         byte[] payment_hash = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_hash();
651         byte[] payment_secret = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_secret();
652         byte[] dest_node_id = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.recover_payee_pub_key();
653         assert Arrays.equals(dest_node_id, peer2.node_id);
654         InvoiceFeatures invoice_features = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.features();
655         RouteHint[] route_hints = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.route_hints();
656
657         Route route;
658         try (LockedNetworkGraph netgraph = peer1.router.read_locked_graph()) {
659             NetworkGraph graph = netgraph.graph();
660             Result_RouteLightningErrorZ route_res = UtilMethods.get_route(peer1.chan_manager.get_our_node_id(), graph, peer2.node_id, invoice_features, peer1_chans, route_hints, 1000000, 42, peer1.logger);
661             assert route_res instanceof Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK;
662             route = ((Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK) route_res).res;
663         }
664
665         Result_NonePaymentSendFailureZ payment_res = peer1.chan_manager.send_payment(route, payment_hash, payment_secret);
666         assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_OK;
667         wait_events_processed(peer1, peer2);
668
669         RouteHop[][] hops = new RouteHop[1][1];
670         byte[] hop_pubkey = new byte[33];
671         hop_pubkey[0] = 3;
672         hop_pubkey[1] = 42;
673         hops[0][0] = RouteHop.of(hop_pubkey, NodeFeatures.known(), 42, ChannelFeatures.known(), 100, 0);
674         Route r2 = Route.of(hops);
675         payment_res = peer1.chan_manager.send_payment(r2, payment_hash, payment_secret);
676         assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_Err;
677
678         if (!use_chan_manager_constructor) {
679             peer1.get_monitor_events(0);
680             peer2.get_monitor_events(0);
681         } else {
682             // The events are combined across manager + monitors but peer1 still has no events
683         }
684
685         if (reload_peers) {
686             if (use_nio_peer_handler) {
687                 peer1.nio_peer_handler.interrupt();
688                 peer2.nio_peer_handler.interrupt();
689             }
690             if (use_chan_manager_constructor) {
691                 peer1.constructor.interrupt();
692                 peer2.constructor.interrupt();
693             }
694             WeakReference<Peer> op1 = new WeakReference<Peer>(peer1);
695             peer1 = new Peer(peer1);
696             peer2 = new Peer(peer2);
697             return new TestState(op1, peer1, peer2, b.getHash());
698         }
699         return new TestState(null, peer1, peer2, b.getHash());
700     }
701
702     boolean cross_reload_ref_pollution = false;
703     class TestState {
704         private final WeakReference<Peer> ref_block;
705         private final Peer peer1;
706         private final Peer peer2;
707         public Sha256Hash best_blockhash;
708
709         public TestState(WeakReference<Peer> ref_block, Peer peer1, Peer peer2, Sha256Hash best_blockhash) {
710             this.ref_block = ref_block;
711             this.peer1 = peer1;
712             this.peer2 = peer2;
713             this.best_blockhash = best_blockhash;
714         }
715     }
716     void do_test_message_handler_b(TestState state) {
717         GcCheck obj = new GcCheck();
718         if (state.ref_block != null) {
719             // Ensure the original peers get freed before we move on. Note that we have to be in a different function
720             // scope to do so as the (at least current OpenJDK) JRE won't release anything created in the same scope.
721             while (!cross_reload_ref_pollution && state.ref_block.get() != null) {
722                 System.gc();
723                 System.runFinalization();
724             }
725             connect_peers(state.peer1, state.peer2);
726         }
727         wait_events_processed(state.peer1, state.peer2);
728
729         Event[] events = state.peer2.get_manager_events(1);
730         assert events[0] instanceof Event.PendingHTLCsForwardable;
731         state.peer2.chan_manager.process_pending_htlc_forwards();
732
733         events = state.peer2.get_manager_events(1);
734         assert events[0] instanceof Event.PaymentReceived;
735         byte[] payment_preimage = ((Event.PaymentReceived)events[0]).payment_preimage;
736         assert !Arrays.equals(payment_preimage, new byte[32]);
737         state.peer2.chan_manager.claim_funds(payment_preimage);
738         wait_events_processed(state.peer1, state.peer2);
739
740         events = state.peer1.get_manager_events(1);
741         assert events[0] instanceof Event.PaymentSent;
742         assert Arrays.equals(((Event.PaymentSent) events[0]).payment_preimage, payment_preimage);
743         wait_events_processed(state.peer1, state.peer2);
744
745         ChannelDetails[] peer1_chans = state.peer1.chan_manager.list_channels();
746
747         if (nice_close) {
748             Result_NoneAPIErrorZ close_res = state.peer1.chan_manager.close_channel(peer1_chans[0].get_channel_id());
749             assert close_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
750             wait_events_processed(state.peer1, state.peer2);
751
752             assert state.peer1.broadcast_set.size() == 1;
753             assert state.peer2.broadcast_set.size() == 1;
754         } else {
755             state.peer1.chan_manager.force_close_all_channels();
756             wait_events_processed(state.peer1, state.peer2);
757
758             assert state.peer1.broadcast_set.size() == 1;
759             assert state.peer2.broadcast_set.size() == 1;
760
761             NetworkParameters bitcoinj_net = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
762             Transaction tx = new Transaction(bitcoinj_net, state.peer1.broadcast_set.getFirst());
763             Block b = new Block(bitcoinj_net, 2, state.best_blockhash, Sha256Hash.ZERO_HASH, 42, 0, 0,
764                     Arrays.asList(new Transaction[]{tx}));
765             TwoTuple<byte[], TwoTuple<Integer, TxOut>[]>[] watch_outputs = state.peer2.connect_block(b, 10, 1);
766             if (watch_outputs != null) { // We only process watch_outputs manually when we use a manually-build Watch impl
767                 assert watch_outputs.length == 1;
768                 assert Arrays.equals(watch_outputs[0].a, tx.getTxId().getReversedBytes());
769                 assert watch_outputs[0].b.length == 2;
770                 assert watch_outputs[0].b[0].a == 0;
771                 assert watch_outputs[0].b[1].a == 1;
772             }
773
774             for (int i = 11; i < 21; i++) {
775                 b = new Block(bitcoinj_net, 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, new ArrayList<>());
776                 state.peer2.connect_block(b, i, 0);
777             }
778
779             Event[] broadcastable_event = state.peer2.get_monitor_events(1);
780             for (ChannelMonitor mon : state.peer2.monitors.values()) {
781                 // This used to be buggy and double-free, so go ahead and fetch them!
782                 byte[][] txn = mon.get_latest_holder_commitment_txn(state.peer2.logger);
783             }
784             assert broadcastable_event.length == 1;
785             assert broadcastable_event[0] instanceof Event.SpendableOutputs;
786             if (state.peer2.explicit_keys_manager != null) {
787                 Result_TransactionNoneZ tx_res = state.peer2.explicit_keys_manager.spend_spendable_outputs(((Event.SpendableOutputs) broadcastable_event[0]).outputs, new TxOut[0], new byte[] {0x00}, 253);
788                 assert tx_res instanceof Result_TransactionNoneZ.Result_TransactionNoneZ_OK;
789                 Transaction built_tx = new Transaction(bitcoinj_net, ((Result_TransactionNoneZ.Result_TransactionNoneZ_OK) tx_res).res);
790                 assert built_tx.getOutputs().size() == 1;
791                 assert Arrays.equals(built_tx.getOutput(0).getScriptBytes(), new byte[]{0x00});
792             }
793         }
794
795         if (use_nio_peer_handler) {
796             state.peer1.peer_manager.disconnect_by_node_id(state.peer2.chan_manager.get_our_node_id(), false);
797             wait_events_processed(state.peer1, state.peer2);
798             assert state.peer1.peer_manager.get_peer_node_ids().length == 0;
799             assert state.peer2.peer_manager.get_peer_node_ids().length == 0;
800             state.peer1.nio_peer_handler.interrupt();
801             state.peer2.nio_peer_handler.interrupt();
802         }
803
804         state.peer1.get_monitor_events(0);
805         state.peer2.get_monitor_events(0);
806
807         if (use_chan_manager_constructor) {
808             state.peer1.constructor.interrupt();
809             state.peer2.constructor.interrupt();
810         }
811
812         t.interrupt();
813     }
814
815     java.util.LinkedList<WeakReference<Object>> must_free_objs = new java.util.LinkedList();
816     int gc_count = 0;
817     int gc_exp_count = 0;
818     class GcCheck {
819         GcCheck() { gc_exp_count += 1; }
820         @Override
821         protected void finalize() throws Throwable {
822             gc_count += 1;
823             super.finalize();
824         }
825     }
826 }
827 public class HumanObjectPeerTest {
828     HumanObjectPeerTestInstance do_test_run(boolean nice_close, boolean use_km_wrapper, boolean use_manual_watch, boolean reload_peers, boolean break_cross_peer_refs, boolean nio_peer_handler, boolean use_chan_manager_constructor) throws InterruptedException {
829         HumanObjectPeerTestInstance instance = new HumanObjectPeerTestInstance(nice_close, use_km_wrapper, use_manual_watch, reload_peers, break_cross_peer_refs, nio_peer_handler, !nio_peer_handler, use_chan_manager_constructor);
830         HumanObjectPeerTestInstance.TestState state = instance.do_test_message_handler();
831         instance.do_test_message_handler_b(state);
832         return instance;
833     }
834     void do_test(boolean nice_close, boolean use_km_wrapper, boolean use_manual_watch, boolean reload_peers, boolean break_cross_peer_refs, boolean nio_peer_handler, boolean use_chan_manager_constructor) throws InterruptedException {
835         HumanObjectPeerTestInstance instance = do_test_run(nice_close, use_km_wrapper, use_manual_watch, reload_peers, break_cross_peer_refs, nio_peer_handler, use_chan_manager_constructor);
836         while (instance.gc_count != instance.gc_exp_count) {
837             System.gc();
838             System.runFinalization();
839         }
840         for (WeakReference<Object> o : instance.must_free_objs)
841             assert o.get() == null;
842     }
843     @Test
844     public void test_message_handler() throws InterruptedException {
845         for (int i = 0; i < (1 << 7) - 1; i++) {
846             boolean nice_close =                   (i & (1 << 0)) != 0;
847             boolean use_km_wrapper =               (i & (1 << 1)) != 0;
848             boolean use_manual_watch =             (i & (1 << 2)) != 0;
849             boolean reload_peers =                 (i & (1 << 3)) != 0;
850             boolean break_cross_refs =             (i & (1 << 4)) != 0;
851             boolean nio_peer_handler =             (i & (1 << 5)) != 0;
852             boolean use_chan_manager_constructor = (i & (1 << 6)) != 0;
853             if (break_cross_refs && !reload_peers) {
854                 // There are no cross refs to break without reloading peers.
855                 continue;
856             }
857             if (use_chan_manager_constructor && (use_manual_watch || !nio_peer_handler)) {
858                 // ChannelManagerConstructor requires a ChainMonitor as the Watch and creates a NioPeerHandler for us.
859                 continue;
860             }
861             System.err.println("Running test with flags " + i);
862             do_test(nice_close, use_km_wrapper, use_manual_watch, reload_peers, break_cross_refs, nio_peer_handler, use_chan_manager_constructor);
863         }
864     }
865 }