3 import org.bitcoinj.core.*;
4 import org.bitcoinj.script.Script;
5 import org.junit.jupiter.api.Test;
6 import org.ldk.batteries.ChannelManagerConstructor;
7 import org.ldk.batteries.NioPeerHandler;
8 import org.ldk.enums.*;
9 import org.ldk.enums.Currency;
10 import org.ldk.structs.*;
11 import org.ldk.util.UInt5;
13 import java.io.IOException;
14 import java.lang.ref.WeakReference;
15 import java.net.InetSocketAddress;
17 import java.util.function.IntConsumer;
19 class HumanObjectPeerTestInstance {
20 private final boolean nice_close;
21 private final boolean use_km_wrapper;
22 private final boolean use_manual_watch;
23 private final boolean reload_peers;
24 private final boolean break_cross_peer_refs;
25 private final boolean use_nio_peer_handler;
26 private final boolean use_filter;
27 private final boolean use_ignore_handler;
28 private final boolean use_chan_manager_constructor;
29 private final boolean use_invoice_payer;
30 TxOut gossip_txout = null;
32 HumanObjectPeerTestInstance(boolean nice_close, boolean use_km_wrapper, boolean use_manual_watch, boolean reload_peers, boolean break_cross_peer_refs, boolean use_nio_peer_handler, boolean use_filter, boolean use_ignore_handler, boolean use_chan_manager_constructor, boolean use_invoice_payer) {
33 this.nice_close = nice_close;
34 this.use_km_wrapper = use_km_wrapper;
35 this.use_manual_watch = use_manual_watch;
36 this.reload_peers = reload_peers;
37 this.break_cross_peer_refs = break_cross_peer_refs;
38 this.use_nio_peer_handler = use_nio_peer_handler;
39 this.use_filter = use_filter;
40 this.use_ignore_handler = use_ignore_handler;
41 this.use_chan_manager_constructor = use_chan_manager_constructor;
42 this.use_invoice_payer = use_invoice_payer;
46 KeysInterface manual_keysif(KeysInterface underlying_if) {
47 return KeysInterface.new_impl(new KeysInterface.KeysInterfaceInterface() {
48 @Override public Result_SecretKeyNoneZ get_node_secret(Recipient recipient) { return underlying_if.get_node_secret(recipient); }
49 @Override public byte[] get_destination_script() { return underlying_if.get_destination_script(); }
50 @Override public ShutdownScript get_shutdown_scriptpubkey() { return underlying_if.get_shutdown_scriptpubkey(); }
53 public Sign get_channel_signer(boolean inbound, long channel_value_satoshis) {
54 Sign underlying_ck = underlying_if.get_channel_signer(inbound, channel_value_satoshis);
55 BaseSign underlying_base = underlying_ck.get_base_sign();
56 BaseSign.BaseSignInterface bsi = new BaseSign.BaseSignInterface() {
57 @Override public byte[] get_per_commitment_point(long idx) {
58 return underlying_base.get_per_commitment_point(idx);
60 @Override public byte[] release_commitment_secret(long idx) {
61 return underlying_base.release_commitment_secret(idx);
63 @Override public Result_NoneNoneZ validate_holder_commitment(HolderCommitmentTransaction holder_tx, byte[][] preimages) {
64 return underlying_base.validate_holder_commitment(holder_tx, preimages);
66 @Override public byte[] channel_keys_id() {
69 @Override public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_counterparty_commitment(CommitmentTransaction commitment_tx, byte[][] preimages) {
70 return underlying_base.sign_counterparty_commitment(commitment_tx, preimages);
72 @Override public Result_NoneNoneZ validate_counterparty_revocation(long idx, byte[] secret) {
73 return underlying_base.validate_counterparty_revocation(idx, secret);
75 @Override public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_holder_commitment_and_htlcs(HolderCommitmentTransaction holder_commitment_tx) {
76 return underlying_base.sign_holder_commitment_and_htlcs(holder_commitment_tx);
78 @Override public Result_SignatureNoneZ sign_justice_revoked_output(byte[] justice_tx, long input, long amount, byte[] per_commitment_key) {
79 return underlying_base.sign_justice_revoked_output(justice_tx, input, amount, per_commitment_key);
81 @Override public Result_SignatureNoneZ sign_justice_revoked_htlc(byte[] justice_tx, long input, long amount, byte[] per_commitment_key, HTLCOutputInCommitment htlc) {
82 return underlying_base.sign_justice_revoked_htlc(justice_tx, input, amount, per_commitment_key, htlc);
84 @Override public Result_SignatureNoneZ sign_counterparty_htlc_transaction(byte[] htlc_tx, long input, long amount, byte[] per_commitment_point, HTLCOutputInCommitment htlc) {
85 return underlying_base.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc);
87 @Override public Result_SignatureNoneZ sign_closing_transaction(ClosingTransaction closing_tx) {
88 return underlying_base.sign_closing_transaction(closing_tx);
90 @Override public Result_C2Tuple_SignatureSignatureZNoneZ sign_channel_announcement(UnsignedChannelAnnouncement msg) {
91 return underlying_base.sign_channel_announcement(msg);
93 @Override public void ready_channel(ChannelTransactionParameters params) {
94 underlying_base.ready_channel(params);
97 Sign.SignInterface si = new Sign.SignInterface() {
99 public byte[] write() {
100 return underlying_ck.write();
103 Sign resp = Sign.new_impl(si, bsi, underlying_base.get_pubkeys());
104 must_free_objs.add(new WeakReference<>(si));
105 must_free_objs.add(new WeakReference<>(bsi));
106 must_free_objs.add(new WeakReference<>(resp));
107 must_free_objs.add(new WeakReference<>(underlying_base));
108 must_free_objs.add(new WeakReference<>(underlying_ck));
113 public byte[] get_secure_random_bytes() {
114 return underlying_if.get_secure_random_bytes();
118 public Result_SignDecodeErrorZ read_chan_signer(byte[] reader) {
119 return underlying_if.read_chan_signer(reader);
123 public Result_RecoverableSignatureNoneZ sign_invoice(byte[] hrp_bytes, UInt5[] invoice_data, Recipient receipient) {
124 return underlying_if.sign_invoice(hrp_bytes, invoice_data, receipient);
128 public byte[] get_inbound_payment_key_material() {
129 return underlying_if.get_inbound_payment_key_material();
134 Watch get_manual_watch() {
135 Watch.WatchInterface watch_impl = new Watch.WatchInterface() {
136 public Result_NoneChannelMonitorUpdateErrZ watch_channel(OutPoint funding_txo, ChannelMonitor monitor) {
137 synchronized (monitors) {
138 assert monitors.put(Arrays.toString(funding_txo.get_txid()), monitor) == null;
140 return Result_NoneChannelMonitorUpdateErrZ.ok();
143 public Result_NoneChannelMonitorUpdateErrZ update_channel(OutPoint funding_txo, ChannelMonitorUpdate update) {
144 synchronized (monitors) {
145 String txid = Arrays.toString(funding_txo.get_txid());
146 assert monitors.containsKey(txid);
147 Result_NoneNoneZ update_res = monitors.get(txid).update_monitor(update, tx_broadcaster, fee_estimator, logger);
148 assert update_res instanceof Result_NoneNoneZ.Result_NoneNoneZ_OK;
150 return Result_NoneChannelMonitorUpdateErrZ.ok();
154 public ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[] release_pending_monitor_events() {
155 synchronized (monitors) {
156 assert monitors.size() <= 1;
157 for (ChannelMonitor mon : monitors.values()) {
158 ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[] res = new ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[1];
159 res[0] = ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ.of(mon.get_funding_txo().get_a(), mon.get_and_clear_pending_monitor_events(), mon.get_counterparty_node_id());
163 return new ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[0];
166 Watch watch = Watch.new_impl(watch_impl);
167 must_free_objs.add(new WeakReference<>(watch_impl));
168 must_free_objs.add(new WeakReference<>(watch));
172 UserConfig get_config() {
173 ChannelHandshakeConfig channel_config = ChannelHandshakeConfig.with_default();
174 channel_config.set_announced_channel(true);
175 UserConfig config = UserConfig.with_default();
176 config.set_channel_handshake_config(channel_config);
180 NioPeerHandler nio_peer_handler;
184 final FeeEstimator fee_estimator;
185 final BroadcasterInterface tx_broadcaster;
186 final KeysManager explicit_keys_manager;
187 final KeysInterface keys_interface;
188 final ChainMonitor chain_monitor;
190 P2PGossipSync route_handler;
191 final Watch chain_watch;
192 final HashSet<String> filter_additions;
193 Option_FilterZ filter;
194 ChannelManager chan_manager;
195 PeerManager peer_manager;
196 final HashMap<String, ChannelMonitor> monitors; // Wow I forgot just how terrible Java is - we can't put a byte array here.
198 byte[] connected_peer_node_id = null;
199 final LinkedList<byte[]> broadcast_set = new LinkedList<>();
200 final LinkedList<Event> pending_manager_events = new LinkedList<>();
201 private final CustomMessageHandler custom_message_handler;
202 final LinkedList<byte[]> received_custom_messages = new LinkedList<>();
203 final LinkedList<byte[]> custom_messages_to_send = new LinkedList<>();
204 ChannelManagerConstructor constructor = null;
205 InvoicePayer payer = null;
206 GcCheck obj = new GcCheck();
208 private ChannelMonitor test_mon_roundtrip(OutPoint expected_id, byte[] data) {
209 // Because get_funding_txo() returns an OutPoint in a tuple that is a reference to an OutPoint inside the
210 // ChannelMonitor, its a good test to ensure that the OutPoint isn't freed (or is cloned) before the
211 // ChannelMonitor is. This used to be broken.
212 Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_monitor = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(data, keys_interface);
213 assert roundtrip_monitor instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
214 TwoTuple_OutPointScriptZ funding_txo = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_monitor).res.get_b().get_funding_txo();
215 System.gc(); System.runFinalization(); // Give the GC a chance to run.
216 assert Arrays.equals(funding_txo.get_a().get_txid(), expected_id.get_txid());
217 assert funding_txo.get_a().get_index() == expected_id.get_index();
218 Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_two = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(data, keys_interface);
219 assert roundtrip_two instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
220 return ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_two).res.get_b();
223 private Peer(Object _dummy, byte seed) {
224 logger = Logger.new_impl((org.ldk.structs.Record arg)->{
225 if (arg.get_level() == Level.LDKLevel_Error)
226 System.err.println(seed + ": " + arg.get_module_path() + " - " + arg.get_args());
228 System.out.println(seed + ": " + arg.get_module_path() + " - " + arg.get_args());
230 fee_estimator = FeeEstimator.new_impl((confirmation_target -> 253));
231 tx_broadcaster = BroadcasterInterface.new_impl(tx -> {
232 synchronized (broadcast_set) {
233 broadcast_set.add(tx);
234 broadcast_set.notifyAll();
237 monitors = new HashMap<>();
239 Persist persister = Persist.new_impl(new Persist.PersistInterface() {
241 public Result_NoneChannelMonitorUpdateErrZ persist_new_channel(OutPoint id, ChannelMonitor data, MonitorUpdateId update_id) {
242 synchronized (monitors) {
243 String key = Arrays.toString(id.to_channel_id());
244 ChannelMonitor res = test_mon_roundtrip(id, data.write());
245 assert monitors.put(key, res) == null;
247 return Result_NoneChannelMonitorUpdateErrZ.ok();
251 public Result_NoneChannelMonitorUpdateErrZ update_persisted_channel(OutPoint id, ChannelMonitorUpdate update, ChannelMonitor data, MonitorUpdateId update_id) {
252 synchronized (monitors) {
253 String key = Arrays.toString(id.to_channel_id());
254 ChannelMonitor res = test_mon_roundtrip(id, data.write());
255 // Note that we use a serialization-roundtrip copy of data here, not the original, as this can
256 // expose the JVM JIT bug where it finalize()s things still being called.
257 assert monitors.put(key, res) != null;
259 return Result_NoneChannelMonitorUpdateErrZ.ok();
263 filter_additions = new HashSet<>();
265 this.filter = Option_FilterZ.some(Filter.new_impl(new Filter.FilterInterface() {
266 @Override public void register_tx(byte[] txid, byte[] script_pubkey) {
267 filter_additions.add(Arrays.toString(txid));
269 @Override public Option_C2Tuple_usizeTransactionZZ register_output(WatchedOutput output) {
270 filter_additions.add(Arrays.toString(output.get_outpoint().get_txid()) + ":" + output.get_outpoint().get_index());
271 return Option_C2Tuple_usizeTransactionZZ.none();
275 this.filter = Option_FilterZ.none();
278 if (use_manual_watch) {
279 chain_watch = get_manual_watch();
280 chain_monitor = null;
282 chain_monitor = ChainMonitor.of(filter, tx_broadcaster, logger, fee_estimator, persister);
283 chain_watch = chain_monitor.as_Watch();
286 byte[] key_seed = new byte[32];
287 for (byte i = 0; i < 32; i++) {
288 key_seed[i] = (byte) (i ^ seed);
290 KeysManager keys = KeysManager.of(key_seed, System.currentTimeMillis() / 1000, (int) (System.currentTimeMillis() * 1000));
291 if (use_km_wrapper) {
292 this.keys_interface = manual_keysif(keys.as_KeysInterface());
293 this.explicit_keys_manager = null;
295 this.keys_interface = keys.as_KeysInterface();
296 this.explicit_keys_manager = keys;
299 this.custom_message_handler = CustomMessageHandler.new_impl(new CustomMessageHandler.CustomMessageHandlerInterface() {
301 public Result_NoneLightningErrorZ handle_custom_message(Type msg, byte[] sender_node_id) {
302 synchronized (received_custom_messages) {
303 received_custom_messages.add(msg.write());
304 received_custom_messages.notifyAll();
306 return Result_NoneLightningErrorZ.ok();
310 public TwoTuple_PublicKeyTypeZ[] get_and_clear_pending_msg() {
312 synchronized (custom_messages_to_send) {
313 bytes = custom_messages_to_send.toArray(new byte[0][0]);
314 custom_messages_to_send.clear();
316 TwoTuple_PublicKeyTypeZ[] ret = new TwoTuple_PublicKeyTypeZ[bytes.length];
317 for (int i = 0; i < bytes.length; i++) {
318 final int msg_idx = i;
319 ret[i] = TwoTuple_PublicKeyTypeZ.of(connected_peer_node_id, Type.new_impl(new Type.TypeInterface() {
320 @Override public short type_id() { return 4096; }
321 @Override public String debug_str() { return "Custom Java Message"; }
322 @Override public byte[] write() { return bytes[msg_idx]; }
327 }, (message_type, buffer) -> {
328 assert message_type == 4096;
329 return Result_COption_TypeZDecodeErrorZ.ok(Option_TypeZ.some(Type.new_impl(new Type.TypeInterface() {
330 @Override public short type_id() { return 4096; }
331 @Override public String debug_str() { return "Custom Java-Decoded Message"; }
332 @Override public byte[] write() { return buffer; }
336 private void bind_nio() {
337 if (!use_nio_peer_handler) return;
338 if (use_chan_manager_constructor) {
339 this.nio_peer_handler = this.constructor.nio_peer_handler;
341 try { this.nio_peer_handler = new NioPeerHandler(peer_manager); } catch (IOException e) { assert false; }
343 for (short i = 10_000; true; i++) {
345 nio_peer_handler.bind_listener(new InetSocketAddress("127.0.0.1", i));
348 } catch (IOException e) { assert i < 10_500; }
351 private void setup_route_handler() {
352 this.route_handler = P2PGossipSync.of(this.router,
353 Option_AccessZ.some(Access.new_impl((genesis_hash, short_channel_id) -> Result_TxOutAccessErrorZ.ok(gossip_txout))), this.logger);
357 this.router = NetworkGraph.of(new byte[32], this.logger);
358 this.setup_route_handler();
360 if (use_chan_manager_constructor) {
361 if (use_ignore_handler) {
362 this.constructor = new ChannelManagerConstructor(Network.LDKNetwork_Bitcoin, get_config(), new byte[32], 0,
363 this.keys_interface, this.fee_estimator, this.chain_monitor, null, this.tx_broadcaster, this.logger);
365 this.constructor = new ChannelManagerConstructor(Network.LDKNetwork_Bitcoin, get_config(), new byte[32], 0,
366 this.keys_interface, this.fee_estimator, this.chain_monitor, this.router, this.tx_broadcaster, this.logger);
368 ProbabilisticScoringParameters params = ProbabilisticScoringParameters.with_default();
369 ProbabilisticScorer default_scorer = ProbabilisticScorer.of(params, this.router, this.logger);
370 Result_ProbabilisticScorerDecodeErrorZ score_res = ProbabilisticScorer.read(default_scorer.write(), params, this.router, this.logger);
371 assert score_res.is_ok();
372 Score score = ((Result_ProbabilisticScorerDecodeErrorZ.Result_ProbabilisticScorerDecodeErrorZ_OK) score_res).res.as_Score();
373 MultiThreadedLockableScore scorer = null;
374 if (use_invoice_payer) { scorer = MultiThreadedLockableScore.of(score); }
375 constructor.chain_sync_completed(new ChannelManagerConstructor.EventHandler() {
376 @Override public void handle_event(Event event) {
377 synchronized (pending_manager_events) {
378 pending_manager_events.add(event);
379 pending_manager_events.notifyAll();
382 @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; }
383 @Override public void persist_network_graph(byte[] graph_bytes) { assert graph_bytes.length > 1; }
384 @Override public void persist_scorer(byte[] scorer_bytes) { assert scorer_bytes.length > 1; }
386 this.chan_manager = constructor.channel_manager;
387 this.peer_manager = constructor.peer_manager;
388 this.payer = constructor.payer;
389 must_free_objs.add(new WeakReference<>(this.chan_manager));
391 ChainParameters params = ChainParameters.of(Network.LDKNetwork_Bitcoin, BestBlock.of(new byte[32], 0));
392 this.chan_manager = ChannelManager.of(this.fee_estimator, chain_watch, tx_broadcaster, logger, this.keys_interface, get_config(), params);
393 byte[] random_data = keys_interface.get_secure_random_bytes();
394 Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
395 assert node_secret.is_ok();
396 this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), route_handler.as_RoutingMessageHandler(),
397 ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res, random_data, logger, this.custom_message_handler);
398 if (use_invoice_payer) {
399 this.payer = InvoicePayer.of(this.chan_manager.as_Payer(), Router.new_impl(new Router.RouterInterface() {
401 public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters params, byte[] payment_hash, ChannelDetails[] first_hops, Score scorer) {
402 return UtilMethods.find_route(payer, params, router, first_hops, logger, scorer, new byte[32]);
404 }), MultiThreadedLockableScore.of(Score.new_impl(new Score.ScoreInterface() {
405 @Override public void payment_path_failed(RouteHop[] path, long scid) {}
406 @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage) { return 0; }
407 @Override public void payment_path_successful(RouteHop[] path) {}
408 @Override public void probe_failed(RouteHop[] path, long short_channel_id) { assert false; }
409 @Override public void probe_successful(RouteHop[] path) { assert false; }
410 @Override public byte[] write() { assert false; return null; }
411 })), logger, EventHandler.new_impl(new EventHandler.EventHandlerInterface() {
412 @Override public void handle_event(Event event) {
413 synchronized (pending_manager_events) {
414 pending_manager_events.add(event);
415 pending_manager_events.notifyAll();
418 }), Retry.attempts(0));
422 this.node_id = chan_manager.get_our_node_id();
430 this(null, orig.seed);
431 if (use_chan_manager_constructor) {
432 byte[][] monitors = {orig.monitors.values().stream().iterator().next().write()};
433 byte[] serialized = orig.chan_manager.write();
434 byte[] serialized_router = orig.router.write();
436 Filter filter_nullable = null;
437 if (this.filter instanceof Option_FilterZ.Some) {
438 filter_nullable = ((Option_FilterZ.Some) this.filter).some;
440 if (use_ignore_handler) {
441 this.constructor = new ChannelManagerConstructor(serialized, monitors, get_config(),
442 this.keys_interface, this.fee_estimator, this.chain_monitor, filter_nullable,
443 null, this.tx_broadcaster, this.logger);
445 this.constructor = new ChannelManagerConstructor(serialized, monitors, get_config(),
446 this.keys_interface, this.fee_estimator, this.chain_monitor, filter_nullable,
447 serialized_router, this.tx_broadcaster, this.logger);
449 // Test that ChannelManagerConstructor correctly rejects duplicate ChannelMonitors
450 byte[][] monitors_dupd = new byte[2][];
451 monitors_dupd[0] = monitors[0];
452 monitors_dupd[1] = monitors[0];
453 ChannelManagerConstructor constr = this.constructor = new ChannelManagerConstructor(serialized, monitors_dupd, get_config(),
454 this.keys_interface, this.fee_estimator, this.chain_monitor, filter_nullable,
455 null, this.tx_broadcaster, this.logger);
457 } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {}
459 this.router = this.constructor.net_graph;
460 setup_route_handler();
461 MultiThreadedLockableScore scorer = null;
462 if (use_invoice_payer) { scorer = MultiThreadedLockableScore.of(ProbabilisticScorer.of(ProbabilisticScoringParameters.with_default(), this.router, this.logger).as_Score()); }
463 constructor.chain_sync_completed(new ChannelManagerConstructor.EventHandler() {
464 @Override public void handle_event(Event event) {
465 synchronized (pending_manager_events) {
466 pending_manager_events.add(event);
467 pending_manager_events.notifyAll();
470 @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; }
471 @Override public void persist_network_graph(byte[] graph_bytes) { assert graph_bytes.length > 1; }
472 @Override public void persist_scorer(byte[] scorer_bytes) { assert scorer_bytes.length > 1; }
474 this.chan_manager = constructor.channel_manager;
475 this.payer = constructor.payer;
476 this.peer_manager = constructor.peer_manager;
477 must_free_objs.add(new WeakReference<>(this.chan_manager));
478 // If we are using a ChannelManagerConstructor, we may have pending events waiting on the old peer
479 // which have been removed from the ChannelManager but which we still need to handle.
480 this.pending_manager_events.addAll(orig.pending_manager_events);
481 if (!this.pending_manager_events.isEmpty()) {
482 // However, this implies cross_reload_ref_pollution
483 cross_reload_ref_pollution = true;
485 } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {
489 this.router = NetworkGraph.of(new byte[32], this.logger);
490 this.setup_route_handler();
491 ChannelMonitor[] monitors = new ChannelMonitor[1];
492 assert orig.monitors.size() == 1;
493 if (!break_cross_peer_refs) {
494 monitors[0] = orig.monitors.values().stream().iterator().next();
496 byte[] serialized = orig.monitors.values().stream().iterator().next().write();
497 Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res =
498 UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(serialized, this.keys_interface);
499 assert res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK;
500 monitors[0] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
502 byte[] serialized = orig.chan_manager.write();
503 Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ read_res =
504 UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(serialized, this.keys_interface, this.fee_estimator, this.chain_watch, this.tx_broadcaster, this.logger, get_config(), monitors);
505 assert read_res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK;
506 this.chan_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK) read_res).res.get_b();
507 this.chain_watch.watch_channel(monitors[0].get_funding_txo().get_a(), monitors[0]);
508 byte[] random_data = keys_interface.get_secure_random_bytes();
509 Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node);
510 assert node_secret.is_ok();
511 this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), route_handler.as_RoutingMessageHandler(),
512 ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res,
513 random_data, logger, this.custom_message_handler);
514 if (!break_cross_peer_refs && (use_manual_watch || use_km_wrapper)) {
515 // When we pass monitors[0] into chain_watch.watch_channel we create a reference from the new Peer to a
516 // field in the old peer, preventing freeing of the original Peer until the new Peer is freed. Thus, we
517 // shouldn't bother waiting for the original to be freed later on.
518 cross_reload_ref_pollution = true;
520 if (use_invoice_payer) {
521 this.payer = InvoicePayer.of(this.chan_manager.as_Payer(), Router.new_impl(new Router.RouterInterface() {
523 public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters params, byte[] _payment_hash, ChannelDetails[] first_hops, Score scorer) {
524 return UtilMethods.find_route(payer, params, router, first_hops, logger, scorer, new byte[32]);
526 }), MultiThreadedLockableScore.of(Score.new_impl(new Score.ScoreInterface() {
527 @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage) { return 0; }
528 @Override public void payment_path_failed(RouteHop[] path, long scid) {}
529 @Override public void payment_path_successful(RouteHop[] path) {}
530 @Override public void probe_failed(RouteHop[] path, long short_channel_id) { assert false; }
531 @Override public void probe_successful(RouteHop[] path) { assert false; }
532 @Override public byte[] write() { assert false; return null; }
533 })), logger, EventHandler.new_impl(new EventHandler.EventHandlerInterface() {
534 @Override public void handle_event(Event event) {
535 synchronized (pending_manager_events) {
536 pending_manager_events.add(event);
537 pending_manager_events.notifyAll();
540 }), Retry.attempts(0));
543 this.node_id = chan_manager.get_our_node_id();
546 if (cross_reload_ref_pollution) {
547 // This really, really needs to be handled at the bindings layer, but its rather complicated -
548 // ChannelSigners can be cloned and passed around without java being involved, resulting in them being
549 // owned by both one or more ChannelMonitors and a ChannelManager, with only one having proper pointers
550 // to the ChannelSigner. Ideally, the ChannelSigner would have a global reference to the Java
551 // implementation class, but that results in circular references. Instead, we need some ability to,
552 // while cloning ChannelSigners, add new references in the calling Java struct (ie ChannelMonitor) to
553 // the ChannelSigner.
554 this.ptr_to = orig.chan_manager;
559 TwoTuple_TxidCVec_C2Tuple_u32TxOutZZZ[] connect_block(Block b, int height, long expected_monitor_update_len) {
560 byte[] header = Arrays.copyOfRange(b.bitcoinSerialize(), 0, 80);
561 TwoTuple_usizeTransactionZ[] txn;
562 if (b.hasTransactions()) {
563 assert b.getTransactions().size() == 1;
564 TwoTuple_usizeTransactionZ txp = TwoTuple_usizeTransactionZ.of((long) 0, b.getTransactions().get(0).bitcoinSerialize());
565 txn = new TwoTuple_usizeTransactionZ[]{txp};
567 txn = new TwoTuple_usizeTransactionZ[0];
568 if (chain_monitor != null) {
569 chan_manager.as_Listen().block_connected(b.bitcoinSerialize(), height);
570 chain_monitor.as_Listen().block_connected(b.bitcoinSerialize(), height);
572 chan_manager.as_Confirm().transactions_confirmed(header, txn, height);
573 chan_manager.as_Confirm().best_block_updated(header, height);
574 // Connect manually if we aren't using a ChainMonitor and are implementing Watch ourselves
575 synchronized (monitors) {
576 assert monitors.size() == 1;
577 for (ChannelMonitor mon : monitors.values()) {
578 TwoTuple_TxidCVec_C2Tuple_u32TxOutZZZ[] ret = mon.block_connected(header, txn, height, tx_broadcaster, fee_estimator, logger);
579 assert ret.length == expected_monitor_update_len;
587 Event[] get_monitor_events(int expected_len) {
588 if (use_chan_manager_constructor) {
590 synchronized (this.pending_manager_events) {
591 if (expected_len != 0 && this.pending_manager_events.size() == expected_len) {
595 if (expected_len == 0) {
596 try { Thread.sleep(500); } catch (InterruptedException e) { assert false; }
602 synchronized (this.pending_manager_events) {
603 Event[] res = this.pending_manager_events.toArray(new Event[0]);
604 this.pending_manager_events.clear();
605 assert res.length == expected_len;
608 } else if (chain_monitor != null) {
609 ArrayList<Event> l = new ArrayList<Event>();
610 chain_monitor.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
611 assert l.size() == expected_len;
612 return l.toArray(new Event[0]);
614 synchronized (monitors) {
615 assert monitors.size() == 1;
616 for (ChannelMonitor mon : monitors.values()) {
617 Event[] res = mon.get_and_clear_pending_events();
618 assert res.length == expected_len;
626 Event[] get_manager_events(int expected_len, Peer peer1, Peer peer2) {
627 assert expected_len != 0;
628 if (!use_nio_peer_handler) {
629 maybe_exchange_peer_messages(peer1, peer2);
631 Event[] res = new Event[0];
632 if (use_chan_manager_constructor) {
633 while (res.length < expected_len) {
634 synchronized (this.pending_manager_events) {
635 if (this.pending_manager_events.size() >= expected_len) {
636 res = this.pending_manager_events.toArray(res);
637 assert res.length == expected_len;
638 this.pending_manager_events.clear();
640 if (res.length < expected_len) {
641 try { this.pending_manager_events.wait(); } catch (InterruptedException e) { assert false; }
646 ArrayList<Event> l = new ArrayList<Event>();
647 while (l.size() < expected_len) {
649 if (use_nio_peer_handler) {
650 peer1.nio_peer_handler.check_events();
651 peer2.nio_peer_handler.check_events();
653 chan_manager.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
655 return l.toArray(new Event[0]);
657 assert res.length == expected_len;
662 static class DescriptorHolder { SocketDescriptor val; }
664 boolean running = false;
665 final LinkedList<Runnable> runqueue = new LinkedList();
667 Thread t = new Thread(() -> {
671 synchronized (runqueue) {
672 while (runqueue.isEmpty()) {
676 r = runqueue.pollFirst();
679 synchronized (runqueue) {
681 runqueue.notifyAll();
683 } catch (InterruptedException e) {
689 void maybe_exchange_peer_messages(Peer peer1, Peer peer2) {
690 if (!use_nio_peer_handler) {
692 peer1.peer_manager.process_events();
693 peer2.peer_manager.process_events();
694 synchronized (runqueue) {
695 if (runqueue.isEmpty() && !running) {
701 try { runqueue.wait(); } catch (InterruptedException e) { assert false; }
704 } else if (!use_chan_manager_constructor) {
705 peer1.nio_peer_handler.check_events();
706 peer2.nio_peer_handler.check_events();
709 void do_read_event(PeerManager pm, SocketDescriptor descriptor, byte[] data) {
710 if (!t.isAlive()) t.start();
711 synchronized (runqueue) {
714 Result_boolPeerHandleErrorZ res = pm.read_event(descriptor, data);
715 assert res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK;
717 runqueue.notifyAll();
719 must_free_objs.add(new WeakReference<>(data));
722 void connect_peers(final Peer peer1, final Peer peer2) {
723 peer2.connected_peer_node_id = peer1.node_id;
724 peer1.connected_peer_node_id = peer2.node_id;
725 if (use_nio_peer_handler) {
727 peer1.nio_peer_handler.connect(peer2.chan_manager.get_our_node_id(), new InetSocketAddress("127.0.0.1", peer2.nio_port), 100);
728 } catch (IOException e) { assert false; }
729 while (peer1.peer_manager.get_peer_node_ids().length == 0 || peer2.peer_manager.get_peer_node_ids().length == 0) {
733 DescriptorHolder descriptor1 = new DescriptorHolder();
734 DescriptorHolder descriptor1ref = descriptor1;
735 SocketDescriptor descriptor2 = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
737 public long send_data(byte[] data, boolean resume_read) {
738 do_read_event(peer1.peer_manager, descriptor1ref.val, data);
742 @Override public void disconnect_socket() { assert false; }
743 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == 2; }
744 @Override public long hash() { return 2; }
747 descriptor1.val = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
749 public long send_data(byte[] data, boolean resume_read) {
750 do_read_event(peer2.peer_manager, descriptor2, data);
754 @Override public void disconnect_socket() { assert false; }
755 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == 1; }
756 @Override public long hash() { return 1; }
759 Result_CVec_u8ZPeerHandleErrorZ conn_res = peer1.peer_manager.new_outbound_connection(peer2.node_id, descriptor1.val, Option_NetAddressZ.none());
760 assert conn_res instanceof Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK;
762 Result_NonePeerHandleErrorZ inbound_conn_res = peer2.peer_manager.new_inbound_connection(descriptor2, Option_NetAddressZ.none());
763 assert inbound_conn_res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_OK;
764 do_read_event(peer2.peer_manager, descriptor2, ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) conn_res).res);
766 maybe_exchange_peer_messages(peer1, peer2);
770 TestState do_test_message_handler() throws InterruptedException {
771 Peer peer1 = new Peer((byte) 1);
772 Peer peer2 = new Peer((byte) 2);
774 connect_peers(peer1, peer2);
776 Result__u832APIErrorZ cc_res = peer1.chan_manager.create_channel(peer2.node_id, 100000, 1000, 42, null);
777 assert cc_res instanceof Result__u832APIErrorZ.Result__u832APIErrorZ_OK;
779 // Previously, this was a SEGFAULT instead of get_funding_txo() returning null.
780 ChannelDetails pre_funding_chan = peer1.chan_manager.list_channels()[0];
781 assert pre_funding_chan.get_funding_txo() == null;
783 Event[] events = peer1.get_manager_events(1, peer1, peer2);
784 assert events[0] instanceof Event.FundingGenerationReady;
785 assert ((Event.FundingGenerationReady) events[0]).channel_value_satoshis == 100000;
786 assert ((Event.FundingGenerationReady) events[0]).user_channel_id == 42;
787 byte[] funding_spk = ((Event.FundingGenerationReady) events[0]).output_script;
788 assert funding_spk.length == 34 && funding_spk[0] == 0 && funding_spk[1] == 32; // P2WSH
789 byte[] chan_id = ((Event.FundingGenerationReady) events[0]).temporary_channel_id;
791 NetworkParameters bitcoinj_net = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
793 Transaction funding = new Transaction(bitcoinj_net);
794 funding.addInput(new TransactionInput(bitcoinj_net, funding, new byte[0]));
795 funding.getInputs().get(0).setWitness(new TransactionWitness(2)); // Make sure we don't complain about lack of witness
796 funding.getInput(0).getWitness().setPush(0, new byte[]{0x1});
797 funding.addOutput(Coin.SATOSHI.multiply(100000), new Script(funding_spk));
798 Result_NoneAPIErrorZ funding_res = peer1.chan_manager.funding_transaction_generated(chan_id, peer2.node_id, funding.bitcoinSerialize());
799 assert funding_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
801 gossip_txout = new TxOut(100000, funding_spk);
803 maybe_exchange_peer_messages(peer1, peer2);
804 synchronized (peer1.broadcast_set) {
805 while (peer1.broadcast_set.size() != 1) {
806 peer1.broadcast_set.wait();
810 assert peer1.broadcast_set.size() == 1;
811 assert Arrays.equals(peer1.broadcast_set.get(0), funding.bitcoinSerialize());
812 peer1.broadcast_set.clear();
814 Block b = new Block(bitcoinj_net, 2, Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[]{funding}));
815 peer1.connect_block(b, 1, 0);
816 peer2.connect_block(b, 1, 0);
818 for (int height = 2; height < 10; height++) {
819 b = new Block(bitcoinj_net, 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[0]));
820 peer1.connect_block(b, height, 0);
821 peer2.connect_block(b, height, 0);
824 maybe_exchange_peer_messages(peer1, peer2);
825 while (peer1.chan_manager.list_usable_channels().length != 1 || peer2.chan_manager.list_usable_channels().length != 1)
827 peer1.chan_manager.list_channels();
828 ChannelDetails[] peer1_chans = peer1.chan_manager.list_usable_channels();
829 ChannelDetails[] peer2_chans = peer2.chan_manager.list_usable_channels();
830 assert peer1_chans.length == 1;
831 assert peer2_chans.length == 1;
832 assert peer1_chans[0].get_channel_value_satoshis() == 100000;
833 assert peer1_chans[0].get_is_usable();
834 Option_u64Z short_chan_id = peer1_chans[0].get_short_channel_id();
835 assert short_chan_id instanceof Option_u64Z.Some;
836 assert ((Option_u64Z.Some)short_chan_id).some == (1L << 40); // 0th output in the 0th transaction in the 1st block
837 assert Arrays.equals(peer1_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
838 assert Arrays.equals(peer2_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
840 Result_InvoiceSignOrCreationErrorZ invoice = UtilMethods.create_invoice_from_channelmanager(peer2.chan_manager, peer2.keys_interface, Currency.LDKCurrency_Bitcoin, Option_u64Z.some(10000000), "Invoice Description", 7200);
841 assert invoice instanceof Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK;
842 System.out.println("Got invoice: " + ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
844 Result_InvoiceParseOrSemanticErrorZ parsed_invoice = Invoice.from_str(((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
845 assert parsed_invoice instanceof Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK;
846 assert Arrays.equals(((Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res.payment_hash(), ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_hash());
847 SignedRawInvoice signed_raw = ((Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res.into_signed_raw();
848 RawInvoice raw_invoice = signed_raw.raw_invoice();
849 byte[] desc_hash = raw_invoice.hash();
850 Description raw_invoice_description = raw_invoice.description();
851 String description_string = raw_invoice_description.into_inner();
852 assert description_string.equals("Invoice Description");
854 if (!use_invoice_payer) {
855 byte[] payment_hash = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_hash();
856 byte[] payment_secret = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_secret();
857 byte[] dest_node_id = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.recover_payee_pub_key();
858 assert Arrays.equals(dest_node_id, peer2.node_id);
859 InvoiceFeatures invoice_features = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.features();
860 RouteHint[] route_hints = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.route_hints();
862 PaymentParameters payee = PaymentParameters.of(peer2.node_id, invoice_features, route_hints, Option_u64Z.none(), 6*24*14, (byte)1, (byte)2, new long[0]);
863 RouteParameters route_params = RouteParameters.of(payee, 10000000, 42);
864 Result_RouteLightningErrorZ route_res = UtilMethods.find_route(
865 peer1.chan_manager.get_our_node_id(), route_params, peer1.router,
866 peer1_chans, peer1.logger, ProbabilisticScorer.of(ProbabilisticScoringParameters.with_default(), peer1.router, peer1.logger).as_Score(), new byte[32]);
867 assert route_res instanceof Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK;
868 Route route = ((Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK) route_res).res;
869 assert route.get_paths().length == 1;
870 assert route.get_paths()[0].length == 1;
871 assert route.get_paths()[0][0].get_fee_msat() == 10000000;
873 Result_PaymentIdPaymentSendFailureZ payment_res = peer1.chan_manager.send_payment(route, payment_hash, payment_secret);
874 assert payment_res instanceof Result_PaymentIdPaymentSendFailureZ.Result_PaymentIdPaymentSendFailureZ_OK;
876 RouteHop[][] hops = new RouteHop[1][1];
877 byte[] hop_pubkey = new byte[33];
880 hops[0][0] = RouteHop.of(hop_pubkey, NodeFeatures.known(), 42, ChannelFeatures.known(), 100, 0);
881 Route r2 = Route.of(hops, payee);
882 payment_res = peer1.chan_manager.send_payment(r2, payment_hash, payment_secret);
883 assert payment_res instanceof Result_PaymentIdPaymentSendFailureZ.Result_PaymentIdPaymentSendFailureZ_Err;
885 Result_PaymentIdPaymentErrorZ send_res = peer1.payer.pay_invoice(((Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res);
886 assert send_res instanceof Result_PaymentIdPaymentErrorZ.Result_PaymentIdPaymentErrorZ_OK;
890 if (use_chan_manager_constructor) {
891 peer1.constructor.interrupt();
892 peer2.constructor.interrupt();
893 } else if (use_nio_peer_handler) {
894 peer1.nio_peer_handler.interrupt();
895 peer2.nio_peer_handler.interrupt();
897 WeakReference<Peer> op1 = new WeakReference<Peer>(peer1);
898 peer1 = new Peer(peer1);
899 peer2 = new Peer(peer2);
900 return new TestState(op1, peer1, peer2, b.getHash());
902 return new TestState(null, peer1, peer2, b.getHash());
905 boolean cross_reload_ref_pollution = false;
907 private final WeakReference<Peer> ref_block;
908 private final Peer peer1;
909 private final Peer peer2;
910 public Sha256Hash best_blockhash;
912 public TestState(WeakReference<Peer> ref_block, Peer peer1, Peer peer2, Sha256Hash best_blockhash) {
913 this.ref_block = ref_block;
916 this.best_blockhash = best_blockhash;
919 void do_test_message_handler_b(TestState state) throws InterruptedException {
920 GcCheck obj = new GcCheck();
921 if (state.ref_block != null) {
922 // Ensure the original peers get freed before we move on. Note that we have to be in a different function
923 // scope to do so as the (at least current OpenJDK) JRE won't release anything created in the same scope.
924 while (!cross_reload_ref_pollution && state.ref_block.get() != null) {
926 System.runFinalization();
928 connect_peers(state.peer1, state.peer2);
931 Event[] events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
932 assert events[0] instanceof Event.PendingHTLCsForwardable;
933 state.peer2.chan_manager.process_pending_htlc_forwards();
935 events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
936 assert events[0] instanceof Event.PaymentReceived;
937 assert ((Event.PaymentReceived)events[0]).purpose instanceof PaymentPurpose.InvoicePayment;
938 byte[] payment_preimage = ((PaymentPurpose.InvoicePayment)((Event.PaymentReceived)events[0]).purpose).payment_preimage;
939 assert !Arrays.equals(payment_preimage, new byte[32]);
940 state.peer2.chan_manager.claim_funds(payment_preimage);
942 events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
943 assert events[0] instanceof Event.PaymentClaimed;
944 assert ((Event.PaymentClaimed)events[0]).purpose instanceof PaymentPurpose.InvoicePayment;
945 payment_preimage = ((PaymentPurpose.InvoicePayment)((Event.PaymentClaimed)events[0]).purpose).payment_preimage;
946 assert !Arrays.equals(payment_preimage, new byte[32]);
948 events = state.peer1.get_manager_events(2, state.peer1, state.peer2);
949 assert events[0] instanceof Event.PaymentSent;
950 assert Arrays.equals(((Event.PaymentSent) events[0]).payment_preimage, payment_preimage);
951 assert events[1] instanceof Event.PaymentPathSuccessful;
952 assert Arrays.equals(((Event.PaymentPathSuccessful) events[1]).payment_hash, ((Event.PaymentSent) events[0]).payment_hash);
954 if (use_nio_peer_handler) {
955 // We receive PaymentSent immediately upon receipt of the payment preimage, but we expect to not have an
956 // HTLC transaction to broadcast below, which requires a bit more time to fully complete the
957 // commitment-transaction-update dance between both peers.
961 if (state.peer1.chain_monitor != null) {
962 Balance[] peer1_balances = state.peer1.chain_monitor.get_claimable_balances(state.peer1.chan_manager.list_channels());
963 assert peer1_balances.length == 0;
964 Balance[] peer2_balances = state.peer2.chain_monitor.get_claimable_balances(state.peer2.chan_manager.list_channels());
965 assert peer2_balances.length == 0;
968 ChannelDetails[] peer1_chans = state.peer1.chan_manager.list_channels();
971 Result_NoneAPIErrorZ close_res = state.peer1.chan_manager.close_channel(peer1_chans[0].get_channel_id(), state.peer2.node_id);
972 assert close_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
973 maybe_exchange_peer_messages(state.peer1, state.peer2);
974 synchronized (state.peer1.broadcast_set) {
975 while (state.peer1.broadcast_set.size() != 1) state.peer1.broadcast_set.wait();
977 synchronized (state.peer2.broadcast_set) {
978 while (state.peer2.broadcast_set.size() != 1) state.peer2.broadcast_set.wait();
981 state.peer1.chan_manager.force_close_all_channels_broadcasting_latest_txn();
982 maybe_exchange_peer_messages(state.peer1, state.peer2);
983 synchronized (state.peer1.broadcast_set) {
984 while (state.peer1.broadcast_set.size() != 1) state.peer1.broadcast_set.wait();
986 synchronized (state.peer2.broadcast_set) {
987 while (state.peer2.broadcast_set.size() != 1) state.peer2.broadcast_set.wait();
991 assert state.peer1.broadcast_set.size() == 1;
992 assert state.peer2.broadcast_set.size() == 1;
994 events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
995 assert events[0] instanceof Event.ChannelClosed;
996 events = state.peer1.get_manager_events(1, state.peer1, state.peer2);
997 assert events[0] instanceof Event.ChannelClosed;
999 if (state.peer1.chain_monitor != null) {
1000 Balance[] peer1_balances = state.peer1.chain_monitor.get_claimable_balances(state.peer1.chan_manager.list_channels());
1001 assert peer1_balances.length == 1;
1002 for (Balance bal : peer1_balances) {
1003 assert bal instanceof Balance.ClaimableOnChannelClose;
1004 long expected_tx_fee = 183;
1005 assert ((Balance.ClaimableOnChannelClose) bal).claimable_amount_satoshis == 100000 - 1 - 10000 - expected_tx_fee;
1007 Balance[] peer2_balances = state.peer2.chain_monitor.get_claimable_balances(state.peer2.chan_manager.list_channels());
1008 assert peer2_balances.length == 1;
1009 for (Balance bal : peer2_balances) {
1010 assert bal instanceof Balance.ClaimableOnChannelClose;
1011 assert ((Balance.ClaimableOnChannelClose) bal).claimable_amount_satoshis == 10000 + 1;
1016 NetworkParameters bitcoinj_net = NetworkParameters.fromID(NetworkParameters.ID_MAINNET);
1017 Transaction tx = new Transaction(bitcoinj_net, state.peer1.broadcast_set.getFirst());
1018 Block b = new Block(bitcoinj_net, 2, state.best_blockhash, Sha256Hash.ZERO_HASH, 42, 0, 0,
1019 Arrays.asList(new Transaction[]{tx}));
1020 TwoTuple_TxidCVec_C2Tuple_u32TxOutZZZ[] watch_outputs = state.peer2.connect_block(b, 10, 1);
1021 if (watch_outputs != null) { // We only process watch_outputs manually when we use a manually-build Watch impl
1022 assert watch_outputs.length == 1;
1023 assert Arrays.equals(watch_outputs[0].get_a(), tx.getTxId().getReversedBytes());
1024 assert watch_outputs[0].get_b().length == 2;
1025 assert watch_outputs[0].get_b()[0].get_a() == 0;
1026 assert watch_outputs[0].get_b()[1].get_a() == 1;
1029 for (int i = 11; i < 21; i++) {
1030 b = new Block(bitcoinj_net, 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, new ArrayList<>());
1031 state.peer2.connect_block(b, i, 0);
1034 Event[] broadcastable_event = state.peer2.get_monitor_events(1);
1035 for (ChannelMonitor mon : state.peer2.monitors.values()) {
1036 // This used to be buggy and double-free, so go ahead and fetch them!
1037 byte[][] txn = mon.get_latest_holder_commitment_txn(state.peer2.logger);
1039 assert broadcastable_event.length == 1;
1040 assert broadcastable_event[0] instanceof Event.SpendableOutputs;
1041 if (state.peer2.explicit_keys_manager != null) {
1042 TxOut[] additional_outputs = new TxOut[]{new TxOut(420, new byte[]{0x42})};
1043 Result_TransactionNoneZ tx_res = state.peer2.explicit_keys_manager.spend_spendable_outputs(((Event.SpendableOutputs) broadcastable_event[0]).outputs, additional_outputs, new byte[]{0x00}, 253);
1044 assert tx_res instanceof Result_TransactionNoneZ.Result_TransactionNoneZ_OK;
1045 Transaction built_tx = new Transaction(bitcoinj_net, ((Result_TransactionNoneZ.Result_TransactionNoneZ_OK) tx_res).res);
1046 assert built_tx.getOutputs().size() == 2;
1047 assert Arrays.equals(built_tx.getOutput(1).getScriptBytes(), new byte[]{0x00});
1048 assert Arrays.equals(built_tx.getOutput(0).getScriptBytes(), new byte[]{0x42});
1049 assert built_tx.getOutput(0).getValue().value == 420;
1053 // Test exchanging a custom message (note that ChannelManagerConstructor) always loads an IgnorimgMessageHandler
1054 // so we cannot exchange custom messages with it
1055 if (!use_chan_manager_constructor) {
1056 byte[] custom_message_bytes = new byte[]{0x42, 0x44, 0x43, 0x00};
1057 state.peer1.custom_messages_to_send.add(custom_message_bytes);
1058 state.peer1.peer_manager.process_events();
1059 synchronized (state.peer2.received_custom_messages) {
1061 if (state.peer2.received_custom_messages.isEmpty()) {
1062 state.peer2.received_custom_messages.wait();
1065 assert state.peer2.received_custom_messages.size() == 1;
1066 assert Arrays.equals(state.peer2.received_custom_messages.get(0), custom_message_bytes);
1072 if (use_nio_peer_handler) {
1073 state.peer1.peer_manager.disconnect_by_node_id(state.peer2.chan_manager.get_our_node_id(), false);
1074 while (state.peer1.peer_manager.get_peer_node_ids().length != 0) Thread.yield();
1075 while (state.peer2.peer_manager.get_peer_node_ids().length != 0) Thread.yield();
1076 state.peer1.nio_peer_handler.interrupt();
1077 state.peer2.nio_peer_handler.interrupt();
1080 state.peer1.get_monitor_events(0);
1081 state.peer2.get_monitor_events(0);
1083 if (use_chan_manager_constructor) {
1084 state.peer1.constructor.interrupt();
1085 state.peer2.constructor.interrupt();
1090 if (state.peer1.router != null)
1091 state.peer1.router.write();
1093 // Construct the only Option_Enum::Variant(OpaqueStruct) we have in the codebase as this used to cause double-frees:
1094 byte[] serd = new byte[] {(byte)0xd9,(byte)0x77,(byte)0xcb,(byte)0x9b,(byte)0x53,(byte)0xd9,(byte)0x3a,(byte)0x6f,(byte)0xf6,(byte)0x4b,(byte)0xb5,(byte)0xf1,(byte)0xe1,(byte)0x58,(byte)0xb4,(byte)0x09,(byte)0x4b,(byte)0x66,(byte)0xe7,(byte)0x98,(byte)0xfb,(byte)0x12,(byte)0x91,(byte)0x11,(byte)0x68,(byte)0xa3,(byte)0xcc,(byte)0xdf,(byte)0x80,(byte)0xa8,(byte)0x30,(byte)0x96,(byte)0x34,(byte)0x0a,(byte)0x6a,(byte)0x95,(byte)0xda,(byte)0x0a,(byte)0xe8,(byte)0xd9,(byte)0xf7,(byte)0x76,(byte)0x52,(byte)0x8e,(byte)0xec,(byte)0xdb,(byte)0xb7,(byte)0x47,(byte)0xeb,(byte)0x6b,(byte)0x54,(byte)0x54,(byte)0x95,(byte)0xa4,(byte)0x31,(byte)0x9e,(byte)0xd5,(byte)0x37,(byte)0x8e,(byte)0x35,(byte)0xb2,(byte)0x1e,(byte)0x07,(byte)0x3a,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x01,(byte)0x19,(byte)0xd6,(byte)0x68,(byte)0x9c,(byte)0x08,(byte)0x5a,(byte)0xe1,(byte)0x65,(byte)0x83,(byte)0x1e,(byte)0x93,(byte)0x4f,(byte)0xf7,(byte)0x63,(byte)0xae,(byte)0x46,(byte)0xa2,(byte)0xa6,(byte)0xc1,(byte)0x72,(byte)0xb3,(byte)0xf1,(byte)0xb6,(byte)0x0a,(byte)0x8c,(byte)0xe2,(byte)0x6f,(byte)0x00,(byte)0x08,(byte)0x3a,(byte)0x84,(byte)0x00,(byte)0x00,(byte)0x03,(byte)0x4d,(byte)0x01,(byte)0x34,(byte)0x13,(byte)0xa7,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x90,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x0f,(byte)0x42,(byte)0x40,(byte)0x00,(byte)0x00,(byte)0x27,(byte)0x10,(byte)0x00,(byte)0x00,(byte)0x00,(byte)0x14,(byte)0xde,(byte)0xad,(byte)0xbe,(byte)0xef,(byte)0x42,(byte)0x42,(byte)0x42,(byte)0x42};
1095 Result_ChannelUpdateDecodeErrorZ upd_msg = ChannelUpdate.read(serd);
1096 assert upd_msg instanceof Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK;
1097 assert ((Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK) upd_msg).res.get_contents().get_htlc_maximum_msat() == 0xdeadbeef42424242L;
1098 Option_NetworkUpdateZ upd = Option_NetworkUpdateZ.some(NetworkUpdate.channel_update_message(((Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK) upd_msg).res));
1101 java.util.LinkedList<WeakReference<Object>> must_free_objs = new java.util.LinkedList();
1103 int gc_exp_count = 0;
1105 GcCheck() { gc_exp_count += 1; }
1107 protected void finalize() throws Throwable {
1113 public class HumanObjectPeerTest {
1114 static HumanObjectPeerTestInstance do_test_run(boolean nice_close, boolean use_km_wrapper, boolean use_manual_watch, boolean reload_peers, boolean break_cross_peer_refs, boolean nio_peer_handler, boolean use_ignoring_routing_handler, boolean use_chan_manager_constructor, boolean use_invoice_payer) throws InterruptedException {
1115 HumanObjectPeerTestInstance instance = new HumanObjectPeerTestInstance(nice_close, use_km_wrapper, use_manual_watch, reload_peers, break_cross_peer_refs, nio_peer_handler, !nio_peer_handler, use_ignoring_routing_handler, use_chan_manager_constructor, use_invoice_payer);
1116 HumanObjectPeerTestInstance.TestState state = instance.do_test_message_handler();
1117 instance.do_test_message_handler_b(state);
1120 static void do_test(boolean nice_close, boolean use_km_wrapper, boolean use_manual_watch, boolean reload_peers, boolean break_cross_peer_refs, boolean nio_peer_handler, boolean use_ignoring_routing_handler, boolean use_chan_manager_constructor, boolean use_invoice_payer) throws InterruptedException {
1121 HumanObjectPeerTestInstance instance = do_test_run(nice_close, use_km_wrapper, use_manual_watch, reload_peers, break_cross_peer_refs, nio_peer_handler, use_ignoring_routing_handler, use_chan_manager_constructor, use_invoice_payer);
1122 while (instance.gc_count != instance.gc_exp_count) {
1124 System.runFinalization();
1126 for (WeakReference<Object> o : instance.must_free_objs)
1127 assert o.get() == null;
1129 public static final int TEST_ITERATIONS = (1 << 9);
1130 public static void do_test_message_handler(IntConsumer statusFunction) throws InterruptedException {
1131 Thread gc_thread = new Thread(() -> {
1134 System.runFinalization();
1135 try { Thread.sleep(0, 1); } catch (InterruptedException e) { break; }
1137 }, "Test GC Thread");
1139 for (int i = 0; i < TEST_ITERATIONS; i++) {
1140 boolean nice_close = (i & (1 << 0)) != 0;
1141 boolean use_km_wrapper = (i & (1 << 1)) != 0;
1142 boolean use_manual_watch = (i & (1 << 2)) != 0;
1143 boolean reload_peers = (i & (1 << 3)) != 0;
1144 boolean break_cross_refs = (i & (1 << 4)) != 0;
1145 boolean use_ignoring_routing_handler = (i & (1 << 5)) != 0;
1146 boolean use_chan_manager_constructor = (i & (1 << 6)) != 0;
1147 boolean use_invoice_payer = (i & (1 << 7)) != 0;
1148 boolean nio_peer_handler = (i & (1 << 8)) != 0;
1149 if (break_cross_refs && !reload_peers) {
1150 // There are no cross refs to break without reloading peers.
1153 if (use_chan_manager_constructor && (use_manual_watch || !nio_peer_handler)) {
1154 // ChannelManagerConstructor requires a ChainMonitor as the Watch and creates a NioPeerHandler for us.
1157 if (!use_chan_manager_constructor && (use_ignoring_routing_handler)) {
1158 // We rely on the ChannelManagerConstructor to convert null into an IgnoringMessageHandler, so don't
1159 // try to run with an IgnoringMessageHandler unless we're also using a ChannelManagerConstructor.
1162 if (use_chan_manager_constructor && use_ignoring_routing_handler && use_invoice_payer) {
1163 // As documented on ChannelManagerConstructor, if we provide a `null` NetworkGraph (because we want to
1164 // use an IgnoringMessageHandler), no InvoicePayer will be constructored for us, thus we cannot use an
1165 // InvoicePayer to send payments in this case.
1168 statusFunction.accept(i);
1169 do_test(nice_close, use_km_wrapper, use_manual_watch, reload_peers, break_cross_refs, nio_peer_handler, use_ignoring_routing_handler, use_chan_manager_constructor, use_invoice_payer);
1171 gc_thread.interrupt();
1175 public void test_message_handler() throws InterruptedException {
1176 do_test_message_handler(i -> System.err.println("Running test with flags " + i));
1179 // This is used in the test jar to test the built jar is runnable
1180 public static void main(String[] args) {
1182 do_test_message_handler(i -> System.err.println("Running test with flags " + i));
1183 } catch (Exception e) {
1184 System.err.println("Caught exception:");
1185 System.err.println(e);