[Java] Update Java Tests to latest upstream API
[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.*;
9 import org.ldk.enums.Currency;
10 import org.ldk.structs.*;
11 import org.ldk.util.UInt5;
12
13 import java.io.IOException;
14 import java.lang.ref.WeakReference;
15 import java.net.InetSocketAddress;
16 import java.util.*;
17 import java.util.function.IntConsumer;
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_ignore_handler;
28     private final boolean use_chan_manager_constructor;
29     private final boolean use_invoice_payer;
30     TxOut gossip_txout = null;
31
32     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_ignore_handler, boolean use_chan_manager_constructor, boolean use_invoice_payer) {
33         this.nice_close = nice_close;
34         this.use_km_wrapper = use_km_wrapper;
35         this.use_manual_watch = use_manual_watch;
36         this.reload_peers = reload_peers;
37         this.break_cross_peer_refs = break_cross_peer_refs;
38         this.use_nio_peer_handler = use_nio_peer_handler;
39         this.use_filter = use_filter;
40         this.use_ignore_handler = use_ignore_handler;
41         this.use_chan_manager_constructor = use_chan_manager_constructor;
42         this.use_invoice_payer = use_invoice_payer;
43     }
44
45     class Peer {
46         KeysInterface manual_keysif(KeysInterface underlying_if) {
47             return KeysInterface.new_impl(new KeysInterface.KeysInterfaceInterface() {
48                 @Override public Result_SecretKeyNoneZ get_node_secret(Recipient recipient) { return underlying_if.get_node_secret(recipient); }
49                 @Override public Result_PublicKeyNoneZ get_node_id(Recipient recipient) { return underlying_if.get_node_id(recipient); }
50
51                 @Override public Result_SharedSecretNoneZ ecdh(Recipient recipient, byte[] other_key, Option_ScalarZ tweak) { return underlying_if.ecdh(recipient, other_key, tweak); }
52                 @Override public byte[] get_destination_script() { return underlying_if.get_destination_script(); }
53                 @Override public ShutdownScript get_shutdown_scriptpubkey() { return underlying_if.get_shutdown_scriptpubkey(); }
54
55                 @Override
56                 public Sign get_channel_signer(boolean inbound, long channel_value_satoshis) {
57                     Sign underlying_ck = underlying_if.get_channel_signer(inbound, channel_value_satoshis);
58                     BaseSign underlying_base = underlying_ck.get_base_sign();
59                     BaseSign.BaseSignInterface bsi = new BaseSign.BaseSignInterface() {
60                         @Override public byte[] get_per_commitment_point(long idx) {
61                             return underlying_base.get_per_commitment_point(idx);
62                         }
63                         @Override public byte[] release_commitment_secret(long idx) {
64                             return underlying_base.release_commitment_secret(idx);
65                         }
66                         @Override public Result_NoneNoneZ validate_holder_commitment(HolderCommitmentTransaction holder_tx, byte[][] preimages) {
67                             return underlying_base.validate_holder_commitment(holder_tx, preimages);
68                         }
69                         @Override public byte[] channel_keys_id() {
70                             return new byte[32];
71                         }
72                         @Override public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_counterparty_commitment(CommitmentTransaction commitment_tx, byte[][] preimages) {
73                             return underlying_base.sign_counterparty_commitment(commitment_tx, preimages);
74                         }
75                         @Override public Result_NoneNoneZ validate_counterparty_revocation(long idx, byte[] secret) {
76                             return underlying_base.validate_counterparty_revocation(idx, secret);
77                         }
78                         @Override public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_holder_commitment_and_htlcs(HolderCommitmentTransaction holder_commitment_tx) {
79                             return underlying_base.sign_holder_commitment_and_htlcs(holder_commitment_tx);
80                         }
81                         @Override public Result_SignatureNoneZ sign_justice_revoked_output(byte[] justice_tx, long input, long amount, byte[] per_commitment_key) {
82                             return underlying_base.sign_justice_revoked_output(justice_tx, input, amount, per_commitment_key);
83                         }
84                         @Override public Result_SignatureNoneZ sign_justice_revoked_htlc(byte[] justice_tx, long input, long amount, byte[] per_commitment_key, HTLCOutputInCommitment htlc) {
85                             return underlying_base.sign_justice_revoked_htlc(justice_tx, input, amount, per_commitment_key, htlc);
86                         }
87                         @Override public Result_SignatureNoneZ sign_counterparty_htlc_transaction(byte[] htlc_tx, long input, long amount, byte[] per_commitment_point, HTLCOutputInCommitment htlc) {
88                             return underlying_base.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc);
89                         }
90                         @Override public Result_SignatureNoneZ sign_closing_transaction(ClosingTransaction closing_tx) {
91                             return underlying_base.sign_closing_transaction(closing_tx);
92                         }
93                         @Override public Result_SignatureNoneZ sign_holder_anchor_input(byte[] anchor_tx, long input) {
94                             return underlying_base.sign_holder_anchor_input(anchor_tx, input);
95                         }
96                         @Override public Result_C2Tuple_SignatureSignatureZNoneZ sign_channel_announcement(UnsignedChannelAnnouncement msg) {
97                             return underlying_base.sign_channel_announcement(msg);
98                         }
99                         @Override public void ready_channel(ChannelTransactionParameters params) {
100                             underlying_base.ready_channel(params);
101                         }
102                     };
103                     Sign.SignInterface si = new Sign.SignInterface() {
104                         @Override
105                         public byte[] write() {
106                             return underlying_ck.write();
107                         }
108                     };
109                     Sign resp = Sign.new_impl(si, bsi, underlying_base.get_pubkeys());
110                     must_free_objs.add(new WeakReference<>(si));
111                     must_free_objs.add(new WeakReference<>(bsi));
112                     must_free_objs.add(new WeakReference<>(resp));
113                     must_free_objs.add(new WeakReference<>(underlying_base));
114                     must_free_objs.add(new WeakReference<>(underlying_ck));
115                     return resp;
116                 }
117
118                 @Override
119                 public byte[] get_secure_random_bytes() {
120                     return underlying_if.get_secure_random_bytes();
121                 }
122
123                 @Override
124                 public Result_SignDecodeErrorZ read_chan_signer(byte[] reader) {
125                     return underlying_if.read_chan_signer(reader);
126                 }
127
128                 @Override
129                 public Result_RecoverableSignatureNoneZ sign_invoice(byte[] hrp_bytes, UInt5[] invoice_data, Recipient receipient) {
130                     return underlying_if.sign_invoice(hrp_bytes, invoice_data, receipient);
131                 }
132
133                 @Override
134                 public byte[] get_inbound_payment_key_material() {
135                     return underlying_if.get_inbound_payment_key_material();
136                 }
137             });
138         }
139
140         Watch get_manual_watch() {
141             Watch.WatchInterface watch_impl = new Watch.WatchInterface() {
142                 public ChannelMonitorUpdateStatus watch_channel(OutPoint funding_txo, ChannelMonitor monitor) {
143                     synchronized (monitors) {
144                         assert monitors.put(Arrays.toString(funding_txo.get_txid()), monitor) == null;
145                     }
146                     return ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
147                 }
148
149                 public ChannelMonitorUpdateStatus update_channel(OutPoint funding_txo, ChannelMonitorUpdate update) {
150                     synchronized (monitors) {
151                         String txid = Arrays.toString(funding_txo.get_txid());
152                         assert monitors.containsKey(txid);
153                         Result_NoneNoneZ update_res = monitors.get(txid).update_monitor(update, tx_broadcaster, fee_estimator, logger);
154                         assert update_res instanceof Result_NoneNoneZ.Result_NoneNoneZ_OK;
155                     }
156                     return ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
157                 }
158
159                 @Override
160                 public ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[] release_pending_monitor_events() {
161                     synchronized (monitors) {
162                         assert monitors.size() <= 1;
163                         for (ChannelMonitor mon : monitors.values()) {
164                             ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[] res = new ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[1];
165                             res[0] = ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ.of(mon.get_funding_txo().get_a(), mon.get_and_clear_pending_monitor_events(), mon.get_counterparty_node_id());
166                             return res;
167                         }
168                     }
169                     return new ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[0];
170                 }
171             };
172             Watch watch = Watch.new_impl(watch_impl);
173             must_free_objs.add(new WeakReference<>(watch_impl));
174             must_free_objs.add(new WeakReference<>(watch));
175             return watch;
176         }
177
178         UserConfig get_config() {
179             ChannelHandshakeConfig channel_config = ChannelHandshakeConfig.with_default();
180             channel_config.set_announced_channel(true);
181             UserConfig config = UserConfig.with_default();
182             config.set_channel_handshake_config(channel_config);
183             return config;
184         }
185
186         NioPeerHandler nio_peer_handler;
187         short nio_port;
188         final byte seed;
189         final Logger logger;
190         final FeeEstimator fee_estimator;
191         final BroadcasterInterface tx_broadcaster;
192         final KeysManager explicit_keys_manager;
193         final KeysInterface keys_interface;
194         final ChainMonitor chain_monitor;
195         NetworkGraph router;
196         P2PGossipSync route_handler;
197         final Watch chain_watch;
198         final HashSet<String> filter_additions;
199         Option_FilterZ filter;
200         ChannelManager chan_manager;
201         PeerManager peer_manager;
202         final HashMap<String, ChannelMonitor> monitors; // Wow I forgot just how terrible Java is - we can't put a byte array here.
203         byte[] node_id;
204         byte[] connected_peer_node_id = null;
205         final LinkedList<byte[]> broadcast_set = new LinkedList<>();
206         final LinkedList<Event> pending_manager_events = new LinkedList<>();
207         private final CustomMessageHandler custom_message_handler;
208         final LinkedList<byte[]> received_custom_messages = new LinkedList<>();
209         final LinkedList<byte[]> custom_messages_to_send = new LinkedList<>();
210         ChannelManagerConstructor constructor = null;
211         InvoicePayer payer = null;
212         GcCheck obj = new GcCheck();
213
214         private ChannelMonitor test_mon_roundtrip(OutPoint expected_id, byte[] data) {
215             // Because get_funding_txo() returns an OutPoint in a tuple that is a reference to an OutPoint inside the
216             // ChannelMonitor, its a good test to ensure that the OutPoint isn't freed (or is cloned) before the
217             // ChannelMonitor is. This used to be broken.
218             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_monitor = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(data, keys_interface);
219             assert roundtrip_monitor instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
220             must_free_objs.add(new WeakReference<>(roundtrip_monitor));
221             TwoTuple_OutPointScriptZ funding_txo = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_monitor).res.get_b().get_funding_txo();
222             must_free_objs.add(new WeakReference<>(funding_txo));
223             System.gc(); System.runFinalization(); // Give the GC a chance to run.
224             assert Arrays.equals(funding_txo.get_a().get_txid(), expected_id.get_txid());
225             assert funding_txo.get_a().get_index() == expected_id.get_index();
226             Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_two = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(data, keys_interface);
227             assert roundtrip_two instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
228             must_free_objs.add(new WeakReference<>(((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_two).res.get_b()));
229             must_free_objs.add(new WeakReference<>(((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_two).res));
230             must_free_objs.add(new WeakReference<>(roundtrip_two));
231             return ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_two).res.get_b();
232         }
233
234         private Peer(Object _dummy, byte seed) {
235             logger = Logger.new_impl((org.ldk.structs.Record arg)->{
236                 if (arg.get_level() == Level.LDKLevel_Error)
237                     System.err.println(seed + ": " + arg.get_module_path() + " - " + arg.get_args());
238                 else
239                     System.out.println(seed + ": " + arg.get_module_path() + " - " + arg.get_args());
240             });
241             fee_estimator = FeeEstimator.new_impl((confirmation_target -> 253));
242             tx_broadcaster = BroadcasterInterface.new_impl(tx -> {
243                 synchronized (broadcast_set) {
244                     broadcast_set.add(tx);
245                     broadcast_set.notifyAll();
246                 }
247             });
248             monitors = new HashMap<>();
249             this.seed = seed;
250             Persist persister = Persist.new_impl(new Persist.PersistInterface() {
251                 @Override
252                 public ChannelMonitorUpdateStatus persist_new_channel(OutPoint id, ChannelMonitor data, MonitorUpdateId update_id) {
253                     synchronized (monitors) {
254                         String key = Arrays.toString(id.to_channel_id());
255                         ChannelMonitor res = test_mon_roundtrip(id, data.write());
256                         assert monitors.put(key, res) == null;
257                     }
258                     return ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
259                 }
260
261                 @Override
262                 public ChannelMonitorUpdateStatus update_persisted_channel(OutPoint id, ChannelMonitorUpdate update, ChannelMonitor data, MonitorUpdateId update_id) {
263                     synchronized (monitors) {
264                         String key = Arrays.toString(id.to_channel_id());
265                         ChannelMonitor res = test_mon_roundtrip(id, data.write());
266                         // Note that we use a serialization-roundtrip copy of data here, not the original, as this can
267                         // expose the JVM JIT bug where it finalize()s things still being called.
268                         assert monitors.put(key, res) != null;
269                     }
270                     return ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
271                 }
272             });
273
274             filter_additions = new HashSet<>();
275             if (use_filter) {
276                 this.filter = Option_FilterZ.some(Filter.new_impl(new Filter.FilterInterface() {
277                     @Override public void register_tx(byte[] txid, byte[] script_pubkey) {
278                         filter_additions.add(Arrays.toString(txid));
279                     }
280                     @Override public void register_output(WatchedOutput output) {
281                         filter_additions.add(Arrays.toString(output.get_outpoint().get_txid()) + ":" + output.get_outpoint().get_index());
282                     }
283                 }));
284             } else {
285                 this.filter = Option_FilterZ.none();
286             }
287
288             if (use_manual_watch) {
289                 chain_watch = get_manual_watch();
290                 chain_monitor = null;
291             } else {
292                 chain_monitor = ChainMonitor.of(filter, tx_broadcaster, logger, fee_estimator, persister);
293                 chain_watch = chain_monitor.as_Watch();
294             }
295
296             byte[] key_seed = new byte[32];
297             for (byte i = 0; i < 32; i++) {
298                 key_seed[i] = (byte) (i ^ seed);
299             }
300             KeysManager keys = KeysManager.of(key_seed, System.currentTimeMillis() / 1000, (int) (System.currentTimeMillis() * 1000));
301             if (use_km_wrapper) {
302                 this.keys_interface = manual_keysif(keys.as_KeysInterface());
303                 this.explicit_keys_manager = null;
304             } else {
305                 this.keys_interface = keys.as_KeysInterface();
306                 this.explicit_keys_manager = keys;
307             }
308
309             this.custom_message_handler = CustomMessageHandler.new_impl(new CustomMessageHandler.CustomMessageHandlerInterface() {
310                 @Override
311                 public Result_NoneLightningErrorZ handle_custom_message(Type msg, byte[] sender_node_id) {
312                     synchronized (received_custom_messages) {
313                         received_custom_messages.add(msg.write());
314                         received_custom_messages.notifyAll();
315                     }
316                     return Result_NoneLightningErrorZ.ok();
317                 }
318
319                 @Override
320                 public TwoTuple_PublicKeyTypeZ[] get_and_clear_pending_msg() {
321                     byte[][] bytes;
322                     synchronized (custom_messages_to_send) {
323                         bytes = custom_messages_to_send.toArray(new byte[0][0]);
324                         custom_messages_to_send.clear();
325                     }
326                     TwoTuple_PublicKeyTypeZ[] ret = new TwoTuple_PublicKeyTypeZ[bytes.length];
327                     for (int i = 0; i < bytes.length; i++) {
328                         final int msg_idx = i;
329                         ret[i] = TwoTuple_PublicKeyTypeZ.of(connected_peer_node_id, Type.new_impl(new Type.TypeInterface() {
330                             @Override public short type_id() { return 4096; }
331                             @Override public String debug_str() { return "Custom Java Message"; }
332                             @Override public byte[] write() { return bytes[msg_idx]; }
333                         }));
334                     }
335                     return ret;
336                 }
337             }, (message_type, buffer) -> {
338                 assert message_type == 4096;
339                 return Result_COption_TypeZDecodeErrorZ.ok(Option_TypeZ.some(Type.new_impl(new Type.TypeInterface() {
340                     @Override public short type_id() { return 4096; }
341                     @Override public String debug_str() { return "Custom Java-Decoded Message"; }
342                     @Override public byte[] write() { return buffer; }
343                 })));
344             });
345         }
346         private void bind_nio() {
347             if (!use_nio_peer_handler) return;
348             if (use_chan_manager_constructor) {
349                 this.nio_peer_handler = this.constructor.nio_peer_handler;
350             } else {
351                 try { this.nio_peer_handler = new NioPeerHandler(peer_manager); } catch (IOException e) { assert false; }
352             }
353             for (short i = 10_000; true; i++) {
354                 try {
355                     nio_peer_handler.bind_listener(new InetSocketAddress("127.0.0.1", i));
356                     nio_port = i;
357                     break;
358                 } catch (IOException e) { assert i < 10_500; }
359             }
360         }
361         private void setup_route_handler() {
362             this.route_handler = P2PGossipSync.of(this.router,
363                 Option_AccessZ.some(Access.new_impl((genesis_hash, short_channel_id) -> Result_TxOutAccessErrorZ.ok(gossip_txout))), this.logger);
364         }
365         Peer(byte seed) {
366             this(null, seed);
367             this.router = NetworkGraph.of(new byte[32], this.logger);
368             this.setup_route_handler();
369
370             if (use_chan_manager_constructor) {
371                 if (use_ignore_handler) {
372                     this.constructor = new ChannelManagerConstructor(Network.LDKNetwork_Bitcoin, get_config(), new byte[32], 0,
373                                                         this.keys_interface, this.fee_estimator, this.chain_monitor, null, this.tx_broadcaster, this.logger);
374                 } else {
375                     this.constructor = new ChannelManagerConstructor(Network.LDKNetwork_Bitcoin, get_config(), new byte[32], 0,
376                                                         this.keys_interface, this.fee_estimator, this.chain_monitor, this.router, this.tx_broadcaster, this.logger);
377                 }
378                 ProbabilisticScoringParameters params = ProbabilisticScoringParameters.with_default();
379                 ProbabilisticScorer default_scorer = ProbabilisticScorer.of(params, this.router, this.logger);
380                 Result_ProbabilisticScorerDecodeErrorZ score_res = ProbabilisticScorer.read(default_scorer.write(), params, this.router, this.logger);
381                 assert score_res.is_ok();
382                 Score score = ((Result_ProbabilisticScorerDecodeErrorZ.Result_ProbabilisticScorerDecodeErrorZ_OK) score_res).res.as_Score();
383                 MultiThreadedLockableScore scorer = null;
384                 if (use_invoice_payer) { scorer = MultiThreadedLockableScore.of(score); }
385                 constructor.chain_sync_completed(new ChannelManagerConstructor.EventHandler() {
386                     @Override public void handle_event(Event event) {
387                         synchronized (pending_manager_events) {
388                             pending_manager_events.add(event);
389                             pending_manager_events.notifyAll();
390                         }
391                     }
392                     @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; }
393                     @Override public void persist_network_graph(byte[] graph_bytes) { assert graph_bytes.length > 1; }
394                     @Override public void persist_scorer(byte[] scorer_bytes) { assert scorer_bytes.length > 1; }
395                 }, scorer);
396                 this.chan_manager = constructor.channel_manager;
397                 this.peer_manager = constructor.peer_manager;
398                 this.payer = constructor.payer;
399                 must_free_objs.add(new WeakReference<>(this.chan_manager));
400             } else {
401                 ChainParameters params = ChainParameters.of(Network.LDKNetwork_Bitcoin, BestBlock.of(new byte[32], 0));
402                 this.chan_manager = ChannelManager.of(this.fee_estimator, chain_watch, tx_broadcaster, logger, this.keys_interface, get_config(), params);
403                 byte[] random_data = keys_interface.get_secure_random_bytes();
404                 Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
405                 assert node_secret.is_ok();
406                 this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), route_handler.as_RoutingMessageHandler(),
407                         IgnoringMessageHandler.of().as_OnionMessageHandler(),
408                         ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res, (int)(System.currentTimeMillis() / 1000),
409                         random_data, logger, this.custom_message_handler);
410                 if (use_invoice_payer) {
411                     this.payer = InvoicePayer.of(this.chan_manager.as_Payer(), Router.new_impl(new Router.RouterInterface() {
412                         @Override public void notify_payment_path_failed(RouteHop[] path, long short_channel_id) {}
413                         @Override public void notify_payment_path_successful(RouteHop[] path) {}
414                         @Override public void notify_payment_probe_successful(RouteHop[] path) {}
415                         @Override public void notify_payment_probe_failed(RouteHop[] path, long short_channel_id) {}
416
417                         @Override
418                         public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters params, byte[] payment_hash, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) {
419                             while (true) {
420                                 try (ReadOnlyNetworkGraph graph = router.read_only()) {
421                                     assert graph.channel(424242) == null;
422                                     long[] channels = graph.list_channels();
423                                     if (channels.length != 1) {
424                                         // If we're using a NioPeerHandler, the handling of announcement signatures and
425                                         // channel broadcasting may be done async, so just wait until the channel shows up.
426                                         assert use_nio_peer_handler;
427                                         continue;
428                                     }
429                                     ChannelInfo chan = graph.channel(channels[0]);
430                                     assert Arrays.equals(chan.get_node_one().as_slice(), chan.get_node_one().write());
431                                     assert Arrays.equals(chan.get_node_one().as_slice(), chan_manager.get_our_node_id()) ||
432                                             Arrays.equals(chan.get_node_two().as_slice(), chan_manager.get_our_node_id());
433                                     break;
434                                 }
435                             }
436                             return UtilMethods.find_route(payer, params, router, first_hops, logger, Score.new_impl(new Score.ScoreInterface() {
437                                 @Override public void payment_path_failed(RouteHop[] path, long scid) {}
438                                 @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage) { return 0; }
439                                 @Override public void payment_path_successful(RouteHop[] path) {}
440                                 @Override public void probe_failed(RouteHop[] path, long short_channel_id) { assert false; }
441                                 @Override public void probe_successful(RouteHop[] path) { assert false; }
442                                 @Override public byte[] write() { assert false; return null; }
443                             }), new byte[32]);
444                         }
445                     }), logger, EventHandler.new_impl(new EventHandler.EventHandlerInterface() {
446                         @Override public void handle_event(Event event) {
447                             synchronized (pending_manager_events) {
448                                 pending_manager_events.add(event);
449                                 pending_manager_events.notifyAll();
450                             }
451                         }
452                     }), Retry.attempts(0));
453                 }
454             }
455
456             this.node_id = chan_manager.get_our_node_id();
457             this.filter = null;
458             bind_nio();
459             System.gc();
460         }
461
462         Object ptr_to;
463         Peer(Peer orig) {
464             this(null, orig.seed);
465             if (use_chan_manager_constructor) {
466                 byte[][] monitors = {orig.monitors.values().stream().iterator().next().write()};
467                 byte[] serialized = orig.chan_manager.write();
468                 byte[] serialized_router = orig.router.write();
469                 try {
470                     Filter filter_nullable = null;
471                     if (this.filter instanceof Option_FilterZ.Some) {
472                         filter_nullable = ((Option_FilterZ.Some) this.filter).some;
473                     }
474                     if (use_ignore_handler) {
475                         this.constructor = new ChannelManagerConstructor(serialized, monitors, get_config(),
476                                 this.keys_interface, this.fee_estimator, this.chain_monitor, filter_nullable,
477                                 null, this.tx_broadcaster, this.logger);
478                     } else {
479                         this.constructor = new ChannelManagerConstructor(serialized, monitors, get_config(),
480                                 this.keys_interface, this.fee_estimator, this.chain_monitor, filter_nullable,
481                                 serialized_router, this.tx_broadcaster, this.logger);
482                         try {
483                             // Test that ChannelManagerConstructor correctly rejects duplicate ChannelMonitors
484                             byte[][] monitors_dupd = new byte[2][];
485                             monitors_dupd[0] = monitors[0];
486                             monitors_dupd[1] = monitors[0];
487                             ChannelManagerConstructor constr = this.constructor = new ChannelManagerConstructor(serialized, monitors_dupd, get_config(),
488                                     this.keys_interface, this.fee_estimator, this.chain_monitor, filter_nullable,
489                                     null, this.tx_broadcaster, this.logger);
490                             assert false;
491                         } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {}
492                     }
493                     this.router = this.constructor.net_graph;
494                     setup_route_handler();
495                     MultiThreadedLockableScore scorer = null;
496                     if (use_invoice_payer) { scorer = MultiThreadedLockableScore.of(ProbabilisticScorer.of(ProbabilisticScoringParameters.with_default(), this.router, this.logger).as_Score()); }
497                     constructor.chain_sync_completed(new ChannelManagerConstructor.EventHandler() {
498                         @Override public void handle_event(Event event) {
499                             synchronized (pending_manager_events) {
500                                 pending_manager_events.add(event);
501                                 pending_manager_events.notifyAll();
502                             }
503                         }
504                         @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; }
505                         @Override public void persist_network_graph(byte[] graph_bytes) { assert graph_bytes.length > 1; }
506                         @Override public void persist_scorer(byte[] scorer_bytes) { assert scorer_bytes.length > 1; }
507                     }, scorer);
508                     this.chan_manager = constructor.channel_manager;
509                     this.payer = constructor.payer;
510                     this.peer_manager = constructor.peer_manager;
511                     must_free_objs.add(new WeakReference<>(this.chan_manager));
512                     // If we are using a ChannelManagerConstructor, we may have pending events waiting on the old peer
513                     // which have been removed from the ChannelManager but which we still need to handle.
514                     this.pending_manager_events.addAll(orig.pending_manager_events);
515                     if (!this.pending_manager_events.isEmpty()) {
516                         // However, this implies cross_reload_ref_pollution
517                         cross_reload_ref_pollution = true;
518                     }
519                 } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {
520                     assert false;
521                 }
522             } else {
523                 this.router = NetworkGraph.of(new byte[32], this.logger);
524                 this.setup_route_handler();
525                 ChannelMonitor[] monitors = new ChannelMonitor[1];
526                 assert orig.monitors.size() == 1;
527                 if (!break_cross_peer_refs) {
528                     monitors[0] = orig.monitors.values().stream().iterator().next();
529                 } else {
530                     byte[] serialized = orig.monitors.values().stream().iterator().next().write();
531                     Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res =
532                             UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(serialized, this.keys_interface);
533                     assert res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
534                     monitors[0] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
535                 }
536                 byte[] serialized = orig.chan_manager.write();
537                 Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ read_res =
538                         UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(serialized, this.keys_interface, this.fee_estimator, this.chain_watch, this.tx_broadcaster, this.logger, get_config(), monitors);
539                 assert read_res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK;
540                 this.chan_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK) read_res).res.get_b();
541                 this.chain_watch.watch_channel(monitors[0].get_funding_txo().get_a(), monitors[0]);
542                 byte[] random_data = keys_interface.get_secure_random_bytes();
543                 Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
544                 assert node_secret.is_ok();
545                 this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), route_handler.as_RoutingMessageHandler(),
546                         IgnoringMessageHandler.of().as_OnionMessageHandler(),
547                         ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res, (int)(System.currentTimeMillis() / 1000),
548                         random_data, logger, this.custom_message_handler);
549                 if (!break_cross_peer_refs && (use_manual_watch || use_km_wrapper)) {
550                     // When we pass monitors[0] into chain_watch.watch_channel we create a reference from the new Peer to a
551                     // field in the old peer, preventing freeing of the original Peer until the new Peer is freed. Thus, we
552                     // shouldn't bother waiting for the original to be freed later on.
553                     cross_reload_ref_pollution = true;
554                 }
555                 if (use_invoice_payer) {
556                     this.payer = InvoicePayer.of(this.chan_manager.as_Payer(), Router.new_impl(new Router.RouterInterface() {
557                         @Override public void notify_payment_path_failed(RouteHop[] path, long short_channel_id) {}
558                         @Override public void notify_payment_path_successful(RouteHop[] path) {}
559                         @Override public void notify_payment_probe_successful(RouteHop[] path) {}
560                         @Override public void notify_payment_probe_failed(RouteHop[] path, long short_channel_id) {}
561
562                         @Override
563                         public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters route_params, byte[] payment_hash, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) {
564                             return UtilMethods.find_route(payer, route_params, router, first_hops, logger, Score.new_impl(new Score.ScoreInterface() {
565                                 @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage) { return 0; }
566                                 @Override public void payment_path_failed(RouteHop[] path, long scid) {}
567                                 @Override public void payment_path_successful(RouteHop[] path) {}
568                                 @Override public void probe_failed(RouteHop[] path, long short_channel_id) { assert false; }
569                                 @Override public void probe_successful(RouteHop[] path) { assert false; }
570                                 @Override public byte[] write() { assert false; return null; }
571                             }), new byte[32]);
572                         }
573                     }), logger, EventHandler.new_impl(new EventHandler.EventHandlerInterface() {
574                         @Override public void handle_event(Event event) {
575                             synchronized (pending_manager_events) {
576                                 pending_manager_events.add(event);
577                                 pending_manager_events.notifyAll();
578                             }
579                         }
580                     }), Retry.attempts(0));
581                 }
582             }
583             this.node_id = chan_manager.get_our_node_id();
584             bind_nio();
585
586             if (cross_reload_ref_pollution) {
587                 // This really, really needs to be handled at the bindings layer, but its rather complicated -
588                 // ChannelSigners can be cloned and passed around without java being involved, resulting in them being
589                 // owned by both one or more ChannelMonitors and a ChannelManager, with only one having proper pointers
590                 // to the ChannelSigner. Ideally, the ChannelSigner would have a global reference to the Java
591                 // implementation class, but that results in circular references. Instead, we need some ability to,
592                 // while cloning ChannelSigners, add new references in the calling Java struct (ie ChannelMonitor) to
593                 // the ChannelSigner.
594                 this.ptr_to = orig.chan_manager;
595             }
596             this.filter = null;
597         }
598
599         TwoTuple_TxidCVec_C2Tuple_u32TxOutZZZ[] connect_block(Block b, int height, long expected_monitor_update_len) {
600             byte[] header = Arrays.copyOfRange(b.bitcoinSerialize(), 0, 80);
601             TwoTuple_usizeTransactionZ[] txn;
602             if (b.hasTransactions()) {
603                 assert b.getTransactions().size() == 1;
604                 TwoTuple_usizeTransactionZ txp = TwoTuple_usizeTransactionZ.of((long) 0, b.getTransactions().get(0).bitcoinSerialize());
605                 txn = new TwoTuple_usizeTransactionZ[]{txp};
606             } else
607                 txn = new TwoTuple_usizeTransactionZ[0];
608             if (chain_monitor != null) {
609                 chan_manager.as_Listen().block_connected(b.bitcoinSerialize(), height);
610                 chain_monitor.as_Listen().block_connected(b.bitcoinSerialize(), height);
611             } else {
612                 chan_manager.as_Confirm().transactions_confirmed(header, txn, height);
613                 chan_manager.as_Confirm().best_block_updated(header, height);
614                 // Connect manually if we aren't using a ChainMonitor and are implementing Watch ourselves
615                 synchronized (monitors) {
616                     assert monitors.size() == 1;
617                     for (ChannelMonitor mon : monitors.values()) {
618                         TwoTuple_TxidCVec_C2Tuple_u32TxOutZZZ[] ret = mon.block_connected(header, txn, height, tx_broadcaster, fee_estimator, logger);
619                         assert ret.length == expected_monitor_update_len;
620                         return ret;
621                     }
622                 }
623             }
624             return null;
625         }
626
627         Event[] get_monitor_events(int expected_len) {
628             if (use_chan_manager_constructor) {
629                 while (true) {
630                     synchronized (this.pending_manager_events) {
631                         if (expected_len != 0 && this.pending_manager_events.size() == expected_len) {
632                             break;
633                         }
634                     }
635                     if (expected_len == 0) {
636                         try { Thread.sleep(500); } catch (InterruptedException e) { assert false; }
637                         break;
638                     } else {
639                         Thread.yield();
640                     }
641                 }
642                 synchronized (this.pending_manager_events) {
643                     Event[] res = this.pending_manager_events.toArray(new Event[0]);
644                     this.pending_manager_events.clear();
645                     assert res.length == expected_len;
646                     return res;
647                 }
648             } else if (chain_monitor != null) {
649                 ArrayList<Event> l = new ArrayList<Event>();
650                 chain_monitor.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
651                 assert l.size() == expected_len;
652                 return l.toArray(new Event[0]);
653             } else {
654                 synchronized (monitors) {
655                     assert monitors.size() == 1;
656                     for (ChannelMonitor mon : monitors.values()) {
657                         Event[] res = mon.get_and_clear_pending_events();
658                         assert res.length == expected_len;
659                         return res;
660                     }
661                     return null;
662                 }
663             }
664         }
665
666         Event[] get_manager_events(int expected_len, Peer peer1, Peer peer2) {
667             assert expected_len != 0;
668             if (!use_nio_peer_handler) {
669                 maybe_exchange_peer_messages(peer1, peer2);
670             }
671             Event[] res = new Event[0];
672             if (use_chan_manager_constructor) {
673                 while (res.length < expected_len) {
674                     synchronized (this.pending_manager_events) {
675                         if (this.pending_manager_events.size() >= expected_len) {
676                             res = this.pending_manager_events.toArray(res);
677                             assert res.length == expected_len;
678                             this.pending_manager_events.clear();
679                         }
680                         if (res.length < expected_len) {
681                             try { this.pending_manager_events.wait(); } catch (InterruptedException e) { assert false; }
682                         }
683                     }
684                 }
685             } else {
686                 ArrayList<Event> l = new ArrayList<Event>();
687                 while (l.size() < expected_len) {
688                     Thread.yield();
689                     if (use_nio_peer_handler) {
690                         peer1.nio_peer_handler.check_events();
691                         peer2.nio_peer_handler.check_events();
692                     }
693                     chan_manager.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
694                 }
695                 return l.toArray(new Event[0]);
696             }
697             assert res.length == expected_len;
698             return res;
699         }
700     }
701
702     static class DescriptorHolder { SocketDescriptor val; }
703
704     boolean running = false;
705     final LinkedList<Runnable> runqueue = new LinkedList();
706     boolean ran = false;
707     Thread t = new Thread(() -> {
708             while (true) {
709                 try {
710                     Runnable r;
711                     synchronized (runqueue) {
712                         while (runqueue.isEmpty()) {
713                             runqueue.wait();
714                         }
715                         running = true;
716                         r = runqueue.pollFirst();
717                     }
718                     r.run();
719                     synchronized (runqueue) {
720                         running = false;
721                         runqueue.notifyAll();
722                     }
723                 } catch (InterruptedException e) {
724                     return;
725                 }
726             }
727     });
728
729     void maybe_exchange_peer_messages(Peer peer1, Peer peer2) {
730         if (!use_nio_peer_handler) {
731             while (true) {
732                 peer1.peer_manager.process_events();
733                 peer2.peer_manager.process_events();
734                 synchronized (runqueue) {
735                     if (runqueue.isEmpty() && !running) {
736                         if (ran) {
737                             ran = false;
738                             continue;
739                         } else { break; }
740                     }
741                     try { runqueue.wait(); } catch (InterruptedException e) { assert false; }
742                 }
743             }
744         } else if (!use_chan_manager_constructor) {
745             peer1.nio_peer_handler.check_events();
746             peer2.nio_peer_handler.check_events();
747         }
748     }
749     void do_read_event(PeerManager pm, SocketDescriptor descriptor, byte[] data) {
750         if (!t.isAlive()) t.start();
751         synchronized (runqueue) {
752             ran = true;
753             runqueue.add(() -> {
754                 Result_boolPeerHandleErrorZ res = pm.read_event(descriptor, data);
755                 assert res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK;
756             });
757             runqueue.notifyAll();
758         }
759         must_free_objs.add(new WeakReference<>(data));
760     }
761
762     void connect_peers(final Peer peer1, final Peer peer2) {
763         peer2.connected_peer_node_id = peer1.node_id;
764         peer1.connected_peer_node_id = peer2.node_id;
765         if (use_nio_peer_handler) {
766             try {
767                 peer1.nio_peer_handler.connect(peer2.chan_manager.get_our_node_id(), new InetSocketAddress("127.0.0.1", peer2.nio_port), 100);
768             } catch (IOException e) { assert false; }
769             while (peer1.peer_manager.get_peer_node_ids().length == 0 || peer2.peer_manager.get_peer_node_ids().length == 0) {
770                 Thread.yield();
771             }
772         } else {
773             DescriptorHolder descriptor1 = new DescriptorHolder();
774             DescriptorHolder descriptor1ref = descriptor1;
775             SocketDescriptor descriptor2 = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
776                 @Override
777                 public long send_data(byte[] data, boolean resume_read) {
778                     do_read_event(peer1.peer_manager, descriptor1ref.val, data);
779                     return data.length;
780                 }
781
782                 @Override public void disconnect_socket() { assert false; }
783                 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == 2; }
784                 @Override public long hash() { return 2; }
785             });
786
787             descriptor1.val = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
788                 @Override
789                 public long send_data(byte[] data, boolean resume_read) {
790                     do_read_event(peer2.peer_manager, descriptor2, data);
791                     return data.length;
792                 }
793
794                 @Override public void disconnect_socket() { assert false; }
795                 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == 1; }
796                 @Override public long hash() { return 1; }
797             });
798
799             Result_CVec_u8ZPeerHandleErrorZ conn_res = peer1.peer_manager.new_outbound_connection(peer2.node_id, descriptor1.val, Option_NetAddressZ.none());
800             assert conn_res instanceof Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK;
801
802             Result_NonePeerHandleErrorZ inbound_conn_res = peer2.peer_manager.new_inbound_connection(descriptor2, Option_NetAddressZ.none());
803             assert inbound_conn_res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_OK;
804             do_read_event(peer2.peer_manager, descriptor2, ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) conn_res).res);
805
806             maybe_exchange_peer_messages(peer1, peer2);
807         }
808     }
809
810     TestState do_test_message_handler() throws InterruptedException {
811         Peer peer1 = new Peer((byte) 1);
812         Peer peer2 = new Peer((byte) 2);
813
814         connect_peers(peer1, peer2);
815
816         Result__u832APIErrorZ cc_res = peer1.chan_manager.create_channel(peer2.node_id, 100000, 1000, 42, null);
817         assert cc_res instanceof Result__u832APIErrorZ.Result__u832APIErrorZ_OK;
818
819         // Previously, this was a SEGFAULT instead of get_funding_txo() returning null.
820         ChannelDetails pre_funding_chan = peer1.chan_manager.list_channels()[0];
821         assert pre_funding_chan.get_funding_txo() == null;
822
823         Event[] events = peer1.get_manager_events(1, peer1, peer2);
824         assert events[0] instanceof Event.FundingGenerationReady;
825         assert ((Event.FundingGenerationReady) events[0]).channel_value_satoshis == 100000;
826         assert ((Event.FundingGenerationReady) events[0]).user_channel_id == 42;
827         byte[] funding_spk = ((Event.FundingGenerationReady) events[0]).output_script;
828         assert funding_spk.length == 34 && funding_spk[0] == 0 && funding_spk[1] == 32; // P2WSH
829         byte[] chan_id = ((Event.FundingGenerationReady) events[0]).temporary_channel_id;
830
831         NetworkParameters bitcoinj_net = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
832
833         Transaction funding = new Transaction(bitcoinj_net);
834         funding.addInput(new TransactionInput(bitcoinj_net, funding, new byte[0]));
835         funding.getInputs().get(0).setWitness(new TransactionWitness(2)); // Make sure we don't complain about lack of witness
836         funding.getInput(0).getWitness().setPush(0, new byte[]{0x1});
837         funding.addOutput(Coin.SATOSHI.multiply(100000), new Script(funding_spk));
838         Result_NoneAPIErrorZ funding_res = peer1.chan_manager.funding_transaction_generated(chan_id, peer2.node_id, funding.bitcoinSerialize());
839         assert funding_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
840
841         gossip_txout = new TxOut(100000, funding_spk);
842
843         maybe_exchange_peer_messages(peer1, peer2);
844         synchronized (peer1.broadcast_set) {
845             while (peer1.broadcast_set.size() != 1) {
846                 peer1.broadcast_set.wait();
847             }
848         }
849
850         assert peer1.broadcast_set.size() == 1;
851         assert Arrays.equals(peer1.broadcast_set.get(0), funding.bitcoinSerialize());
852         peer1.broadcast_set.clear();
853
854         Block b = new Block(bitcoinj_net, 2, Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[]{funding}));
855         peer1.connect_block(b, 1, 0);
856         peer2.connect_block(b, 1, 0);
857
858         for (int height = 2; height < 10; height++) {
859             b = new Block(bitcoinj_net, 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[0]));
860             peer1.connect_block(b, height, 0);
861             peer2.connect_block(b, height, 0);
862         }
863
864         maybe_exchange_peer_messages(peer1, peer2);
865         while (peer1.chan_manager.list_usable_channels().length != 1 || peer2.chan_manager.list_usable_channels().length != 1)
866
867         peer1.chan_manager.list_channels();
868         ChannelDetails[] peer1_chans = peer1.chan_manager.list_usable_channels();
869         ChannelDetails[] peer2_chans = peer2.chan_manager.list_usable_channels();
870         assert peer1_chans.length == 1;
871         assert peer2_chans.length == 1;
872         assert peer1_chans[0].get_channel_value_satoshis() == 100000;
873         assert peer1_chans[0].get_is_usable();
874         Option_u64Z short_chan_id = peer1_chans[0].get_short_channel_id();
875         assert short_chan_id instanceof Option_u64Z.Some;
876         assert ((Option_u64Z.Some)short_chan_id).some == (1L << 40); // 0th output in the 0th transaction in the 1st block
877         assert Arrays.equals(peer1_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
878         assert Arrays.equals(peer2_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
879
880         Result_InvoiceSignOrCreationErrorZ invoice = UtilMethods.create_invoice_from_channelmanager(peer2.chan_manager, peer2.keys_interface, peer2.logger, Currency.LDKCurrency_Bitcoin, Option_u64Z.some(10000000), "Invoice Description", 7200);
881         assert invoice instanceof Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK;
882         System.out.println("Got invoice: " + ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
883
884         Result_InvoiceParseOrSemanticErrorZ parsed_invoice = Invoice.from_str(((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
885         assert parsed_invoice instanceof Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK;
886         assert Arrays.equals(((Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res.payment_hash(), ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_hash());
887         SignedRawInvoice signed_raw = ((Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res.into_signed_raw();
888         RawInvoice raw_invoice = signed_raw.raw_invoice();
889         byte[] desc_hash = raw_invoice.signable_hash();
890         Description raw_invoice_description = raw_invoice.description();
891         String description_string = raw_invoice_description.into_inner();
892         assert description_string.equals("Invoice Description");
893
894         if (!use_invoice_payer) {
895             byte[] payment_hash = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_hash();
896             byte[] payment_secret = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_secret();
897             byte[] dest_node_id = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.recover_payee_pub_key();
898             assert Arrays.equals(dest_node_id, peer2.node_id);
899             InvoiceFeatures invoice_features = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.features();
900             RouteHint[] route_hints = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.route_hints();
901
902             PaymentParameters payee = PaymentParameters.of(peer2.node_id, invoice_features, route_hints, Option_u64Z.none(), 6*24*14, (byte)1, (byte)2, new long[0]);
903             RouteParameters route_params = RouteParameters.of(payee, 10000000, 42);
904             Result_RouteLightningErrorZ route_res = UtilMethods.find_route(
905                     peer1.chan_manager.get_our_node_id(), route_params, peer1.router,
906                     peer1_chans, peer1.logger, ProbabilisticScorer.of(ProbabilisticScoringParameters.with_default(), peer1.router, peer1.logger).as_Score(), new byte[32]);
907             assert route_res instanceof Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK;
908             Route route = ((Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK) route_res).res;
909             assert route.get_paths().length == 1;
910             assert route.get_paths()[0].length == 1;
911             assert route.get_paths()[0][0].get_fee_msat() == 10000000;
912
913             Result_PaymentIdPaymentSendFailureZ payment_res = peer1.chan_manager.send_payment(route, payment_hash, payment_secret);
914             assert payment_res instanceof Result_PaymentIdPaymentSendFailureZ.Result_PaymentIdPaymentSendFailureZ_OK;
915
916             RouteHop[][] hops = new RouteHop[1][1];
917             byte[] hop_pubkey = new byte[33];
918             hop_pubkey[0] = 3;
919             hop_pubkey[1] = 42;
920             NodeFeatures node_features = NodeFeatures.empty();
921             ChannelFeatures channel_features = ChannelFeatures.empty();
922             hops[0][0] = RouteHop.of(hop_pubkey, node_features, 42, channel_features, 100, 0);
923             Route r2 = Route.of(hops, payee);
924             payment_res = peer1.chan_manager.send_payment(r2, payment_hash, payment_secret);
925             assert payment_res instanceof Result_PaymentIdPaymentSendFailureZ.Result_PaymentIdPaymentSendFailureZ_Err;
926         } else {
927             Result_PaymentIdPaymentErrorZ send_res = peer1.payer.pay_invoice(((Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res);
928             assert send_res instanceof Result_PaymentIdPaymentErrorZ.Result_PaymentIdPaymentErrorZ_OK;
929         }
930
931         if (reload_peers) {
932             if (use_chan_manager_constructor) {
933                 peer1.constructor.interrupt();
934                 peer2.constructor.interrupt();
935             } else if (use_nio_peer_handler) {
936                 peer1.nio_peer_handler.interrupt();
937                 peer2.nio_peer_handler.interrupt();
938             }
939             WeakReference<Peer> op1 = new WeakReference<Peer>(peer1);
940             peer1 = new Peer(peer1);
941             peer2 = new Peer(peer2);
942             return new TestState(op1, peer1, peer2, b.getHash());
943         }
944         return new TestState(null, peer1, peer2, b.getHash());
945     }
946
947     boolean cross_reload_ref_pollution = false;
948     class TestState {
949         private final WeakReference<Peer> ref_block;
950         private final Peer peer1;
951         private final Peer peer2;
952         public Sha256Hash best_blockhash;
953
954         public TestState(WeakReference<Peer> ref_block, Peer peer1, Peer peer2, Sha256Hash best_blockhash) {
955             this.ref_block = ref_block;
956             this.peer1 = peer1;
957             this.peer2 = peer2;
958             this.best_blockhash = best_blockhash;
959         }
960     }
961     void do_test_message_handler_b(TestState state) throws InterruptedException {
962         GcCheck obj = new GcCheck();
963         if (state.ref_block != null) {
964             // Ensure the original peers get freed before we move on. Note that we have to be in a different function
965             // scope to do so as the (at least current OpenJDK) JRE won't release anything created in the same scope.
966             while (!cross_reload_ref_pollution && state.ref_block.get() != null) {
967                 System.gc();
968                 System.runFinalization();
969             }
970             connect_peers(state.peer1, state.peer2);
971         }
972
973         Event[] events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
974         assert events[0] instanceof Event.PendingHTLCsForwardable;
975         state.peer2.chan_manager.process_pending_htlc_forwards();
976
977         events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
978         assert events[0] instanceof Event.PaymentReceived;
979         assert ((Event.PaymentReceived)events[0]).purpose instanceof PaymentPurpose.InvoicePayment;
980         byte[] payment_preimage = ((PaymentPurpose.InvoicePayment)((Event.PaymentReceived)events[0]).purpose).payment_preimage;
981         assert !Arrays.equals(payment_preimage, new byte[32]);
982         state.peer2.chan_manager.claim_funds(payment_preimage);
983
984         events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
985         assert events[0] instanceof Event.PaymentClaimed;
986         assert ((Event.PaymentClaimed)events[0]).purpose instanceof PaymentPurpose.InvoicePayment;
987         payment_preimage = ((PaymentPurpose.InvoicePayment)((Event.PaymentClaimed)events[0]).purpose).payment_preimage;
988         assert !Arrays.equals(payment_preimage, new byte[32]);
989
990         events = state.peer1.get_manager_events(2, state.peer1, state.peer2);
991         assert events[0] instanceof Event.PaymentSent;
992         assert Arrays.equals(((Event.PaymentSent) events[0]).payment_preimage, payment_preimage);
993         assert events[1] instanceof Event.PaymentPathSuccessful;
994         assert Arrays.equals(((Event.PaymentPathSuccessful) events[1]).payment_hash, ((Event.PaymentSent) events[0]).payment_hash);
995
996         if (use_nio_peer_handler) {
997             // We receive PaymentSent immediately upon receipt of the payment preimage, but we expect to not have an
998             // HTLC transaction to broadcast below, which requires a bit more time to fully complete the
999             // commitment-transaction-update dance between both peers.
1000             Thread.sleep(100);
1001         }
1002
1003         if (state.peer1.chain_monitor != null) {
1004             Balance[] peer1_balances = state.peer1.chain_monitor.get_claimable_balances(state.peer1.chan_manager.list_channels());
1005             assert peer1_balances.length == 0;
1006             Balance[] peer2_balances = state.peer2.chain_monitor.get_claimable_balances(state.peer2.chan_manager.list_channels());
1007             assert peer2_balances.length == 0;
1008         }
1009
1010         ChannelDetails[] peer1_chans = state.peer1.chan_manager.list_channels();
1011
1012         if (nice_close) {
1013             Result_NoneAPIErrorZ close_res = state.peer1.chan_manager.close_channel(peer1_chans[0].get_channel_id(), state.peer2.node_id);
1014             assert close_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
1015             maybe_exchange_peer_messages(state.peer1, state.peer2);
1016             synchronized (state.peer1.broadcast_set) {
1017                 while (state.peer1.broadcast_set.size() != 1) state.peer1.broadcast_set.wait();
1018             }
1019             synchronized (state.peer2.broadcast_set) {
1020                 while (state.peer2.broadcast_set.size() != 1) state.peer2.broadcast_set.wait();
1021             }
1022         } else {
1023             state.peer1.chan_manager.force_close_all_channels_broadcasting_latest_txn();
1024             maybe_exchange_peer_messages(state.peer1, state.peer2);
1025             synchronized (state.peer1.broadcast_set) {
1026                 while (state.peer1.broadcast_set.size() != 1) state.peer1.broadcast_set.wait();
1027             }
1028             synchronized (state.peer2.broadcast_set) {
1029                 while (state.peer2.broadcast_set.size() != 1) state.peer2.broadcast_set.wait();
1030             }
1031         }
1032
1033         assert state.peer1.broadcast_set.size() == 1;
1034         assert state.peer2.broadcast_set.size() == 1;
1035
1036         events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
1037         assert events[0] instanceof Event.ChannelClosed;
1038         events = state.peer1.get_manager_events(1, state.peer1, state.peer2);
1039         assert events[0] instanceof Event.ChannelClosed;
1040
1041         if (state.peer1.chain_monitor != null) {
1042             Balance[] peer1_balances = state.peer1.chain_monitor.get_claimable_balances(state.peer1.chan_manager.list_channels());
1043             assert peer1_balances.length == 1;
1044             for (Balance bal : peer1_balances) {
1045                 assert bal instanceof Balance.ClaimableOnChannelClose;
1046                 long expected_tx_fee = 183;
1047                 assert ((Balance.ClaimableOnChannelClose) bal).claimable_amount_satoshis == 100000 - 1 - 10000 - expected_tx_fee;
1048             }
1049             Balance[] peer2_balances = state.peer2.chain_monitor.get_claimable_balances(state.peer2.chan_manager.list_channels());
1050             assert peer2_balances.length == 1;
1051             for (Balance bal : peer2_balances) {
1052                 assert bal instanceof Balance.ClaimableOnChannelClose;
1053                 assert ((Balance.ClaimableOnChannelClose) bal).claimable_amount_satoshis == 10000 + 1;
1054             }
1055         }
1056
1057         if (!nice_close) {
1058             NetworkParameters bitcoinj_net = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
1059             Transaction tx = new Transaction(bitcoinj_net, state.peer1.broadcast_set.getFirst());
1060             Block b = new Block(bitcoinj_net, 2, state.best_blockhash, Sha256Hash.ZERO_HASH, 42, 0, 0,
1061                     Arrays.asList(new Transaction[]{tx}));
1062             TwoTuple_TxidCVec_C2Tuple_u32TxOutZZZ[] watch_outputs = state.peer2.connect_block(b, 10, 1);
1063             if (watch_outputs != null) { // We only process watch_outputs manually when we use a manually-build Watch impl
1064                 assert watch_outputs.length == 1;
1065                 assert Arrays.equals(watch_outputs[0].get_a(), tx.getTxId().getReversedBytes());
1066                 assert watch_outputs[0].get_b().length == 2;
1067                 assert watch_outputs[0].get_b()[0].get_a() == 0;
1068                 assert watch_outputs[0].get_b()[1].get_a() == 1;
1069             }
1070
1071             for (int i = 11; i < 21; i++) {
1072                 b = new Block(bitcoinj_net, 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, new ArrayList<>());
1073                 state.peer2.connect_block(b, i, 0);
1074             }
1075
1076             Event[] broadcastable_event = state.peer2.get_monitor_events(1);
1077             for (ChannelMonitor mon : state.peer2.monitors.values()) {
1078                 // This used to be buggy and double-free, so go ahead and fetch them!
1079                 byte[][] txn = mon.get_latest_holder_commitment_txn(state.peer2.logger);
1080             }
1081             assert broadcastable_event.length == 1;
1082             assert broadcastable_event[0] instanceof Event.SpendableOutputs;
1083             if (state.peer2.explicit_keys_manager != null) {
1084                 TxOut[] additional_outputs = new TxOut[]{new TxOut(420, new byte[]{0x42})};
1085                 Result_TransactionNoneZ tx_res = state.peer2.explicit_keys_manager.spend_spendable_outputs(((Event.SpendableOutputs) broadcastable_event[0]).outputs, additional_outputs, new byte[]{0x00}, 253);
1086                 assert tx_res instanceof Result_TransactionNoneZ.Result_TransactionNoneZ_OK;
1087                 Transaction built_tx = new Transaction(bitcoinj_net, ((Result_TransactionNoneZ.Result_TransactionNoneZ_OK) tx_res).res);
1088                 assert built_tx.getOutputs().size() == 2;
1089                 assert Arrays.equals(built_tx.getOutput(1).getScriptBytes(), new byte[]{0x00});
1090                 assert Arrays.equals(built_tx.getOutput(0).getScriptBytes(), new byte[]{0x42});
1091                 assert built_tx.getOutput(0).getValue().value == 420;
1092             }
1093         }
1094
1095         // Test exchanging a custom message (note that ChannelManagerConstructor) always loads an IgnorimgMessageHandler
1096         // so we cannot exchange custom messages with it
1097         if (!use_chan_manager_constructor) {
1098             byte[] custom_message_bytes = new byte[]{0x42, 0x44, 0x43, 0x00};
1099             synchronized(state.peer1.custom_messages_to_send) {
1100                 state.peer1.custom_messages_to_send.add(custom_message_bytes);
1101             }
1102             state.peer1.peer_manager.process_events();
1103             synchronized (state.peer2.received_custom_messages) {
1104                 while (true) {
1105                     if (state.peer2.received_custom_messages.isEmpty()) {
1106                         state.peer2.received_custom_messages.wait();
1107                         continue;
1108                     }
1109                     assert state.peer2.received_custom_messages.size() == 1;
1110                     assert Arrays.equals(state.peer2.received_custom_messages.get(0), custom_message_bytes);
1111                     break;
1112                 }
1113             }
1114         }
1115
1116         if (use_nio_peer_handler) {
1117             state.peer1.peer_manager.disconnect_by_node_id(state.peer2.chan_manager.get_our_node_id(), false);
1118             while (state.peer1.peer_manager.get_peer_node_ids().length != 0) Thread.yield();
1119             while (state.peer2.peer_manager.get_peer_node_ids().length != 0) Thread.yield();
1120             state.peer1.nio_peer_handler.interrupt();
1121             state.peer2.nio_peer_handler.interrupt();
1122         }
1123
1124         state.peer1.get_monitor_events(0);
1125         state.peer2.get_monitor_events(0);
1126
1127         if (use_chan_manager_constructor) {
1128             state.peer1.constructor.interrupt();
1129             state.peer2.constructor.interrupt();
1130         }
1131
1132         t.interrupt();
1133
1134         if (state.peer1.router != null)
1135             state.peer1.router.write();
1136
1137         // Construct the only Option_Enum::Variant(OpaqueStruct) we have in the codebase as this used to cause double-frees:
1138         byte[] serd = new byte[] {(byte)0xd9,(byte)0x77,(byte)0xcb,(byte)0x9b,(byte)0x53,(byte)0xd9,(byte)0x3a,(byte)0x6f,(byte)0xf6,(byte)0x4b,(byte)0xb5,(byte)0xf1,(byte)0xe1,(byte)0x58,(byte)0xb4,(byte)0x09,(byte)0x4b,(byte)0x66,(byte)0xe7,(byte)0x98,(byte)0xfb,(byte)0x12,(byte)0x91,(byte)0x11,(byte)0x68,(byte)0xa3,(byte)0xcc,(byte)0xdf,(byte)0x80,(byte)0xa8,(byte)0x30,(byte)0x96,(byte)0x34,(byte)0x0a,(byte)0x6a,(byte)0x95,(byte)0xda,(byte)0x0a,(byte)0xe8,(byte)0xd9,(byte)0xf7,(byte)0x76,(byte)0x52,(byte)0x8e,(byte)0xec,(byte)0xdb,(byte)0xb7,(byte)0x47,(byte)0xeb,(byte)0x6b,(byte)0x54,(byte)0x54,(byte)0x95,(byte)0xa4,(byte)0x31,(byte)0x9e,(byte)0xd5,(byte)0x37,(byte)0x8e,(byte)0x35,(byte)0xb2,(byte)0x1e,(byte)0x07,(byte)0x3a,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0x19,(byte)0xd6,(byte)0x68,(byte)0x9c,(byte)0x08,(byte)0x5a,(byte)0xe1,(byte)0x65,(byte)0x83,(byte)0x1e,(byte)0x93,(byte)0x4f,(byte)0xf7,(byte)0x63,(byte)0xae,(byte)0x46,(byte)0xa2,(byte)0xa6,(byte)0xc1,(byte)0x72,(byte)0xb3,(byte)0xf1,(byte)0xb6,(byte)0x0a,(byte)0x8c,(byte)0xe2,(byte)0x6f,(byte)0x00,(byte)0x08,(byte)0x3a,(byte)0x84,(byte)0x00,(byte)0x00,(byte)0x03,(byte)0x4d,(byte)0x01,(byte)0x34,(byte)0x13,(byte)0xa7,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x90,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x0f,(byte)0x42,(byte)0x40,(byte)0x00,(byte)0x00,(byte)0x27,(byte)0x10,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x14,(byte)0xde,(byte)0xad,(byte)0xbe,(byte)0xef,(byte)0x42,(byte)0x42,(byte)0x42,(byte)0x42};
1139         Result_ChannelUpdateDecodeErrorZ upd_msg = ChannelUpdate.read(serd);
1140         assert upd_msg instanceof Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK;
1141         assert ((Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK) upd_msg).res.get_contents().get_htlc_maximum_msat() == 0xdeadbeef42424242L;
1142         Option_NetworkUpdateZ upd = Option_NetworkUpdateZ.some(NetworkUpdate.channel_update_message(((Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK) upd_msg).res));
1143     }
1144
1145     java.util.LinkedList<WeakReference<Object>> must_free_objs = new java.util.LinkedList();
1146     int gc_count = 0;
1147     int gc_exp_count = 0;
1148     class GcCheck {
1149         GcCheck() { gc_exp_count += 1; }
1150         @Override
1151         protected void finalize() throws Throwable {
1152             gc_count += 1;
1153             super.finalize();
1154         }
1155     }
1156 }
1157 public class HumanObjectPeerTest {
1158     static 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_ignoring_routing_handler, boolean use_chan_manager_constructor, boolean use_invoice_payer) throws InterruptedException {
1159         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_ignoring_routing_handler, use_chan_manager_constructor, use_invoice_payer);
1160         HumanObjectPeerTestInstance.TestState state = instance.do_test_message_handler();
1161         instance.do_test_message_handler_b(state);
1162         return instance;
1163     }
1164     static 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_ignoring_routing_handler, boolean use_chan_manager_constructor, boolean use_invoice_payer) throws InterruptedException {
1165         HumanObjectPeerTestInstance instance = do_test_run(nice_close, use_km_wrapper, use_manual_watch, reload_peers, break_cross_peer_refs, nio_peer_handler, use_ignoring_routing_handler, use_chan_manager_constructor, use_invoice_payer);
1166         while (instance.gc_count != instance.gc_exp_count) {
1167             System.gc();
1168             System.runFinalization();
1169         }
1170         for (WeakReference<Object> o : instance.must_free_objs)
1171             assert o.get() == null;
1172     }
1173     public static final int TEST_ITERATIONS = (1 << 9);
1174     public static void do_test_message_handler(IntConsumer statusFunction) throws InterruptedException {
1175         Thread gc_thread = new Thread(() -> {
1176             while (true) {
1177                 System.gc();
1178                 System.runFinalization();
1179                 try { Thread.sleep(0, 1); } catch (InterruptedException e) { break; }
1180             }
1181         }, "Test GC Thread");
1182         gc_thread.start();
1183         for (int i = 0; i < TEST_ITERATIONS; i++) {
1184             boolean nice_close =                   (i & (1 << 0)) != 0;
1185             boolean use_km_wrapper =               (i & (1 << 1)) != 0;
1186             boolean use_manual_watch =             (i & (1 << 2)) != 0;
1187             boolean reload_peers =                 (i & (1 << 3)) != 0;
1188             boolean break_cross_refs =             (i & (1 << 4)) != 0;
1189             boolean use_ignoring_routing_handler = (i & (1 << 5)) != 0;
1190             boolean use_chan_manager_constructor = (i & (1 << 6)) != 0;
1191             boolean use_invoice_payer =            (i & (1 << 7)) != 0;
1192             boolean nio_peer_handler =             (i & (1 << 8)) != 0;
1193             if (break_cross_refs && !reload_peers) {
1194                 // There are no cross refs to break without reloading peers.
1195                 continue;
1196             }
1197             if (use_chan_manager_constructor && (use_manual_watch || !nio_peer_handler)) {
1198                 // ChannelManagerConstructor requires a ChainMonitor as the Watch and creates a NioPeerHandler for us.
1199                 continue;
1200             }
1201             if (!use_chan_manager_constructor && (use_ignoring_routing_handler)) {
1202                 // We rely on the ChannelManagerConstructor to convert null into an IgnoringMessageHandler, so don't
1203                 // try to run with an IgnoringMessageHandler unless we're also using a ChannelManagerConstructor.
1204                 continue;
1205             }
1206             if (use_chan_manager_constructor && use_ignoring_routing_handler && use_invoice_payer) {
1207                 // As documented on ChannelManagerConstructor, if we provide a `null` NetworkGraph (because we want to
1208                 // use an IgnoringMessageHandler), no InvoicePayer will be constructored for us, thus we cannot use an
1209                 // InvoicePayer to send payments in this case.
1210                 continue;
1211             }
1212             statusFunction.accept(i);
1213             do_test(nice_close, use_km_wrapper, use_manual_watch, reload_peers, break_cross_refs, nio_peer_handler, use_ignoring_routing_handler, use_chan_manager_constructor, use_invoice_payer);
1214         }
1215         gc_thread.interrupt();
1216         gc_thread.join();
1217     }
1218     @Test
1219     public void test_message_handler() throws InterruptedException {
1220         do_test_message_handler(i -> System.err.println("Running test with flags " + i));
1221     }
1222
1223     // This is used in the test jar to test the built jar is runnable
1224     public static void main(String[] args) {
1225         try {
1226             do_test_message_handler(i -> System.err.println("Running test with flags " + i));
1227         } catch (Exception e) {
1228             System.err.println("Caught exception:");
1229             System.err.println(e);
1230             System.exit(1);
1231         }
1232     }
1233 }