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