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