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