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