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;
14 import java.io.IOException;
15 import java.lang.ref.WeakReference;
16 import java.net.InetSocketAddress;
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;
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;
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(); }
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);
57 @Override public byte[] release_commitment_secret(long idx) {
58 return underlying_base.release_commitment_secret(idx);
60 @Override public Result_NoneNoneZ validate_holder_commitment(HolderCommitmentTransaction holder_tx) {
61 return underlying_base.validate_holder_commitment(holder_tx);
63 @Override public byte[] channel_keys_id() {
66 @Override public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_counterparty_commitment(CommitmentTransaction commitment_tx) {
67 return underlying_base.sign_counterparty_commitment(commitment_tx);
69 @Override public Result_NoneNoneZ validate_counterparty_revocation(long idx, byte[] secret) {
70 return underlying_base.validate_counterparty_revocation(idx, secret);
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);
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);
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);
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);
84 @Override public Result_SignatureNoneZ sign_closing_transaction(ClosingTransaction closing_tx) {
85 return underlying_base.sign_closing_transaction(closing_tx);
87 @Override public Result_SignatureNoneZ sign_channel_announcement(UnsignedChannelAnnouncement msg) {
88 return underlying_base.sign_channel_announcement(msg);
90 @Override public void ready_channel(ChannelTransactionParameters params) {
91 underlying_base.ready_channel(params);
94 Sign.SignInterface si = new Sign.SignInterface() {
96 public byte[] write() {
97 return underlying_ck.write();
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));
110 public byte[] get_secure_random_bytes() {
111 return underlying_if.get_secure_random_bytes();
115 public Result_SignDecodeErrorZ read_chan_signer(byte[] reader) {
116 return underlying_if.read_chan_signer(reader);
120 public Result_RecoverableSignatureNoneZ sign_invoice(byte[] invoice_preimage) {
121 return underlying_if.sign_invoice(invoice_preimage);
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;
132 return Result_NoneChannelMonitorUpdateErrZ.ok();
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;
142 return Result_NoneChannelMonitorUpdateErrZ.ok();
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();
153 return new MonitorEvent[0];
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));
162 NioPeerHandler nio_peer_handler;
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.
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();
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.
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();
208 monitors = new HashMap<>();
210 Persist persister = Persist.new_impl(new Persist.PersistInterface() {
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();
220 return Result_NoneChannelMonitorUpdateErrZ.ok();
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();
232 return Result_NoneChannelMonitorUpdateErrZ.ok();
236 filter_additions = new HashSet<>();
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));
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();
248 this.filter = Option_FilterZ.none();
251 if (use_manual_watch) {
252 chain_watch = get_manual_watch();
253 chain_monitor = null;
255 chain_monitor = ChainMonitor.of(filter, tx_broadcaster, logger, fee_estimator, persister);
256 chain_watch = chain_monitor.as_Watch();
259 byte[] key_seed = new byte[32];
260 for (byte i = 0; i < 32; i++) {
261 key_seed[i] = (byte) (i ^ seed);
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;
268 this.keys_interface = keys.as_KeysInterface();
269 this.explicit_keys_manager = keys;
271 this.router = NetGraphMsgHandler.of(NetworkGraph.of(new byte[32]), Option_AccessZ.some(Access.new_impl(new Access.AccessInterface() {
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.
277 return Result_TxOutAccessErrorZ.err(AccessError.LDKAccessError_UnknownTx);
281 this.custom_message_handler = CustomMessageHandler.new_impl(new CustomMessageHandler.CustomMessageHandlerInterface() {
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();
288 return Result_NoneLightningErrorZ.ok();
292 public TwoTuple_PublicKeyTypeZ[] get_and_clear_pending_msg() {
294 synchronized (custom_messages_to_send) {
295 bytes = custom_messages_to_send.toArray(new byte[0][0]);
296 custom_messages_to_send.clear();
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]; }
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; }
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;
323 try { this.nio_peer_handler = new NioPeerHandler(peer_manager); } catch (IOException e) { assert false; }
325 for (short i = 10_000; true; i++) {
327 nio_peer_handler.bind_listener(new InetSocketAddress("127.0.0.1", i));
330 } catch (IOException e) { assert i < 10_500; }
335 if (use_chan_manager_constructor) {
336 NetGraphMsgHandler route_handler = null;
337 if (!use_ignore_handler) {
338 route_handler = router;
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();
349 @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; }
351 this.chan_manager = constructor.channel_manager;
352 this.peer_manager = constructor.peer_manager;
353 must_free_objs.add(new WeakReference<>(this.chan_manager));
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);
361 this.node_id = chan_manager.get_our_node_id();
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();
373 Filter filter_nullable = null;
374 if (this.filter instanceof Option_FilterZ.Some) {
375 filter_nullable = ((Option_FilterZ.Some) this.filter).some;
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();
386 @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; }
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;
398 } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {
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();
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();
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;
428 this.node_id = chan_manager.get_our_node_id();
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;
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};
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);
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;
471 Event[] get_monitor_events(int expected_len) {
472 if (use_chan_manager_constructor) {
474 synchronized (this.pending_manager_events) {
475 if (expected_len != 0 && this.pending_manager_events.size() == expected_len) {
479 if (expected_len == 0) {
480 try { Thread.sleep(500); } catch (InterruptedException e) { assert false; }
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;
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]);
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;
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);
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; }
528 ArrayList<Event> l = new ArrayList<Event>();
529 while (l.size() < expected_len) {
531 if (use_nio_peer_handler) {
532 peer1.nio_peer_handler.check_events();
533 peer2.nio_peer_handler.check_events();
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
538 return l.toArray(new Event[0]);
540 assert res.length == expected_len;
545 static class DescriptorHolder { SocketDescriptor val; }
547 boolean running = false;
548 final LinkedList<Runnable> runqueue = new LinkedList();
550 Thread t = new Thread(() -> {
554 synchronized (runqueue) {
555 while (runqueue.isEmpty()) {
559 r = runqueue.pollFirst();
562 synchronized (runqueue) {
564 runqueue.notifyAll();
566 } catch (InterruptedException e) {
572 void maybe_exchange_peer_messages(Peer peer1, Peer peer2) {
573 if (!use_nio_peer_handler) {
574 synchronized (runqueue) {
578 peer1.peer_manager.process_events();
579 peer2.peer_manager.process_events();
580 synchronized (runqueue) {
581 if (runqueue.isEmpty() && !running) {
587 try { runqueue.wait(); } catch (InterruptedException e) { assert false; }
590 } else if (!use_chan_manager_constructor) {
591 peer1.nio_peer_handler.check_events();
592 peer2.nio_peer_handler.check_events();
595 void do_read_event(PeerManager pm, SocketDescriptor descriptor, byte[] data) {
596 if (!t.isAlive()) t.start();
597 synchronized (runqueue) {
600 Result_boolPeerHandleErrorZ res = pm.read_event(descriptor, data);
601 assert res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK;
603 runqueue.notifyAll();
605 must_free_objs.add(new WeakReference<>(data));
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) {
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) {
619 DescriptorHolder descriptor1 = new DescriptorHolder();
620 DescriptorHolder descriptor1ref = descriptor1;
621 SocketDescriptor descriptor2 = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
623 public long send_data(byte[] data, boolean resume_read) {
624 do_read_event(peer1.peer_manager, descriptor1ref.val, data);
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; }
633 descriptor1.val = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
635 public long send_data(byte[] data, boolean resume_read) {
636 do_read_event(peer2.peer_manager, descriptor2, data);
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; }
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;
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);
652 maybe_exchange_peer_messages(peer1, peer2);
656 TestState do_test_message_handler() throws InterruptedException {
657 Peer peer1 = new Peer((byte) 1);
658 Peer peer2 = new Peer((byte) 2);
660 connect_peers(peer1, peer2);
662 Result_NoneAPIErrorZ cc_res = peer1.chan_manager.create_channel(peer2.node_id, 100000, 1000, 42, null);
663 assert cc_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
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;
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;
677 NetworkParameters bitcoinj_net = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
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;
687 maybe_exchange_peer_messages(peer1, peer2);
688 synchronized (peer1.broadcast_set) {
689 while (peer1.broadcast_set.size() != 1) {
690 peer1.broadcast_set.wait();
694 assert peer1.broadcast_set.size() == 1;
695 assert Arrays.equals(peer1.broadcast_set.get(0), funding.bitcoinSerialize());
696 peer1.broadcast_set.clear();
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);
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);
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)
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());
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());
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();
744 Result_RouteLightningErrorZ route_res = UtilMethods.get_route(peer1.chan_manager.get_our_node_id(), peer1.router.get_network_graph(), peer2.node_id, invoice_features, peer1_chans, route_hints, 10000000, 42, peer1.logger);
745 assert route_res instanceof Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK;
746 Route route = ((Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK) route_res).res;
747 assert route.get_paths().length == 1;
748 assert route.get_paths()[0].length == 1;
749 assert route.get_paths()[0][0].get_fee_msat() == 10000000;
751 Result_NonePaymentSendFailureZ payment_res = peer1.chan_manager.send_payment(route, payment_hash, payment_secret);
752 assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_OK;
754 RouteHop[][] hops = new RouteHop[1][1];
755 byte[] hop_pubkey = new byte[33];
758 hops[0][0] = RouteHop.of(hop_pubkey, NodeFeatures.known(), 42, ChannelFeatures.known(), 100, 0);
759 Route r2 = Route.of(hops);
760 payment_res = peer1.chan_manager.send_payment(r2, payment_hash, payment_secret);
761 assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_Err;
764 if (use_chan_manager_constructor) {
765 peer1.constructor.interrupt();
766 peer2.constructor.interrupt();
767 } else if (use_nio_peer_handler) {
768 peer1.nio_peer_handler.interrupt();
769 peer2.nio_peer_handler.interrupt();
771 WeakReference<Peer> op1 = new WeakReference<Peer>(peer1);
772 peer1 = new Peer(peer1);
773 peer2 = new Peer(peer2);
774 return new TestState(op1, peer1, peer2, b.getHash());
776 return new TestState(null, peer1, peer2, b.getHash());
779 boolean cross_reload_ref_pollution = false;
781 private final WeakReference<Peer> ref_block;
782 private final Peer peer1;
783 private final Peer peer2;
784 public Sha256Hash best_blockhash;
786 public TestState(WeakReference<Peer> ref_block, Peer peer1, Peer peer2, Sha256Hash best_blockhash) {
787 this.ref_block = ref_block;
790 this.best_blockhash = best_blockhash;
793 void do_test_message_handler_b(TestState state) throws InterruptedException {
794 GcCheck obj = new GcCheck();
795 if (state.ref_block != null) {
796 // Ensure the original peers get freed before we move on. Note that we have to be in a different function
797 // scope to do so as the (at least current OpenJDK) JRE won't release anything created in the same scope.
798 while (!cross_reload_ref_pollution && state.ref_block.get() != null) {
800 System.runFinalization();
802 connect_peers(state.peer1, state.peer2);
805 Event[] events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
806 assert events[0] instanceof Event.PendingHTLCsForwardable;
807 state.peer2.chan_manager.process_pending_htlc_forwards();
809 events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
810 assert events[0] instanceof Event.PaymentReceived;
811 assert ((Event.PaymentReceived)events[0]).purpose instanceof PaymentPurpose.InvoicePayment;
812 byte[] payment_preimage = ((PaymentPurpose.InvoicePayment)((Event.PaymentReceived)events[0]).purpose).payment_preimage;
813 assert !Arrays.equals(payment_preimage, new byte[32]);
814 state.peer2.chan_manager.claim_funds(payment_preimage);
816 events = state.peer1.get_manager_events(1, state.peer1, state.peer2);
817 assert events[0] instanceof Event.PaymentSent;
818 assert Arrays.equals(((Event.PaymentSent) events[0]).payment_preimage, payment_preimage);
820 if (use_nio_peer_handler) {
821 // We receive PaymentSent immediately upon receipt of the payment preimage, but we expect to not have an
822 // HTLC transaction to broadcast below, which requires a bit more time to fully complete the
823 // commitment-transaction-update dance between both peers.
827 if (state.peer1.chain_monitor != null) {
828 Balance[] peer1_balances = state.peer1.chain_monitor.get_claimable_balances(state.peer1.chan_manager.list_channels());
829 assert peer1_balances.length == 0;
830 Balance[] peer2_balances = state.peer2.chain_monitor.get_claimable_balances(state.peer2.chan_manager.list_channels());
831 assert peer2_balances.length == 0;
834 ChannelDetails[] peer1_chans = state.peer1.chan_manager.list_channels();
837 Result_NoneAPIErrorZ close_res = state.peer1.chan_manager.close_channel(peer1_chans[0].get_channel_id());
838 assert close_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
839 maybe_exchange_peer_messages(state.peer1, state.peer2);
840 synchronized (state.peer1.broadcast_set) {
841 while (state.peer1.broadcast_set.size() != 1) state.peer1.broadcast_set.wait();
843 synchronized (state.peer2.broadcast_set) {
844 while (state.peer2.broadcast_set.size() != 1) state.peer2.broadcast_set.wait();
847 assert state.peer1.broadcast_set.size() == 1;
848 assert state.peer2.broadcast_set.size() == 1;
850 state.peer1.chan_manager.force_close_all_channels();
851 maybe_exchange_peer_messages(state.peer1, state.peer2);
852 synchronized (state.peer1.broadcast_set) {
853 while (state.peer1.broadcast_set.size() != 1) state.peer1.broadcast_set.wait();
855 synchronized (state.peer2.broadcast_set) {
856 while (state.peer2.broadcast_set.size() != 1) state.peer2.broadcast_set.wait();
859 assert state.peer1.broadcast_set.size() == 1;
860 assert state.peer2.broadcast_set.size() == 1;
863 events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
864 assert events[0] instanceof Event.ChannelClosed;
865 events = state.peer1.get_manager_events(1, state.peer1, state.peer2);
866 assert events[0] instanceof Event.ChannelClosed;
868 if (state.peer1.chain_monitor != null) {
869 Balance[] peer1_balances = state.peer1.chain_monitor.get_claimable_balances(state.peer1.chan_manager.list_channels());
870 assert peer1_balances.length == 1;
871 for (Balance bal : peer1_balances) {
872 assert bal instanceof Balance.ClaimableOnChannelClose;
873 long expected_tx_fee = 183;
874 assert ((Balance.ClaimableOnChannelClose) bal).claimable_amount_satoshis == 100000 - 1 - 10000 - expected_tx_fee;
876 Balance[] peer2_balances = state.peer2.chain_monitor.get_claimable_balances(state.peer2.chan_manager.list_channels());
877 assert peer2_balances.length == 1;
878 for (Balance bal : peer2_balances) {
879 assert bal instanceof Balance.ClaimableOnChannelClose;
880 assert ((Balance.ClaimableOnChannelClose) bal).claimable_amount_satoshis == 10000 + 1;
885 NetworkParameters bitcoinj_net = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
886 Transaction tx = new Transaction(bitcoinj_net, state.peer1.broadcast_set.getFirst());
887 Block b = new Block(bitcoinj_net, 2, state.best_blockhash, Sha256Hash.ZERO_HASH, 42, 0, 0,
888 Arrays.asList(new Transaction[]{tx}));
889 TwoTuple_TxidCVec_C2Tuple_u32TxOutZZZ[] watch_outputs = state.peer2.connect_block(b, 10, 1);
890 if (watch_outputs != null) { // We only process watch_outputs manually when we use a manually-build Watch impl
891 assert watch_outputs.length == 1;
892 assert Arrays.equals(watch_outputs[0].get_a(), tx.getTxId().getReversedBytes());
893 assert watch_outputs[0].get_b().length == 2;
894 assert watch_outputs[0].get_b()[0].get_a() == 0;
895 assert watch_outputs[0].get_b()[1].get_a() == 1;
898 for (int i = 11; i < 21; i++) {
899 b = new Block(bitcoinj_net, 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, new ArrayList<>());
900 state.peer2.connect_block(b, i, 0);
903 Event[] broadcastable_event = state.peer2.get_monitor_events(1);
904 for (ChannelMonitor mon : state.peer2.monitors.values()) {
905 // This used to be buggy and double-free, so go ahead and fetch them!
906 byte[][] txn = mon.get_latest_holder_commitment_txn(state.peer2.logger);
908 assert broadcastable_event.length == 1;
909 assert broadcastable_event[0] instanceof Event.SpendableOutputs;
910 if (state.peer2.explicit_keys_manager != null) {
911 TxOut[] additional_outputs = new TxOut[]{new TxOut(420, new byte[]{0x42})};
912 Result_TransactionNoneZ tx_res = state.peer2.explicit_keys_manager.spend_spendable_outputs(((Event.SpendableOutputs) broadcastable_event[0]).outputs, additional_outputs, new byte[]{0x00}, 253);
913 assert tx_res instanceof Result_TransactionNoneZ.Result_TransactionNoneZ_OK;
914 Transaction built_tx = new Transaction(bitcoinj_net, ((Result_TransactionNoneZ.Result_TransactionNoneZ_OK) tx_res).res);
915 assert built_tx.getOutputs().size() == 2;
916 assert Arrays.equals(built_tx.getOutput(1).getScriptBytes(), new byte[]{0x00});
917 assert Arrays.equals(built_tx.getOutput(0).getScriptBytes(), new byte[]{0x42});
918 assert built_tx.getOutput(0).getValue().value == 420;
922 // Test exchanging a custom message (note that ChannelManagerConstructor) always loads an IgnorimgMessageHandler
923 // so we cannot exchange custom messages with it
924 if (!use_chan_manager_constructor) {
925 byte[] custom_message_bytes = new byte[]{0x42, 0x44, 0x43, 0x00};
926 state.peer1.custom_messages_to_send.add(custom_message_bytes);
927 state.peer1.peer_manager.process_events();
928 synchronized (state.peer2.received_custom_messages) {
930 if (state.peer2.received_custom_messages.isEmpty()) {
931 state.peer2.received_custom_messages.wait();
934 assert state.peer2.received_custom_messages.size() == 1;
935 assert Arrays.equals(state.peer2.received_custom_messages.get(0), custom_message_bytes);
941 if (use_nio_peer_handler) {
942 state.peer1.peer_manager.disconnect_by_node_id(state.peer2.chan_manager.get_our_node_id(), false);
943 while (state.peer1.peer_manager.get_peer_node_ids().length != 0) Thread.yield();
944 while (state.peer2.peer_manager.get_peer_node_ids().length != 0) Thread.yield();
945 state.peer1.nio_peer_handler.interrupt();
946 state.peer2.nio_peer_handler.interrupt();
949 state.peer1.get_monitor_events(0);
950 state.peer2.get_monitor_events(0);
952 if (use_chan_manager_constructor) {
953 state.peer1.constructor.interrupt();
954 state.peer2.constructor.interrupt();
959 // Construct the only Option_Enum::Variant(OpaqueStruct) we have in the codebase as this used to cause double-frees:
960 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,};
961 Result_ChannelUpdateDecodeErrorZ upd_msg = ChannelUpdate.read(serd);
962 assert upd_msg instanceof Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK;
963 Option_NetworkUpdateZ upd = Option_NetworkUpdateZ.some(NetworkUpdate.channel_update_message(((Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK) upd_msg).res));
966 java.util.LinkedList<WeakReference<Object>> must_free_objs = new java.util.LinkedList();
968 int gc_exp_count = 0;
970 GcCheck() { gc_exp_count += 1; }
972 protected void finalize() throws Throwable {
978 public class HumanObjectPeerTest {
979 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 {
980 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);
981 HumanObjectPeerTestInstance.TestState state = instance.do_test_message_handler();
982 instance.do_test_message_handler_b(state);
985 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 {
986 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);
987 while (instance.gc_count != instance.gc_exp_count) {
989 System.runFinalization();
991 for (WeakReference<Object> o : instance.must_free_objs)
992 assert o.get() == null;
995 public void test_message_handler() throws InterruptedException {
996 for (int i = 0; i < (1 << 8) - 1; i++) {
997 boolean nice_close = (i & (1 << 0)) != 0;
998 boolean use_km_wrapper = (i & (1 << 1)) != 0;
999 boolean use_manual_watch = (i & (1 << 2)) != 0;
1000 boolean reload_peers = (i & (1 << 3)) != 0;
1001 boolean break_cross_refs = (i & (1 << 4)) != 0;
1002 boolean nio_peer_handler = (i & (1 << 5)) != 0;
1003 boolean use_ignoring_routing_handler = (i & (1 << 6)) != 0;
1004 boolean use_chan_manager_constructor = (i & (1 << 7)) != 0;
1005 if (break_cross_refs && !reload_peers) {
1006 // There are no cross refs to break without reloading peers.
1009 if (use_chan_manager_constructor && (use_manual_watch || !nio_peer_handler)) {
1010 // ChannelManagerConstructor requires a ChainMonitor as the Watch and creates a NioPeerHandler for us.
1013 if (!use_chan_manager_constructor && use_ignoring_routing_handler) {
1014 // We rely on the ChannelManagerConstructor to convert null into an IgnoringMessageHandler, so don't
1015 // try to run with an IgnoringMessageHandler unless we're also using a ChannelManagerConstructor.
1018 System.err.println("Running test with flags " + i);
1019 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);
1023 // This is used in the test jar to test the built jar is runnable
1024 public static void main(String[] args) {
1026 new HumanObjectPeerTest().test_message_handler();
1027 } catch (Exception e) {
1028 System.err.println("Caught exception:");
1029 System.err.println(e);