3 import org.bitcoinj.base.BitcoinNetwork;
4 import org.bitcoinj.base.Coin;
5 import org.bitcoinj.base.Sha256Hash;
6 import org.bitcoinj.core.*;
7 import org.bitcoinj.params.BitcoinNetworkParams;
8 import org.bitcoinj.script.Script;
9 import org.junit.jupiter.api.Test;
10 import org.ldk.batteries.ChannelManagerConstructor;
11 import org.ldk.batteries.NioPeerHandler;
12 import org.ldk.enums.*;
13 import org.ldk.enums.Currency;
14 import org.ldk.structs.*;
15 import org.ldk.util.UInt128;
16 import org.ldk.util.UInt5;
18 import java.io.IOException;
19 import java.lang.ref.WeakReference;
20 import java.net.InetSocketAddress;
22 import java.util.function.IntConsumer;
24 class HumanObjectPeerTestInstance {
25 private final boolean nice_close;
26 private final boolean use_km_wrapper;
27 private final boolean use_manual_watch;
28 private final boolean reload_peers;
29 private final boolean break_cross_peer_refs;
30 private final boolean use_nio_peer_handler;
31 private final boolean use_filter;
32 private final boolean use_ignore_handler;
33 private final boolean use_chan_manager_constructor;
34 private final boolean use_invoice_payer;
35 TxOut gossip_txout = null;
37 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) {
38 this.nice_close = nice_close;
39 this.use_km_wrapper = use_km_wrapper;
40 this.use_manual_watch = use_manual_watch;
41 this.reload_peers = reload_peers;
42 this.break_cross_peer_refs = break_cross_peer_refs;
43 this.use_nio_peer_handler = use_nio_peer_handler;
44 this.use_filter = use_filter;
45 this.use_ignore_handler = use_ignore_handler;
46 this.use_chan_manager_constructor = use_chan_manager_constructor;
47 this.use_invoice_payer = use_invoice_payer;
51 NodeSigner manual_node_signer(KeysManager underlying_km) {
52 NodeSigner underlying_ns = underlying_km.as_NodeSigner();
53 must_free_objs.add(new WeakReference<>(underlying_ns));
54 return NodeSigner.new_impl(new NodeSigner.NodeSignerInterface() {
55 @Override public byte[] get_inbound_payment_key_material() { return underlying_ns.get_inbound_payment_key_material(); }
56 @Override public Result_PublicKeyNoneZ get_node_id(Recipient recipient) { return underlying_ns.get_node_id(recipient); }
57 @Override public Result_ThirtyTwoBytesNoneZ ecdh(Recipient recipient, byte[] other_key, Option_BigEndianScalarZ tweak) {
58 return underlying_ns.ecdh(recipient, other_key, tweak);
60 @Override public Result_RecoverableSignatureNoneZ sign_invoice(byte[] hrp_bytes, UInt5[] invoice_data, Recipient recipient) {
61 return underlying_ns.sign_invoice(hrp_bytes, invoice_data, recipient);
63 @Override public Result_SchnorrSignatureNoneZ sign_bolt12_invoice_request(UnsignedInvoiceRequest invoice_request) {
64 return underlying_ns.sign_bolt12_invoice_request(invoice_request);
66 @Override public Result_SchnorrSignatureNoneZ sign_bolt12_invoice(UnsignedBolt12Invoice invoice) {
67 return underlying_ns.sign_bolt12_invoice(invoice);
69 @Override public Result_ECDSASignatureNoneZ sign_gossip_message(UnsignedGossipMessage msg) {
70 return underlying_ns.sign_gossip_message(msg);
74 SignerProvider manual_signer_provider(KeysManager underlying_km) {
75 SignerProvider underlying_sp = underlying_km.as_SignerProvider();
76 must_free_objs.add(new WeakReference<>(underlying_sp));
77 return SignerProvider.new_impl(new SignerProvider.SignerProviderInterface() {
78 @Override public Result_CVec_u8ZNoneZ get_destination_script() { return underlying_sp.get_destination_script(); }
79 @Override public Result_ShutdownScriptNoneZ get_shutdown_scriptpubkey() { return underlying_sp.get_shutdown_scriptpubkey(); }
80 @Override public byte[] generate_channel_keys_id(boolean inbound, long channel_value_satoshis, UInt128 user_channel_id) {
81 return underlying_sp.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id);
84 public WriteableEcdsaChannelSigner derive_channel_signer(long channel_value_satoshis, byte[] channel_keys_id) {
85 WriteableEcdsaChannelSigner underlying_wecs = underlying_sp.derive_channel_signer(channel_value_satoshis, channel_keys_id);
86 EcdsaChannelSigner underlying_ecs = underlying_wecs.get_ecdsa_channel_signer();
87 ChannelSigner underlying_cs = underlying_ecs.get_channel_signer();
88 ChannelSigner.ChannelSignerInterface csi = new ChannelSigner.ChannelSignerInterface() {
89 @Override public byte[] get_per_commitment_point(long idx) { return underlying_cs.get_per_commitment_point(idx); }
90 @Override public byte[] release_commitment_secret(long idx) { return underlying_cs.release_commitment_secret(idx); }
91 @Override public Result_NoneNoneZ validate_holder_commitment(HolderCommitmentTransaction holder_tx, byte[][] preimages) {
92 return underlying_cs.validate_holder_commitment(holder_tx, preimages);
94 @Override public byte[] channel_keys_id() { return underlying_cs.channel_keys_id(); }
95 @Override public void provide_channel_parameters(ChannelTransactionParameters channel_parameters) {
96 underlying_cs.provide_channel_parameters(channel_parameters);
99 EcdsaChannelSigner.EcdsaChannelSignerInterface ecsi = new EcdsaChannelSigner.EcdsaChannelSignerInterface() {
100 @Override public Result_C2Tuple_ECDSASignatureCVec_ECDSASignatureZZNoneZ sign_counterparty_commitment(CommitmentTransaction commitment_tx, byte[][] preimages) {
101 return underlying_ecs.sign_counterparty_commitment(commitment_tx, preimages);
103 @Override public Result_NoneNoneZ validate_counterparty_revocation(long idx, byte[] secret) {
104 return underlying_ecs.validate_counterparty_revocation(idx, secret);
106 @Override public Result_C2Tuple_ECDSASignatureCVec_ECDSASignatureZZNoneZ sign_holder_commitment_and_htlcs(HolderCommitmentTransaction commitment_tx) {
107 return underlying_ecs.sign_holder_commitment_and_htlcs(commitment_tx);
109 @Override public Result_ECDSASignatureNoneZ sign_justice_revoked_output(byte[] justice_tx, long input, long amount, byte[] per_commitment_key) {
110 return underlying_ecs.sign_justice_revoked_output(justice_tx, input, amount, per_commitment_key);
112 @Override public Result_ECDSASignatureNoneZ sign_justice_revoked_htlc(byte[] justice_tx, long input, long amount, byte[] per_commitment_key, HTLCOutputInCommitment htlc) {
113 return underlying_ecs.sign_justice_revoked_htlc(justice_tx, input, amount, per_commitment_key, htlc);
115 @Override public Result_ECDSASignatureNoneZ sign_holder_htlc_transaction(byte[] htlc_tx, long input, HTLCDescriptor htlc_descriptor) {
116 return underlying_ecs.sign_holder_htlc_transaction(htlc_tx, input, htlc_descriptor);
118 @Override public Result_ECDSASignatureNoneZ sign_counterparty_htlc_transaction(byte[] htlc_tx, long input, long amount, byte[] per_commitment_point, HTLCOutputInCommitment htlc) {
119 return underlying_ecs.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc);
121 @Override public Result_ECDSASignatureNoneZ sign_closing_transaction(ClosingTransaction closing_tx) {
122 return underlying_ecs.sign_closing_transaction(closing_tx);
124 @Override public Result_ECDSASignatureNoneZ sign_holder_anchor_input(byte[] anchor_tx, long input) {
125 return underlying_ecs.sign_holder_anchor_input(anchor_tx, input);
127 @Override public Result_ECDSASignatureNoneZ sign_channel_announcement_with_funding_key(UnsignedChannelAnnouncement msg) {
128 return underlying_ecs.sign_channel_announcement_with_funding_key(msg);
131 WriteableEcdsaChannelSigner.WriteableEcdsaChannelSignerInterface wecsi = new WriteableEcdsaChannelSigner.WriteableEcdsaChannelSignerInterface() {
132 @Override public byte[] write() { return underlying_wecs.write(); }
134 WriteableEcdsaChannelSigner resp = WriteableEcdsaChannelSigner.new_impl(wecsi, ecsi, csi, underlying_cs.get_pubkeys());
135 must_free_objs.add(new WeakReference<>(wecsi));
136 must_free_objs.add(new WeakReference<>(ecsi));
137 must_free_objs.add(new WeakReference<>(csi));
138 must_free_objs.add(new WeakReference<>(resp));
139 must_free_objs.add(new WeakReference<>(underlying_wecs));
140 must_free_objs.add(new WeakReference<>(underlying_ecs));
141 must_free_objs.add(new WeakReference<>(underlying_cs));
146 public Result_WriteableEcdsaChannelSignerDecodeErrorZ read_chan_signer(byte[] reader) {
147 return underlying_sp.read_chan_signer(reader);
152 Watch get_manual_watch() {
153 Watch.WatchInterface watch_impl = new Watch.WatchInterface() {
154 public Result_ChannelMonitorUpdateStatusNoneZ watch_channel(OutPoint funding_txo, ChannelMonitor monitor) {
155 synchronized (monitors) {
156 assert monitors.put(Arrays.toString(funding_txo.get_txid()), monitor) == null;
158 return Result_ChannelMonitorUpdateStatusNoneZ.ok(ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed);
161 public ChannelMonitorUpdateStatus update_channel(OutPoint funding_txo, ChannelMonitorUpdate update) {
162 synchronized (monitors) {
163 String txid = Arrays.toString(funding_txo.get_txid());
164 assert monitors.containsKey(txid);
165 Result_NoneNoneZ update_res = monitors.get(txid).update_monitor(update, tx_broadcaster, fee_estimator, logger);
166 assert update_res instanceof Result_NoneNoneZ.Result_NoneNoneZ_OK;
168 return ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
172 public ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[] release_pending_monitor_events() {
173 synchronized (monitors) {
174 assert monitors.size() <= 1;
175 for (ChannelMonitor mon : monitors.values()) {
176 ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[] res = new ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[1];
177 res[0] = ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ.of(mon.get_funding_txo().get_a(), mon.get_and_clear_pending_monitor_events(), mon.get_counterparty_node_id());
181 return new ThreeTuple_OutPointCVec_MonitorEventZPublicKeyZ[0];
184 Watch watch = Watch.new_impl(watch_impl);
185 must_free_objs.add(new WeakReference<>(watch_impl));
186 must_free_objs.add(new WeakReference<>(watch));
190 UserConfig get_config() {
191 ChannelHandshakeConfig channel_config = ChannelHandshakeConfig.with_default();
192 channel_config.set_announced_channel(true);
193 UserConfig config = UserConfig.with_default();
194 config.set_channel_handshake_config(channel_config);
198 NioPeerHandler nio_peer_handler;
201 final byte[] key_seed = new byte[32];
203 final FeeEstimator fee_estimator;
204 final BroadcasterInterface tx_broadcaster;
205 final KeysManager explicit_keys_manager;
206 final NodeSigner node_signer;
207 final SignerProvider signer_provider;
208 final EntropySource entropy_source;
209 final ChainMonitor chain_monitor;
210 NetworkGraph net_graph;
211 P2PGossipSync route_handler;
212 final Watch chain_watch;
213 final HashSet<String> filter_additions;
214 Option_FilterZ filter;
215 ChannelManager chan_manager;
216 PeerManager peer_manager;
217 final HashMap<String, ChannelMonitor> monitors; // Wow I forgot just how terrible Java is - we can't put a byte array here.
219 byte[] connected_peer_node_id = null;
220 final LinkedList<byte[]> broadcast_set = new LinkedList<>();
221 final LinkedList<Event> pending_manager_events = new LinkedList<>();
222 private final CustomMessageHandler custom_message_handler;
223 final LinkedList<byte[]> received_custom_messages = new LinkedList<>();
224 final LinkedList<byte[]> custom_messages_to_send = new LinkedList<>();
225 ChannelManagerConstructor constructor = null;
226 long network_graph_persists = 0;
227 GcCheck obj = new GcCheck();
229 private ChannelMonitor test_mon_roundtrip(OutPoint expected_id, byte[] data) {
230 // Because get_funding_txo() returns an OutPoint in a tuple that is a reference to an OutPoint inside the
231 // ChannelMonitor, its a good test to ensure that the OutPoint isn't freed (or is cloned) before the
232 // ChannelMonitor is. This used to be broken.
233 Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ roundtrip_monitor = UtilMethods.C2Tuple_ThirtyTwoBytesChannelMonitorZ_read(data, this.entropy_source, this.signer_provider);
234 assert roundtrip_monitor instanceof Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK;
235 must_free_objs.add(new WeakReference<>(roundtrip_monitor));
236 TwoTuple_OutPointCVec_u8ZZ funding_txo = ((Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK) roundtrip_monitor).res.get_b().get_funding_txo();
237 must_free_objs.add(new WeakReference<>(funding_txo));
238 System.gc(); System.runFinalization(); // Give the GC a chance to run.
239 assert Arrays.equals(funding_txo.get_a().get_txid(), expected_id.get_txid());
240 assert funding_txo.get_a().get_index() == expected_id.get_index();
241 Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ roundtrip_two = UtilMethods.C2Tuple_ThirtyTwoBytesChannelMonitorZ_read(data, this.entropy_source, this.signer_provider);
242 assert roundtrip_two instanceof Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK;
243 must_free_objs.add(new WeakReference<>(((Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK) roundtrip_two).res.get_b()));
244 must_free_objs.add(new WeakReference<>(((Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK) roundtrip_two).res));
245 must_free_objs.add(new WeakReference<>(roundtrip_two));
246 return ((Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK) roundtrip_two).res.get_b();
249 private Peer(Object _dummy, byte seed) {
250 logger = Logger.new_impl((org.ldk.structs.Record arg)->{
251 if (arg.get_level() == Level.LDKLevel_Error)
252 System.err.println(seed + ": " + arg.get_module_path() + " - " + arg.get_args());
254 System.out.println(seed + ": " + arg.get_module_path() + " - " + arg.get_args());
256 fee_estimator = FeeEstimator.new_impl((confirmation_target -> 253));
257 tx_broadcaster = BroadcasterInterface.new_impl(txn -> {
258 synchronized (broadcast_set) {
259 for (byte[] tx : txn){
260 broadcast_set.add(tx);
262 broadcast_set.notifyAll();
265 monitors = new HashMap<>();
267 Persist persister = Persist.new_impl(new Persist.PersistInterface() {
269 public ChannelMonitorUpdateStatus persist_new_channel(OutPoint id, ChannelMonitor data, MonitorUpdateId update_id) {
270 synchronized (monitors) {
271 String key = Arrays.toString(id.to_channel_id());
272 ChannelMonitor res = test_mon_roundtrip(id, data.write());
273 assert monitors.put(key, res) == null;
275 return ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
279 public ChannelMonitorUpdateStatus update_persisted_channel(OutPoint id, ChannelMonitorUpdate update, ChannelMonitor data, MonitorUpdateId update_id) {
280 synchronized (monitors) {
281 String key = Arrays.toString(id.to_channel_id());
282 ChannelMonitor res = test_mon_roundtrip(id, data.write());
283 // Note that we use a serialization-roundtrip copy of data here, not the original, as this can
284 // expose the JVM JIT bug where it finalize()s things still being called.
285 assert monitors.put(key, res) != null;
287 return ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed;
291 filter_additions = new HashSet<>();
293 this.filter = Option_FilterZ.some(Filter.new_impl(new Filter.FilterInterface() {
294 @Override public void register_tx(byte[] txid, byte[] script_pubkey) {
295 filter_additions.add(Arrays.toString(txid));
297 @Override public void register_output(WatchedOutput output) {
298 filter_additions.add(Arrays.toString(output.get_outpoint().get_txid()) + ":" + output.get_outpoint().get_index());
302 this.filter = Option_FilterZ.none();
305 if (use_manual_watch) {
306 chain_watch = get_manual_watch();
307 chain_monitor = null;
309 chain_monitor = ChainMonitor.of(filter, tx_broadcaster, logger, fee_estimator, persister);
310 chain_watch = chain_monitor.as_Watch();
313 for (byte i = 0; i < 32; i++) {
314 key_seed[i] = (byte) (i ^ seed);
316 KeysManager keys = KeysManager.of(key_seed, System.currentTimeMillis() / 1000, (int) (System.currentTimeMillis() * 1000));
317 if (use_km_wrapper) {
318 this.signer_provider = manual_signer_provider(keys);
319 this.node_signer = manual_node_signer(keys);
320 this.entropy_source = EntropySource.new_impl(new EntropySource.EntropySourceInterface() {
321 @Override public byte[] get_secure_random_bytes() { return keys.as_EntropySource().get_secure_random_bytes(); }
323 this.explicit_keys_manager = null;
325 this.signer_provider = keys.as_SignerProvider();
326 this.entropy_source = keys.as_EntropySource();
327 this.node_signer = keys.as_NodeSigner();
328 this.explicit_keys_manager = keys;
331 this.custom_message_handler = CustomMessageHandler.new_impl(new CustomMessageHandler.CustomMessageHandlerInterface() {
333 public Result_NoneLightningErrorZ handle_custom_message(Type msg, byte[] sender_node_id) {
334 synchronized (received_custom_messages) {
335 received_custom_messages.add(msg.write());
336 received_custom_messages.notifyAll();
338 return Result_NoneLightningErrorZ.ok();
342 public TwoTuple_PublicKeyTypeZ[] get_and_clear_pending_msg() {
344 synchronized (custom_messages_to_send) {
345 bytes = custom_messages_to_send.toArray(new byte[0][0]);
346 custom_messages_to_send.clear();
348 TwoTuple_PublicKeyTypeZ[] ret = new TwoTuple_PublicKeyTypeZ[bytes.length];
349 for (int i = 0; i < bytes.length; i++) {
350 final int msg_idx = i;
351 ret[i] = TwoTuple_PublicKeyTypeZ.of(connected_peer_node_id, Type.new_impl(new Type.TypeInterface() {
352 @Override public short type_id() { return 4096; }
353 @Override public String debug_str() { return "Custom Java Message"; }
354 @Override public byte[] write() { return bytes[msg_idx]; }
359 @Override public NodeFeatures provided_node_features() {
360 return NodeFeatures.empty();
362 @Override public InitFeatures provided_init_features(byte[] their_node_id) {
363 return InitFeatures.empty();
365 }, (message_type, buffer) -> {
366 assert message_type == 4096;
367 return Result_COption_TypeZDecodeErrorZ.ok(Option_TypeZ.some(Type.new_impl(new Type.TypeInterface() {
368 @Override public short type_id() { return 4096; }
369 @Override public String debug_str() { return "Custom Java-Decoded Message"; }
370 @Override public byte[] write() { return buffer; }
374 private void bind_nio() {
375 if (!use_nio_peer_handler) return;
376 if (use_chan_manager_constructor) {
377 this.nio_peer_handler = this.constructor.nio_peer_handler;
379 try { this.nio_peer_handler = new NioPeerHandler(peer_manager); } catch (IOException e) { assert false; }
381 for (short i = 10_000; true; i++) {
383 nio_peer_handler.bind_listener(new InetSocketAddress("127.0.0.1", i));
386 } catch (IOException e) { assert i < 10_500; }
389 private void setup_route_handler() {
390 this.route_handler = P2PGossipSync.of(this.net_graph,
391 Option_UtxoLookupZ.some(UtxoLookup.new_impl((genesis_hash, short_channel_id) -> UtxoResult.sync(Result_TxOutUtxoLookupErrorZ.ok(gossip_txout)))), this.logger);
395 this.net_graph = NetworkGraph.of(Network.LDKNetwork_Bitcoin, this.logger);
396 this.setup_route_handler();
398 if (use_chan_manager_constructor) {
399 this.constructor = new ChannelManagerConstructor(Network.LDKNetwork_Bitcoin, get_config(), new byte[32], 0,
400 this.explicit_keys_manager.as_EntropySource(), this.explicit_keys_manager.as_NodeSigner(), this.explicit_keys_manager.as_SignerProvider(),
401 this.fee_estimator, this.chain_monitor, this.net_graph,
402 ProbabilisticScoringDecayParameters.with_default(), ProbabilisticScoringFeeParameters.with_default(),
403 (ChannelManagerConstructor.RouterWrapper)
404 (payer_node_id, route_params, first_hops, inflight_htlcs, payment_hash, payment_id, default_router) -> {
405 assert payment_hash != null && payment_id != null;
406 Router r = default_router.as_Router();
407 must_free_objs.add(new WeakReference<>(r));
408 return r.find_route_with_id(payer_node_id, route_params, first_hops, inflight_htlcs, payment_hash, payment_id);
410 this.tx_broadcaster, this.logger);
411 constructor.chain_sync_completed(new ChannelManagerConstructor.EventHandler() {
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 @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; }
419 @Override public void persist_network_graph(byte[] graph_bytes) { assert graph_bytes.length > 1; network_graph_persists += 1; }
420 @Override public void persist_scorer(byte[] scorer_bytes) { assert scorer_bytes.length > 1; }
421 }, !use_ignore_handler);
422 this.chan_manager = constructor.channel_manager;
423 this.peer_manager = constructor.peer_manager;
424 must_free_objs.add(new WeakReference<>(this.chan_manager));
426 Router router = Router.new_impl(new Router.RouterInterface() {
428 public Result_RouteLightningErrorZ find_route_with_id(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs, byte[] _payment_hash, byte[] _payment_id) {
429 return find_route(payer, route_params, first_hops, inflight_htlcs);
433 public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) {
435 try (ReadOnlyNetworkGraph graph = net_graph.read_only()) {
436 assert graph.channel(424242) == null;
437 long[] channels = graph.list_channels();
438 if (channels.length != 1) {
439 // If we're using a NioPeerHandler, the handling of announcement signatures and
440 // channel broadcasting may be done async, so just wait until the channel shows up.
441 assert use_nio_peer_handler;
444 ChannelInfo chan = graph.channel(channels[0]);
445 assert Arrays.equals(chan.get_node_one().as_slice(), chan.get_node_one().write());
446 assert Arrays.equals(chan.get_node_one().as_slice(), chan_manager.get_our_node_id()) ||
447 Arrays.equals(chan.get_node_two().as_slice(), chan_manager.get_our_node_id());
451 return UtilMethods.find_route(payer, params, net_graph, first_hops, logger, ScoreLookUp.new_impl(new ScoreLookUp.ScoreLookUpInterface() {
452 @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage, ProbabilisticScoringFeeParameters params) { return 0; }
453 }), ProbabilisticScoringFeeParameters.with_default(), new byte[32]);
456 ChainParameters params = ChainParameters.of(Network.LDKNetwork_Bitcoin, BestBlock.of(new byte[32], 0));
457 this.chan_manager = ChannelManager.of(this.fee_estimator, chain_watch, tx_broadcaster, router, logger,
458 this.entropy_source, this.node_signer, this.signer_provider, get_config(), params,
459 (int)(System.currentTimeMillis() / 1000));
460 this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), route_handler.as_RoutingMessageHandler(),
461 IgnoringMessageHandler.of().as_OnionMessageHandler(), this.custom_message_handler, 0xdeadbeef,
462 this.entropy_source.get_secure_random_bytes(), logger, this.node_signer);
465 this.node_id = chan_manager.get_our_node_id();
473 this(null, orig.seed);
474 if (use_chan_manager_constructor) {
475 byte[][] monitors = {orig.monitors.values().stream().iterator().next().write()};
476 byte[] serialized = orig.chan_manager.write();
477 byte[] serialized_graph = orig.net_graph.write();
478 byte[] serialized_scorer = orig.constructor.scorer.write();
480 Filter filter_nullable = null;
481 if (this.filter instanceof Option_FilterZ.Some) {
482 filter_nullable = ((Option_FilterZ.Some) this.filter).some;
484 this.constructor = new ChannelManagerConstructor(serialized, monitors, get_config(),
485 this.explicit_keys_manager.as_EntropySource(), this.explicit_keys_manager.as_NodeSigner(), this.explicit_keys_manager.as_SignerProvider(),
486 this.fee_estimator, this.chain_monitor, filter_nullable,
487 serialized_graph, ProbabilisticScoringDecayParameters.with_default(),
488 ProbabilisticScoringFeeParameters.with_default(), serialized_scorer, null,
489 this.tx_broadcaster, this.logger);
491 // Test that ChannelManagerConstructor correctly rejects duplicate ChannelMonitors
492 byte[][] monitors_dupd = new byte[2][];
493 monitors_dupd[0] = monitors[0];
494 monitors_dupd[1] = monitors[0];
495 ChannelManagerConstructor constr = new ChannelManagerConstructor(serialized, monitors_dupd, get_config(),
496 this.explicit_keys_manager.as_EntropySource(), this.explicit_keys_manager.as_NodeSigner(), this.explicit_keys_manager.as_SignerProvider(),
497 this.fee_estimator, this.chain_monitor, filter_nullable,
498 serialized_graph, ProbabilisticScoringDecayParameters.with_default(),
499 ProbabilisticScoringFeeParameters.with_default(), serialized_scorer, null,
500 this.tx_broadcaster, this.logger);
502 } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {}
503 this.net_graph = this.constructor.net_graph;
504 setup_route_handler();
505 constructor.chain_sync_completed(new ChannelManagerConstructor.EventHandler() {
506 @Override public void handle_event(Event event) {
507 synchronized (pending_manager_events) {
508 pending_manager_events.add(event);
509 pending_manager_events.notifyAll();
512 @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; }
513 @Override public void persist_network_graph(byte[] graph_bytes) { assert graph_bytes.length > 1; network_graph_persists += 1; }
514 @Override public void persist_scorer(byte[] scorer_bytes) { assert scorer_bytes.length > 1; }
515 }, !use_ignore_handler);
516 this.chan_manager = constructor.channel_manager;
517 this.peer_manager = constructor.peer_manager;
518 must_free_objs.add(new WeakReference<>(this.chan_manager));
519 // If we are using a ChannelManagerConstructor, we may have pending events waiting on the old peer
520 // which have been removed from the ChannelManager but which we still need to handle.
521 this.pending_manager_events.addAll(orig.pending_manager_events);
522 if (!this.pending_manager_events.isEmpty()) {
523 // However, this implies cross_reload_ref_pollution
524 cross_reload_ref_pollution = true;
526 } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {
530 this.net_graph = NetworkGraph.of(Network.LDKNetwork_Bitcoin, this.logger);
531 Router router = Router.new_impl(new Router.RouterInterface() {
533 public Result_RouteLightningErrorZ find_route_with_id(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs, byte[] _payment_hash, byte[] _payment_id) {
534 return find_route(payer, route_params, first_hops, inflight_htlcs);
538 public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) {
540 try (ReadOnlyNetworkGraph graph = net_graph.read_only()) {
541 assert graph.channel(424242) == null;
542 long[] channels = graph.list_channels();
543 if (channels.length != 1) {
544 // If we're using a NioPeerHandler, the handling of announcement signatures and
545 // channel broadcasting may be done async, so just wait until the channel shows up.
546 assert use_nio_peer_handler;
549 ChannelInfo chan = graph.channel(channels[0]);
550 assert Arrays.equals(chan.get_node_one().as_slice(), chan.get_node_one().write());
551 assert Arrays.equals(chan.get_node_one().as_slice(), chan_manager.get_our_node_id()) ||
552 Arrays.equals(chan.get_node_two().as_slice(), chan_manager.get_our_node_id());
556 return UtilMethods.find_route(payer, params, net_graph, first_hops, logger, ScoreLookUp.new_impl(new ScoreLookUp.ScoreLookUpInterface() {
557 @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage, ProbabilisticScoringFeeParameters params) { return 0; }
558 }), ProbabilisticScoringFeeParameters.with_default(), new byte[32]);
561 this.setup_route_handler();
562 ChannelMonitor[] monitors = new ChannelMonitor[1];
563 assert orig.monitors.size() == 1;
564 if (!break_cross_peer_refs) {
565 monitors[0] = orig.monitors.values().stream().iterator().next();
567 byte[] serialized = orig.monitors.values().stream().iterator().next().write();
568 Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ res =
569 UtilMethods.C2Tuple_ThirtyTwoBytesChannelMonitorZ_read(serialized, this.entropy_source, this.signer_provider);
570 assert res instanceof Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK;
571 monitors[0] = ((Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelMonitorZDecodeErrorZ_OK) res).res.get_b();
573 byte[] serialized = orig.chan_manager.write();
574 Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ read_res =
575 UtilMethods.C2Tuple_ThirtyTwoBytesChannelManagerZ_read(serialized, this.entropy_source, this.node_signer, this.signer_provider, this.fee_estimator, this.chain_watch, this.tx_broadcaster, router, this.logger, get_config(), monitors);
576 assert read_res instanceof Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ_OK;
577 this.chan_manager = ((Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ.Result_C2Tuple_ThirtyTwoBytesChannelManagerZDecodeErrorZ_OK) read_res).res.get_b();
578 this.chain_watch.watch_channel(monitors[0].get_funding_txo().get_a(), monitors[0]);
579 this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), route_handler.as_RoutingMessageHandler(),
580 IgnoringMessageHandler.of().as_OnionMessageHandler(), this.custom_message_handler,
581 (int)(System.currentTimeMillis() / 1000), this.entropy_source.get_secure_random_bytes(),
582 logger, this.node_signer);
583 if (!break_cross_peer_refs && (use_manual_watch || use_km_wrapper)) {
584 // When we pass monitors[0] into chain_watch.watch_channel we create a reference from the new Peer to a
585 // field in the old peer, preventing freeing of the original Peer until the new Peer is freed. Thus, we
586 // shouldn't bother waiting for the original to be freed later on.
587 cross_reload_ref_pollution = true;
590 this.node_id = chan_manager.get_our_node_id();
593 if (cross_reload_ref_pollution) {
594 // This really, really needs to be handled at the bindings layer, but its rather complicated -
595 // ChannelSigners can be cloned and passed around without java being involved, resulting in them being
596 // owned by both one or more ChannelMonitors and a ChannelManager, with only one having proper pointers
597 // to the ChannelSigner. Ideally, the ChannelSigner would have a global reference to the Java
598 // implementation class, but that results in circular references. Instead, we need some ability to,
599 // while cloning ChannelSigners, add new references in the calling Java struct (ie ChannelMonitor) to
600 // the ChannelSigner.
601 this.ptr_to = orig.chan_manager;
606 TwoTuple_ThirtyTwoBytesCVec_C2Tuple_u32TxOutZZZ[] connect_block(Block b, int height, long expected_monitor_update_len) {
607 byte[] header = Arrays.copyOfRange(b.bitcoinSerialize(), 0, 80);
608 TwoTuple_usizeTransactionZ[] txn;
609 if (b.hasTransactions()) {
610 assert b.getTransactions().size() == 1;
611 TwoTuple_usizeTransactionZ txp = TwoTuple_usizeTransactionZ.of((long) 0, b.getTransactions().get(0).bitcoinSerialize());
612 txn = new TwoTuple_usizeTransactionZ[]{txp};
614 txn = new TwoTuple_usizeTransactionZ[0];
615 if (chain_monitor != null) {
616 chan_manager.as_Listen().block_connected(b.bitcoinSerialize(), height);
617 chain_monitor.as_Listen().block_connected(b.bitcoinSerialize(), height);
619 chan_manager.as_Confirm().transactions_confirmed(header, txn, height);
620 chan_manager.as_Confirm().best_block_updated(header, height);
621 // Connect manually if we aren't using a ChainMonitor and are implementing Watch ourselves
622 synchronized (monitors) {
623 assert monitors.size() == 1;
624 for (ChannelMonitor mon : monitors.values()) {
625 TwoTuple_ThirtyTwoBytesCVec_C2Tuple_u32TxOutZZZ[] ret = mon.block_connected(header, txn, height, tx_broadcaster, fee_estimator, logger);
626 assert ret.length == expected_monitor_update_len;
634 Event[] get_monitor_events(int expected_len) {
635 if (use_chan_manager_constructor) {
637 synchronized (this.pending_manager_events) {
638 if (expected_len != 0 && this.pending_manager_events.size() == expected_len) {
642 if (expected_len == 0) {
643 try { Thread.sleep(500); } catch (InterruptedException e) { assert false; }
649 synchronized (this.pending_manager_events) {
650 Event[] res = this.pending_manager_events.toArray(new Event[0]);
651 this.pending_manager_events.clear();
652 assert res.length == expected_len;
655 } else if (chain_monitor != null) {
656 ArrayList<Event> l = new ArrayList<Event>();
657 chain_monitor.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
658 assert l.size() == expected_len;
659 return l.toArray(new Event[0]);
661 synchronized (monitors) {
662 assert monitors.size() == 1;
663 for (ChannelMonitor mon : monitors.values()) {
664 ArrayList<Event> res = new ArrayList<Event>();
665 EventHandler handler = EventHandler.new_impl(new EventHandler.EventHandlerInterface() {
666 @Override public void handle_event(Event event) {
670 mon.process_pending_events(handler);
671 assert res.size() == expected_len;
672 return res.toArray(new Event[0]);
679 Event[] get_manager_events(int expected_len, Peer peer1, Peer peer2) {
680 assert expected_len != 0;
681 if (!use_nio_peer_handler) {
682 maybe_exchange_peer_messages(peer1, peer2);
684 Event[] res = new Event[0];
685 if (use_chan_manager_constructor) {
686 while (res.length < expected_len) {
687 synchronized (this.pending_manager_events) {
688 if (this.pending_manager_events.size() >= expected_len) {
689 res = this.pending_manager_events.toArray(res);
690 assert res.length == expected_len;
691 this.pending_manager_events.clear();
693 if (res.length < expected_len) {
694 try { this.pending_manager_events.wait(); } catch (InterruptedException e) { assert false; }
699 ArrayList<Event> l = new ArrayList<Event>();
700 while (l.size() < expected_len) {
702 if (use_nio_peer_handler) {
703 peer1.nio_peer_handler.check_events();
704 peer2.nio_peer_handler.check_events();
706 chan_manager.as_EventsProvider().process_pending_events(EventHandler.new_impl(l::add));
708 return l.toArray(new Event[0]);
710 assert res.length == expected_len;
715 static class DescriptorHolder { SocketDescriptor val; }
717 boolean running = false;
718 final LinkedList<Runnable> runqueue = new LinkedList();
720 Thread t = new Thread(() -> {
724 synchronized (runqueue) {
725 while (runqueue.isEmpty()) {
729 r = runqueue.pollFirst();
732 synchronized (runqueue) {
734 runqueue.notifyAll();
736 } catch (InterruptedException e) {
742 void maybe_exchange_peer_messages(Peer peer1, Peer peer2) {
743 if (!use_nio_peer_handler) {
745 peer1.peer_manager.process_events();
746 peer2.peer_manager.process_events();
747 synchronized (runqueue) {
748 if (runqueue.isEmpty() && !running) {
754 try { runqueue.wait(); } catch (InterruptedException e) { assert false; }
757 } else if (!use_chan_manager_constructor) {
758 peer1.nio_peer_handler.check_events();
759 peer2.nio_peer_handler.check_events();
762 void do_read_event(PeerManager pm, SocketDescriptor descriptor, byte[] data) {
763 if (!t.isAlive()) t.start();
764 synchronized (runqueue) {
767 Result_boolPeerHandleErrorZ res = pm.read_event(descriptor, data);
768 assert res instanceof Result_boolPeerHandleErrorZ.Result_boolPeerHandleErrorZ_OK;
770 runqueue.notifyAll();
772 must_free_objs.add(new WeakReference<>(data));
775 void connect_peers(final Peer peer1, final Peer peer2) {
776 peer2.connected_peer_node_id = peer1.node_id;
777 peer1.connected_peer_node_id = peer2.node_id;
778 if (use_nio_peer_handler) {
780 peer1.nio_peer_handler.connect(peer2.chan_manager.get_our_node_id(), new InetSocketAddress("127.0.0.1", peer2.nio_port), 100);
781 } catch (IOException e) { assert false; }
782 while (peer1.peer_manager.get_peer_node_ids().length == 0 || peer2.peer_manager.get_peer_node_ids().length == 0) {
786 DescriptorHolder descriptor1 = new DescriptorHolder();
787 DescriptorHolder descriptor1ref = descriptor1;
788 SocketDescriptor descriptor2 = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
790 public long send_data(byte[] data, boolean resume_read) {
791 do_read_event(peer1.peer_manager, descriptor1ref.val, data);
795 @Override public void disconnect_socket() { assert false; }
796 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == 2; }
797 @Override public long hash() { return 2; }
800 descriptor1.val = SocketDescriptor.new_impl(new SocketDescriptor.SocketDescriptorInterface() {
802 public long send_data(byte[] data, boolean resume_read) {
803 do_read_event(peer2.peer_manager, descriptor2, data);
807 @Override public void disconnect_socket() { assert false; }
808 @Override public boolean eq(SocketDescriptor other_arg) { return other_arg.hash() == 1; }
809 @Override public long hash() { return 1; }
812 Result_CVec_u8ZPeerHandleErrorZ conn_res = peer1.peer_manager.new_outbound_connection(peer2.node_id, descriptor1.val, Option_SocketAddressZ.none());
813 assert conn_res instanceof Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK;
815 Result_NonePeerHandleErrorZ inbound_conn_res = peer2.peer_manager.new_inbound_connection(descriptor2, Option_SocketAddressZ.none());
816 assert inbound_conn_res instanceof Result_NonePeerHandleErrorZ.Result_NonePeerHandleErrorZ_OK;
817 do_read_event(peer2.peer_manager, descriptor2, ((Result_CVec_u8ZPeerHandleErrorZ.Result_CVec_u8ZPeerHandleErrorZ_OK) conn_res).res);
819 maybe_exchange_peer_messages(peer1, peer2);
823 TestState do_test_message_handler() throws InterruptedException {
824 Peer peer1 = new Peer((byte) 1);
825 Peer peer2 = new Peer((byte) 2);
827 connect_peers(peer1, peer2);
829 UInt128 user_id = new UInt128(new byte[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16});
831 Result_ThirtyTwoBytesAPIErrorZ cc_res = peer1.chan_manager.create_channel(peer2.node_id, 100000, 1000, user_id, null);
832 assert cc_res instanceof Result_ThirtyTwoBytesAPIErrorZ.Result_ThirtyTwoBytesAPIErrorZ_OK;
834 // Previously, this was a SEGFAULT instead of get_funding_txo() returning null.
835 ChannelDetails pre_funding_chan = peer1.chan_manager.list_channels()[0];
836 assert pre_funding_chan.get_funding_txo() == null;
838 Event[] events = peer1.get_manager_events(1, peer1, peer2);
839 assert events[0] instanceof Event.FundingGenerationReady;
840 assert ((Event.FundingGenerationReady) events[0]).channel_value_satoshis == 100000;
841 assert ((Event.FundingGenerationReady) events[0]).user_channel_id.equals(user_id);
842 byte[] funding_spk = ((Event.FundingGenerationReady) events[0]).output_script;
843 assert funding_spk.length == 34 && funding_spk[0] == 0 && funding_spk[1] == 32; // P2WSH
844 byte[] chan_id = ((Event.FundingGenerationReady) events[0]).temporary_channel_id;
846 BitcoinNetworkParams bitcoinj_net = BitcoinNetworkParams.of(BitcoinNetwork.MAINNET);
848 Transaction funding_input = new Transaction(bitcoinj_net);
849 funding_input.addOutput(Coin.SATOSHI.multiply(100000), new Script(funding_spk));
850 Transaction funding = new Transaction(bitcoinj_net);
851 funding.addInput(funding_input.getOutput(0));
852 funding.getInputs().get(0).setWitness(new TransactionWitness(2)); // Make sure we don't complain about lack of witness
853 funding.getInput(0).getWitness().setPush(0, new byte[]{0x1});
854 funding.addOutput(Coin.SATOSHI.multiply(100000), new Script(funding_spk));
855 Result_NoneAPIErrorZ funding_res = peer1.chan_manager.funding_transaction_generated(chan_id, peer2.node_id, funding.bitcoinSerialize());
856 assert funding_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
858 gossip_txout = new TxOut(100000, funding_spk);
860 maybe_exchange_peer_messages(peer1, peer2);
861 synchronized (peer1.broadcast_set) {
862 while (peer1.broadcast_set.size() != 1) {
863 peer1.broadcast_set.wait();
867 events = peer1.get_manager_events(1, peer1, peer2);
868 assert events[0] instanceof Event.ChannelPending;
870 events = peer2.get_manager_events(1, peer1, peer2);
871 assert events[0] instanceof Event.ChannelPending;
873 assert peer1.broadcast_set.size() == 1;
874 assert Arrays.equals(peer1.broadcast_set.get(0), funding.bitcoinSerialize());
875 peer1.broadcast_set.clear();
877 Block b = new Block(bitcoinj_net, 2, Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[]{funding}));
878 peer1.connect_block(b, 1, 0);
879 peer2.connect_block(b, 1, 0);
881 for (int height = 2; height < 10; height++) {
882 b = new Block(bitcoinj_net, 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[0]));
883 peer1.connect_block(b, height, 0);
884 peer2.connect_block(b, height, 0);
887 maybe_exchange_peer_messages(peer1, peer2);
888 while (peer1.chan_manager.list_usable_channels().length != 1 || peer2.chan_manager.list_usable_channels().length != 1) ;
890 events = peer1.get_manager_events(1, peer1, peer2);
891 assert events[0] instanceof Event.ChannelReady;
893 events = peer2.get_manager_events(1, peer1, peer2);
894 assert events[0] instanceof Event.ChannelReady;
896 ChannelDetails[] peer1_chans = peer1.chan_manager.list_usable_channels();
897 ChannelDetails[] peer2_chans = peer2.chan_manager.list_usable_channels();
898 assert peer1_chans.length == 1;
899 assert peer2_chans.length == 1;
900 assert peer1_chans[0].get_channel_value_satoshis() == 100000;
901 assert peer1_chans[0].get_is_usable();
902 Option_u64Z short_chan_id = peer1_chans[0].get_short_channel_id();
903 assert short_chan_id instanceof Option_u64Z.Some;
904 assert ((Option_u64Z.Some)short_chan_id).some == (1L << 40); // 0th output in the 0th transaction in the 1st block
905 assert Arrays.equals(peer1_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
906 assert Arrays.equals(peer2_chans[0].get_channel_id(), funding.getTxId().getReversedBytes());
908 Result_Bolt11InvoiceSignOrCreationErrorZ invoice = UtilMethods.create_invoice_from_channelmanager(peer2.chan_manager, peer2.node_signer, peer2.logger, Currency.LDKCurrency_Bitcoin, Option_u64Z.some(10000000), "Invoice Description", 7200, Option_u16Z.none());
909 assert invoice instanceof Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK;
910 System.out.println("Got invoice: " + ((Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
912 Result_Bolt11InvoiceParseOrSemanticErrorZ parsed_invoice = Bolt11Invoice.from_str(((Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str());
913 assert parsed_invoice instanceof Result_Bolt11InvoiceParseOrSemanticErrorZ.Result_Bolt11InvoiceParseOrSemanticErrorZ_OK;
914 //assert ((Result_Bolt11InvoiceParseOrSemanticErrorZ.Result_Bolt11InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res.fallback_addresses().length == 0;
915 assert Arrays.equals(((Result_Bolt11InvoiceParseOrSemanticErrorZ.Result_Bolt11InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res.payment_hash(), ((Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_hash());
916 SignedRawBolt11Invoice signed_raw = ((Result_Bolt11InvoiceParseOrSemanticErrorZ.Result_Bolt11InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res.into_signed_raw();
917 RawBolt11Invoice raw_invoice = signed_raw.raw_invoice();
918 byte[] desc_hash = raw_invoice.signable_hash();
919 Description raw_invoice_description = raw_invoice.description();
920 String description_string = raw_invoice_description.into_inner();
921 assert description_string.equals("Invoice Description");
923 // Do a trivial test of constructing a phantom invoice
924 Result_Bolt11InvoiceSignOrCreationErrorZ phantom_invoice = UtilMethods.create_phantom_invoice(
925 Option_u64Z.some(42000),
926 Option_ThirtyTwoBytesZ.none(),
927 "Phantom Invoice", 7200,
928 new PhantomRouteHints[]{ peer2.chan_manager.get_phantom_route_hints() },
929 peer2.entropy_source,
930 PhantomKeysManager.of(peer2.key_seed, 42, 42, new byte[32]).as_NodeSigner(),
931 peer2.logger, Currency.LDKCurrency_Bitcoin, Option_u16Z.none(),
932 System.currentTimeMillis() / 1000);
933 assert phantom_invoice.is_ok();
934 RouteHint[] hints = ((Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK)phantom_invoice).res.route_hints();
935 assert hints.length == 1;
936 RouteHintHop[] val = hints[0].get_a();
937 assert hints[0].get_a().length == 1; // Our one channel is public so we should just have a single-hop hint
939 if (!use_invoice_payer) {
940 byte[] payment_hash = ((Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_hash();
941 byte[] payment_secret = ((Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK) invoice).res.payment_secret();
942 byte[] dest_node_id = ((Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK) invoice).res.recover_payee_pub_key();
943 assert Arrays.equals(dest_node_id, peer2.node_id);
944 Bolt11InvoiceFeatures invoice_features = ((Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK) invoice).res.features();
945 RouteHint[] route_hints = ((Result_Bolt11InvoiceSignOrCreationErrorZ.Result_Bolt11InvoiceSignOrCreationErrorZ_OK) invoice).res.route_hints();
947 Payee payee = Payee.clear(peer2.node_id, route_hints, invoice_features, 42);
948 PaymentParameters pay_params = PaymentParameters.of(payee, Option_u64Z.none(), 6*24*14, (byte)1, (byte)2, new long[0]);
949 RouteParameters route_params = RouteParameters.from_payment_params_and_value(pay_params, 10000000);
950 Result_RouteLightningErrorZ route_res = UtilMethods.find_route(
951 peer1.chan_manager.get_our_node_id(), route_params, peer1.net_graph,
952 peer1_chans, peer1.logger,
953 ProbabilisticScorer.of(ProbabilisticScoringDecayParameters.with_default(), peer1.net_graph, peer1.logger).as_ScoreLookUp(),
954 ProbabilisticScoringFeeParameters.with_default(), new byte[32]);
955 assert route_res instanceof Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK;
956 Route route = ((Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK) route_res).res;
957 assert route.get_paths().length == 1;
958 assert route.get_paths()[0].get_hops().length == 1;
959 assert route.get_paths()[0].final_value_msat() == 10000000;
961 byte[] payment_id = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 };
962 Result_NonePaymentSendFailureZ payment_res = peer1.chan_manager.send_payment_with_route(route, payment_hash, RecipientOnionFields.secret_only(payment_secret), payment_id);
963 assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_OK;
965 RouteHop[] hops = new RouteHop[1];
966 byte[] hop_pubkey = new byte[33];
969 NodeFeatures node_features = NodeFeatures.empty();
970 ChannelFeatures channel_features = ChannelFeatures.empty();
971 hops[0] = RouteHop.of(hop_pubkey, node_features, 42, channel_features, 100, 0, false);
972 Path[] paths = new Path[1];
973 paths[0] = Path.of(hops, null);
974 Route r2 = Route.of(paths, RouteParameters.from_payment_params_and_value(pay_params, 100));
975 payment_res = peer1.chan_manager.send_payment_with_route(r2, payment_hash, RecipientOnionFields.secret_only(payment_secret), payment_id);
976 assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_Err;
978 Result_ThirtyTwoBytesPaymentErrorZ send_res = UtilMethods.pay_invoice(((Result_Bolt11InvoiceParseOrSemanticErrorZ.Result_Bolt11InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res, Retry.attempts(0), peer1.chan_manager);
979 assert send_res instanceof Result_ThirtyTwoBytesPaymentErrorZ.Result_ThirtyTwoBytesPaymentErrorZ_OK;
983 assert peer1.network_graph_persists == 0;
984 assert peer2.network_graph_persists == 0;
985 if (use_chan_manager_constructor) {
986 peer1.constructor.interrupt();
987 peer2.constructor.interrupt();
988 if (!use_ignore_handler) {
989 assert peer1.network_graph_persists >= 1;
990 assert peer2.network_graph_persists >= 1;
992 assert peer1.network_graph_persists == 0;
993 assert peer2.network_graph_persists == 0;
995 } else if (use_nio_peer_handler) {
996 peer1.nio_peer_handler.interrupt();
997 peer2.nio_peer_handler.interrupt();
999 WeakReference<Peer> op1 = new WeakReference<Peer>(peer1);
1000 peer1 = new Peer(peer1);
1001 peer2 = new Peer(peer2);
1002 return new TestState(op1, peer1, peer2, b.getHash());
1004 return new TestState(null, peer1, peer2, b.getHash());
1007 boolean cross_reload_ref_pollution = false;
1009 private final WeakReference<Peer> ref_block;
1010 private final Peer peer1;
1011 private final Peer peer2;
1012 public Sha256Hash best_blockhash;
1014 public TestState(WeakReference<Peer> ref_block, Peer peer1, Peer peer2, Sha256Hash best_blockhash) {
1015 this.ref_block = ref_block;
1018 this.best_blockhash = best_blockhash;
1021 void do_test_message_handler_b(TestState state) throws Exception {
1022 GcCheck obj = new GcCheck();
1023 if (state.ref_block != null) {
1024 // Ensure the original peers get freed before we move on. Note that we have to be in a different function
1025 // scope to do so as the (at least current OpenJDK) JRE won't release anything created in the same scope.
1026 while (!cross_reload_ref_pollution && state.ref_block.get() != null) {
1028 System.runFinalization();
1030 connect_peers(state.peer1, state.peer2);
1033 Event[] events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
1034 assert events[0] instanceof Event.PendingHTLCsForwardable;
1035 state.peer2.chan_manager.process_pending_htlc_forwards();
1037 events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
1038 assert events[0] instanceof Event.PaymentClaimable;
1039 assert ((Event.PaymentClaimable)events[0]).purpose instanceof PaymentPurpose.InvoicePayment;
1040 assert ((PaymentPurpose.InvoicePayment) ((Event.PaymentClaimable)events[0]).purpose).payment_preimage instanceof Option_ThirtyTwoBytesZ.Some;
1041 byte[] payment_preimage = ((Option_ThirtyTwoBytesZ.Some) ((PaymentPurpose.InvoicePayment)((Event.PaymentClaimable)events[0]).purpose).payment_preimage).some;
1042 assert !Arrays.equals(payment_preimage, new byte[32]);
1043 state.peer2.chan_manager.claim_funds(payment_preimage);
1045 events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
1046 assert events[0] instanceof Event.PaymentClaimed;
1047 assert ((Event.PaymentClaimed)events[0]).purpose instanceof PaymentPurpose.InvoicePayment;
1048 assert ((PaymentPurpose.InvoicePayment) ((Event.PaymentClaimed)events[0]).purpose).payment_preimage instanceof Option_ThirtyTwoBytesZ.Some;
1049 payment_preimage = ((Option_ThirtyTwoBytesZ.Some)((PaymentPurpose.InvoicePayment)((Event.PaymentClaimed)events[0]).purpose).payment_preimage).some;
1050 assert !Arrays.equals(payment_preimage, new byte[32]);
1052 events = state.peer1.get_manager_events(2, state.peer1, state.peer2);
1053 assert events[0] instanceof Event.PaymentSent;
1054 assert Arrays.equals(((Event.PaymentSent) events[0]).payment_preimage, payment_preimage);
1055 assert events[1] instanceof Event.PaymentPathSuccessful;
1056 assert ((Event.PaymentPathSuccessful) events[1]).payment_hash instanceof Option_ThirtyTwoBytesZ.Some;
1057 assert Arrays.equals(((Option_ThirtyTwoBytesZ.Some) ((Event.PaymentPathSuccessful) events[1]).payment_hash).some, ((Event.PaymentSent) events[0]).payment_hash);
1059 if (use_nio_peer_handler) {
1060 // We receive PaymentSent immediately upon receipt of the payment preimage, but we expect to not have an
1061 // HTLC transaction to broadcast below, which requires a bit more time to fully complete the
1062 // commitment-transaction-update dance between both peers.
1066 if (state.peer1.chain_monitor != null) {
1067 Balance[] peer1_balances = state.peer1.chain_monitor.get_claimable_balances(state.peer1.chan_manager.list_channels());
1068 assert peer1_balances.length == 0;
1069 Balance[] peer2_balances = state.peer2.chain_monitor.get_claimable_balances(state.peer2.chan_manager.list_channels());
1070 assert peer2_balances.length == 0;
1073 ChannelDetails[] peer1_chans = state.peer1.chan_manager.list_channels();
1076 Result_NoneAPIErrorZ close_res = state.peer1.chan_manager.close_channel(peer1_chans[0].get_channel_id(), state.peer2.node_id);
1077 assert close_res instanceof Result_NoneAPIErrorZ.Result_NoneAPIErrorZ_OK;
1078 maybe_exchange_peer_messages(state.peer1, state.peer2);
1079 synchronized (state.peer1.broadcast_set) {
1080 while (state.peer1.broadcast_set.size() != 1) state.peer1.broadcast_set.wait();
1082 synchronized (state.peer2.broadcast_set) {
1083 while (state.peer2.broadcast_set.size() != 1) state.peer2.broadcast_set.wait();
1086 state.peer1.chan_manager.force_close_all_channels_broadcasting_latest_txn();
1087 maybe_exchange_peer_messages(state.peer1, state.peer2);
1088 synchronized (state.peer1.broadcast_set) {
1089 while (state.peer1.broadcast_set.size() != 1) state.peer1.broadcast_set.wait();
1091 synchronized (state.peer2.broadcast_set) {
1092 while (state.peer2.broadcast_set.size() != 1) state.peer2.broadcast_set.wait();
1096 assert state.peer1.broadcast_set.size() == 1;
1097 assert state.peer2.broadcast_set.size() == 1;
1099 events = state.peer2.get_manager_events(1, state.peer1, state.peer2);
1100 assert events[0] instanceof Event.ChannelClosed;
1101 events = state.peer1.get_manager_events(1, state.peer1, state.peer2);
1102 assert events[0] instanceof Event.ChannelClosed;
1104 if (state.peer1.chain_monitor != null) {
1105 Balance[] peer1_balances = state.peer1.chain_monitor.get_claimable_balances(state.peer1.chan_manager.list_channels());
1106 assert peer1_balances.length == 1;
1107 for (Balance bal : peer1_balances) {
1108 assert bal instanceof Balance.ClaimableOnChannelClose;
1109 long expected_tx_fee = 183;
1110 assert ((Balance.ClaimableOnChannelClose) bal).amount_satoshis == 100000 - 1 - 10000 - expected_tx_fee;
1112 Balance[] peer2_balances = state.peer2.chain_monitor.get_claimable_balances(state.peer2.chan_manager.list_channels());
1113 assert peer2_balances.length == 1;
1114 for (Balance bal : peer2_balances) {
1115 assert bal instanceof Balance.ClaimableOnChannelClose;
1116 assert ((Balance.ClaimableOnChannelClose) bal).amount_satoshis == 10000 + 1;
1121 BitcoinNetworkParams bitcoinj_net = BitcoinNetworkParams.of(BitcoinNetwork.MAINNET);
1122 Transaction tx = new Transaction(bitcoinj_net, state.peer1.broadcast_set.getFirst());
1123 Block b = new Block(bitcoinj_net, 2, state.best_blockhash, Sha256Hash.ZERO_HASH, 42, 0, 0,
1124 Arrays.asList(new Transaction[]{tx}));
1125 TwoTuple_ThirtyTwoBytesCVec_C2Tuple_u32TxOutZZZ[] watch_outputs = state.peer2.connect_block(b, 10, 1);
1126 if (watch_outputs != null) { // We only process watch_outputs manually when we use a manually-build Watch impl
1127 assert watch_outputs.length == 1;
1128 assert Arrays.equals(watch_outputs[0].get_a(), tx.getTxId().getReversedBytes());
1129 assert watch_outputs[0].get_b().length == 2;
1130 assert watch_outputs[0].get_b()[0].get_a() == 0;
1131 assert watch_outputs[0].get_b()[1].get_a() == 1;
1134 for (int i = 11; i < 21; i++) {
1135 b = new Block(bitcoinj_net, 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, new ArrayList<>());
1136 state.peer2.connect_block(b, i, 0);
1139 Event[] broadcastable_event = state.peer2.get_monitor_events(1);
1140 for (ChannelMonitor mon : state.peer2.monitors.values()) {
1141 // This used to be buggy and double-free, so go ahead and fetch them!
1142 byte[][] txn = mon.get_latest_holder_commitment_txn(state.peer2.logger);
1144 assert broadcastable_event.length == 1;
1145 assert broadcastable_event[0] instanceof Event.SpendableOutputs;
1146 if (state.peer2.explicit_keys_manager != null) {
1147 TxOut[] additional_outputs = new TxOut[]{new TxOut(420, new byte[]{0x42})};
1148 Result_TransactionNoneZ tx_res = state.peer2.explicit_keys_manager.spend_spendable_outputs(((Event.SpendableOutputs) broadcastable_event[0]).outputs, additional_outputs, new byte[]{0x00}, 253, Option_u32Z.none());
1149 assert tx_res instanceof Result_TransactionNoneZ.Result_TransactionNoneZ_OK;
1150 Transaction built_tx = new Transaction(bitcoinj_net, ((Result_TransactionNoneZ.Result_TransactionNoneZ_OK) tx_res).res);
1151 assert built_tx.getOutputs().size() == 2;
1152 assert Arrays.equals(built_tx.getOutput(1).getScriptBytes(), new byte[]{0x00});
1153 assert Arrays.equals(built_tx.getOutput(0).getScriptBytes(), new byte[]{0x42});
1154 assert built_tx.getOutput(0).getValue().value == 420;
1158 // Test exchanging a custom message (note that ChannelManagerConstructor) always loads an IgnorimgMessageHandler
1159 // so we cannot exchange custom messages with it
1160 if (!use_chan_manager_constructor) {
1161 byte[] custom_message_bytes = new byte[]{0x42, 0x44, 0x43, 0x00};
1162 synchronized(state.peer1.custom_messages_to_send) {
1163 state.peer1.custom_messages_to_send.add(custom_message_bytes);
1165 state.peer1.peer_manager.process_events();
1166 synchronized (state.peer2.received_custom_messages) {
1168 if (state.peer2.received_custom_messages.isEmpty()) {
1169 state.peer2.received_custom_messages.wait();
1172 assert state.peer2.received_custom_messages.size() == 1;
1173 assert Arrays.equals(state.peer2.received_custom_messages.get(0), custom_message_bytes);
1179 if (use_nio_peer_handler) {
1180 state.peer1.peer_manager.disconnect_by_node_id(state.peer2.chan_manager.get_our_node_id());
1181 while (state.peer1.peer_manager.get_peer_node_ids().length != 0) Thread.yield();
1182 while (state.peer2.peer_manager.get_peer_node_ids().length != 0) Thread.yield();
1183 state.peer1.nio_peer_handler.interrupt();
1184 state.peer2.nio_peer_handler.interrupt();
1187 state.peer1.get_monitor_events(0);
1188 state.peer2.get_monitor_events(0);
1190 if (use_chan_manager_constructor) {
1191 assert state.peer1.network_graph_persists == 0;
1192 assert state.peer2.network_graph_persists == 0;
1193 state.peer1.constructor.interrupt();
1194 state.peer2.constructor.interrupt();
1195 if (!use_ignore_handler) {
1196 assert state.peer1.network_graph_persists >= 1;
1197 assert state.peer2.network_graph_persists >= 1;
1199 assert state.peer1.network_graph_persists == 0;
1200 assert state.peer2.network_graph_persists == 0;
1206 if (state.peer1.net_graph != null)
1207 state.peer1.net_graph.write();
1209 // Construct the only Option_Enum::Variant(OpaqueStruct) we have in the codebase as this used to cause double-frees:
1210 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};
1211 Result_ChannelUpdateDecodeErrorZ upd_msg = ChannelUpdate.read(serd);
1212 assert upd_msg instanceof Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK;
1213 assert ((Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK) upd_msg).res.get_contents().get_htlc_maximum_msat() == 0xdeadbeef42424242L;
1214 Option_NetworkUpdateZ upd = Option_NetworkUpdateZ.some(NetworkUpdate.channel_update_message(((Result_ChannelUpdateDecodeErrorZ.Result_ChannelUpdateDecodeErrorZ_OK) upd_msg).res));
1216 if (use_chan_manager_constructor) {
1217 // Lock the scorer twice back-to-back to check that the try-with-resources AutoCloseable on the scorer works.
1218 try (ChannelManagerConstructor.ScorerWrapper score = state.peer1.constructor.get_locked_scorer()) {
1219 score.prob_scorer.debug_log_liquidity_stats();
1224 java.util.LinkedList<WeakReference<Object>> must_free_objs = new java.util.LinkedList();
1226 int gc_exp_count = 0;
1228 GcCheck() { gc_exp_count += 1; }
1230 protected void finalize() throws Throwable {
1236 public class HumanObjectPeerTest {
1237 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 Exception {
1238 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);
1239 HumanObjectPeerTestInstance.TestState state = instance.do_test_message_handler();
1240 instance.do_test_message_handler_b(state);
1243 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 Exception {
1244 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);
1245 while (instance.gc_count != instance.gc_exp_count) {
1247 System.runFinalization();
1249 for (WeakReference<Object> o : instance.must_free_objs)
1250 assert o.get() == null;
1252 public static final int TEST_ITERATIONS = (1 << 9);
1253 public static void do_test_message_handler(IntConsumer statusFunction) throws Exception {
1254 Thread gc_thread = new Thread(() -> {
1257 System.runFinalization();
1258 try { Thread.sleep(0, 1); } catch (InterruptedException e) { break; }
1260 }, "Test GC Thread");
1262 for (int i = 0; i < TEST_ITERATIONS; i++) {
1263 boolean nice_close = (i & (1 << 0)) != 0;
1264 boolean use_km_wrapper = (i & (1 << 1)) != 0;
1265 boolean use_manual_watch = (i & (1 << 2)) != 0;
1266 boolean reload_peers = (i & (1 << 3)) != 0;
1267 boolean break_cross_refs = (i & (1 << 4)) != 0;
1268 boolean use_ignoring_routing_handler = (i & (1 << 5)) != 0;
1269 boolean use_chan_manager_constructor = (i & (1 << 6)) != 0;
1270 boolean use_invoice_payer = (i & (1 << 7)) != 0;
1271 boolean nio_peer_handler = (i & (1 << 8)) != 0;
1272 if (break_cross_refs && !reload_peers) {
1273 // There are no cross refs to break without reloading peers.
1276 if (use_chan_manager_constructor && (use_manual_watch || !nio_peer_handler)) {
1277 // ChannelManagerConstructor requires a ChainMonitor as the Watch and creates a NioPeerHandler for us.
1280 if (!use_chan_manager_constructor && (use_ignoring_routing_handler)) {
1281 // We rely on the ChannelManagerConstructor to convert null into an IgnoringMessageHandler, so don't
1282 // try to run with an IgnoringMessageHandler unless we're also using a ChannelManagerConstructor.
1285 if (use_chan_manager_constructor && use_ignoring_routing_handler && use_invoice_payer) {
1286 // As documented on ChannelManagerConstructor, if we provide a `null` NetworkGraph (because we want to
1287 // use an IgnoringMessageHandler), no InvoicePayer will be constructored for us, thus we cannot use an
1288 // InvoicePayer to send payments in this case.
1291 if (use_chan_manager_constructor && use_km_wrapper) {
1292 // ChannelManagerConstructor requires a full KeysManager, so using wrapped keys interfaces doesn't make
1296 statusFunction.accept(i);
1297 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);
1299 gc_thread.interrupt();
1303 public void test_message_handler() throws Exception {
1304 do_test_message_handler(i -> System.err.println("Running test with flags " + i));
1307 // This is used in the test jar to test the built jar is runnable
1308 public static void main(String[] args) {
1310 do_test_message_handler(i -> System.err.println("Running test with flags " + i));
1311 } catch (Exception e) {
1312 System.err.println("Caught exception:");
1313 System.err.println(e);