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