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