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