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