From 53e12f51175b8266b0ea5a9978e782980014901b Mon Sep 17 00:00:00 2001 From: Matt Corallo Date: Wed, 8 Mar 2023 01:06:31 +0000 Subject: [PATCH] [Java] Update tests to latest (0.0.114) LDK API, rm non-hu ones The old non-human-object-based tests don't really have any business being held on to, so we simply remove them entirely here, relying on the `HumanObjectPeerTest` to do all our work. --- .../java/org/ldk/HumanObjectPeerTest.java | 412 ++++++++---------- .../org/ldk/ManualMsgHandlingPeerTest.java | 209 --------- src/test/java/org/ldk/PeerTest.java | 409 ----------------- 3 files changed, 191 insertions(+), 839 deletions(-) delete mode 100644 src/test/java/org/ldk/ManualMsgHandlingPeerTest.java delete mode 100644 src/test/java/org/ldk/PeerTest.java diff --git a/src/test/java/org/ldk/HumanObjectPeerTest.java b/src/test/java/org/ldk/HumanObjectPeerTest.java index fb28dae8..113eae90 100644 --- a/src/test/java/org/ldk/HumanObjectPeerTest.java +++ b/src/test/java/org/ldk/HumanObjectPeerTest.java @@ -44,100 +44,94 @@ class HumanObjectPeerTestInstance { } class Peer { - KeysInterface manual_keysif(KeysInterface underlying_if) { - return KeysInterface.new_impl(new KeysInterface.KeysInterfaceInterface() { - @Override public Result_SecretKeyNoneZ get_node_secret(Recipient recipient) { return underlying_if.get_node_secret(recipient); } - @Override public Result_PublicKeyNoneZ get_node_id(Recipient recipient) { return underlying_if.get_node_id(recipient); } - - @Override public Result_SharedSecretNoneZ ecdh(Recipient recipient, byte[] other_key, Option_ScalarZ tweak) { return underlying_if.ecdh(recipient, other_key, tweak); } - @Override public byte[] get_destination_script() { return underlying_if.get_destination_script(); } - @Override public ShutdownScript get_shutdown_scriptpubkey() { return underlying_if.get_shutdown_scriptpubkey(); } - + NodeSigner manual_node_signer(KeysManager underlying_km) { + NodeSigner underlying_ns = underlying_km.as_NodeSigner(); + must_free_objs.add(new WeakReference<>(underlying_ns)); + return NodeSigner.new_impl(new NodeSigner.NodeSignerInterface() { + @Override public byte[] get_inbound_payment_key_material() { return underlying_ns.get_inbound_payment_key_material(); } + @Override public Result_PublicKeyNoneZ get_node_id(Recipient recipient) { return underlying_ns.get_node_id(recipient); } + @Override public Result_SharedSecretNoneZ ecdh(Recipient recipient, byte[] other_key, Option_ScalarZ tweak) { + return underlying_ns.ecdh(recipient, other_key, tweak); + } + @Override public Result_RecoverableSignatureNoneZ sign_invoice(byte[] hrp_bytes, UInt5[] invoice_data, Recipient recipient) { + return underlying_ns.sign_invoice(hrp_bytes, invoice_data, recipient); + } + @Override public Result_SignatureNoneZ sign_gossip_message(UnsignedGossipMessage msg) { + return underlying_ns.sign_gossip_message(msg); + } + }); + } + SignerProvider manual_signer_provider(KeysManager underlying_km) { + SignerProvider underlying_sp = underlying_km.as_SignerProvider(); + must_free_objs.add(new WeakReference<>(underlying_sp)); + return SignerProvider.new_impl(new SignerProvider.SignerProviderInterface() { + @Override public byte[] get_destination_script() { return underlying_sp.get_destination_script(); } + @Override public ShutdownScript get_shutdown_scriptpubkey() { return underlying_sp.get_shutdown_scriptpubkey(); } @Override public byte[] generate_channel_keys_id(boolean inbound, long channel_value_satoshis, UInt128 user_channel_id) { - return underlying_if.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id); + return underlying_sp.generate_channel_keys_id(inbound, channel_value_satoshis, user_channel_id); } @Override - public Sign derive_channel_signer(long channel_value_satoshis, byte[] channel_keys_id) { - Sign underlying_ck = underlying_if.derive_channel_signer(channel_value_satoshis, channel_keys_id); - BaseSign underlying_base = underlying_ck.get_base_sign(); - BaseSign.BaseSignInterface bsi = new BaseSign.BaseSignInterface() { - @Override public byte[] get_per_commitment_point(long idx) { - return underlying_base.get_per_commitment_point(idx); - } - @Override public byte[] release_commitment_secret(long idx) { - return underlying_base.release_commitment_secret(idx); - } + public WriteableEcdsaChannelSigner derive_channel_signer(long channel_value_satoshis, byte[] channel_keys_id) { + WriteableEcdsaChannelSigner underlying_wecs = underlying_sp.derive_channel_signer(channel_value_satoshis, channel_keys_id); + EcdsaChannelSigner underlying_ecs = underlying_wecs.get_ecdsa_channel_signer(); + ChannelSigner underlying_cs = underlying_ecs.get_channel_signer(); + ChannelSigner.ChannelSignerInterface csi = new ChannelSigner.ChannelSignerInterface() { + @Override public byte[] get_per_commitment_point(long idx) { return underlying_cs.get_per_commitment_point(idx); } + @Override public byte[] release_commitment_secret(long idx) { return underlying_cs.release_commitment_secret(idx); } @Override public Result_NoneNoneZ validate_holder_commitment(HolderCommitmentTransaction holder_tx, byte[][] preimages) { - return underlying_base.validate_holder_commitment(holder_tx, preimages); + return underlying_cs.validate_holder_commitment(holder_tx, preimages); } - @Override public byte[] channel_keys_id() { - return channel_keys_id; + @Override public byte[] channel_keys_id() { return underlying_cs.channel_keys_id(); } + @Override public void provide_channel_parameters(ChannelTransactionParameters channel_parameters) { + underlying_cs.provide_channel_parameters(channel_parameters); } + }; + EcdsaChannelSigner.EcdsaChannelSignerInterface ecsi = new EcdsaChannelSigner.EcdsaChannelSignerInterface() { @Override public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_counterparty_commitment(CommitmentTransaction commitment_tx, byte[][] preimages) { - return underlying_base.sign_counterparty_commitment(commitment_tx, preimages); + return underlying_ecs.sign_counterparty_commitment(commitment_tx, preimages); } @Override public Result_NoneNoneZ validate_counterparty_revocation(long idx, byte[] secret) { - return underlying_base.validate_counterparty_revocation(idx, secret); + return underlying_ecs.validate_counterparty_revocation(idx, secret); } - @Override public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_holder_commitment_and_htlcs(HolderCommitmentTransaction holder_commitment_tx) { - return underlying_base.sign_holder_commitment_and_htlcs(holder_commitment_tx); + @Override public Result_C2Tuple_SignatureCVec_SignatureZZNoneZ sign_holder_commitment_and_htlcs(HolderCommitmentTransaction commitment_tx) { + return underlying_ecs.sign_holder_commitment_and_htlcs(commitment_tx); } @Override public Result_SignatureNoneZ sign_justice_revoked_output(byte[] justice_tx, long input, long amount, byte[] per_commitment_key) { - return underlying_base.sign_justice_revoked_output(justice_tx, input, amount, per_commitment_key); + return underlying_ecs.sign_justice_revoked_output(justice_tx, input, amount, per_commitment_key); } @Override public Result_SignatureNoneZ sign_justice_revoked_htlc(byte[] justice_tx, long input, long amount, byte[] per_commitment_key, HTLCOutputInCommitment htlc) { - return underlying_base.sign_justice_revoked_htlc(justice_tx, input, amount, per_commitment_key, htlc); + return underlying_ecs.sign_justice_revoked_htlc(justice_tx, input, amount, per_commitment_key, htlc); } @Override public Result_SignatureNoneZ sign_counterparty_htlc_transaction(byte[] htlc_tx, long input, long amount, byte[] per_commitment_point, HTLCOutputInCommitment htlc) { - return underlying_base.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc); + return underlying_ecs.sign_counterparty_htlc_transaction(htlc_tx, input, amount, per_commitment_point, htlc); } @Override public Result_SignatureNoneZ sign_closing_transaction(ClosingTransaction closing_tx) { - return underlying_base.sign_closing_transaction(closing_tx); + return underlying_ecs.sign_closing_transaction(closing_tx); } @Override public Result_SignatureNoneZ sign_holder_anchor_input(byte[] anchor_tx, long input) { - return underlying_base.sign_holder_anchor_input(anchor_tx, input); - } - @Override public Result_C2Tuple_SignatureSignatureZNoneZ sign_channel_announcement(UnsignedChannelAnnouncement msg) { - return underlying_base.sign_channel_announcement(msg); + return underlying_ecs.sign_holder_anchor_input(anchor_tx, input); } - - @Override public void provide_channel_parameters(ChannelTransactionParameters channel_parameters) { - underlying_base.provide_channel_parameters(channel_parameters); + @Override public Result_SignatureNoneZ sign_channel_announcement_with_funding_key(UnsignedChannelAnnouncement msg) { + return underlying_ecs.sign_channel_announcement_with_funding_key(msg); } }; - Sign.SignInterface si = new Sign.SignInterface() { - @Override - public byte[] write() { - return underlying_ck.write(); - } + WriteableEcdsaChannelSigner.WriteableEcdsaChannelSignerInterface wecsi = new WriteableEcdsaChannelSigner.WriteableEcdsaChannelSignerInterface() { + @Override public byte[] write() { return underlying_wecs.write(); } }; - Sign resp = Sign.new_impl(si, bsi, underlying_base.get_pubkeys()); - must_free_objs.add(new WeakReference<>(si)); - must_free_objs.add(new WeakReference<>(bsi)); + WriteableEcdsaChannelSigner resp = WriteableEcdsaChannelSigner.new_impl(wecsi, ecsi, csi, underlying_cs.get_pubkeys()); + must_free_objs.add(new WeakReference<>(wecsi)); + must_free_objs.add(new WeakReference<>(ecsi)); + must_free_objs.add(new WeakReference<>(csi)); must_free_objs.add(new WeakReference<>(resp)); - must_free_objs.add(new WeakReference<>(underlying_base)); - must_free_objs.add(new WeakReference<>(underlying_ck)); + must_free_objs.add(new WeakReference<>(underlying_wecs)); + must_free_objs.add(new WeakReference<>(underlying_ecs)); + must_free_objs.add(new WeakReference<>(underlying_cs)); return resp; } @Override - public byte[] get_secure_random_bytes() { - return underlying_if.get_secure_random_bytes(); - } - - @Override - public Result_SignDecodeErrorZ read_chan_signer(byte[] reader) { - return underlying_if.read_chan_signer(reader); - } - - @Override - public Result_RecoverableSignatureNoneZ sign_invoice(byte[] hrp_bytes, UInt5[] invoice_data, Recipient receipient) { - return underlying_if.sign_invoice(hrp_bytes, invoice_data, receipient); - } - - @Override - public byte[] get_inbound_payment_key_material() { - return underlying_if.get_inbound_payment_key_material(); + public Result_WriteableEcdsaChannelSignerDecodeErrorZ read_chan_signer(byte[] reader) { + return underlying_sp.read_chan_signer(reader); } }); } @@ -195,9 +189,11 @@ class HumanObjectPeerTestInstance { final FeeEstimator fee_estimator; final BroadcasterInterface tx_broadcaster; final KeysManager explicit_keys_manager; - final KeysInterface keys_interface; + final NodeSigner node_signer; + final SignerProvider signer_provider; + final EntropySource entropy_source; final ChainMonitor chain_monitor; - NetworkGraph router; + NetworkGraph net_graph; P2PGossipSync route_handler; final Watch chain_watch; final HashSet filter_additions; @@ -213,14 +209,13 @@ class HumanObjectPeerTestInstance { final LinkedList received_custom_messages = new LinkedList<>(); final LinkedList custom_messages_to_send = new LinkedList<>(); ChannelManagerConstructor constructor = null; - InvoicePayer payer = null; GcCheck obj = new GcCheck(); private ChannelMonitor test_mon_roundtrip(OutPoint expected_id, byte[] data) { // Because get_funding_txo() returns an OutPoint in a tuple that is a reference to an OutPoint inside the // ChannelMonitor, its a good test to ensure that the OutPoint isn't freed (or is cloned) before the // ChannelMonitor is. This used to be broken. - Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_monitor = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(data, keys_interface); + Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_monitor = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(data, this.entropy_source, this.signer_provider); assert roundtrip_monitor instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK; must_free_objs.add(new WeakReference<>(roundtrip_monitor)); TwoTuple_OutPointScriptZ funding_txo = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_monitor).res.get_b().get_funding_txo(); @@ -228,7 +223,7 @@ class HumanObjectPeerTestInstance { System.gc(); System.runFinalization(); // Give the GC a chance to run. assert Arrays.equals(funding_txo.get_a().get_txid(), expected_id.get_txid()); assert funding_txo.get_a().get_index() == expected_id.get_index(); - Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_two = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(data, keys_interface); + Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ roundtrip_two = UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(data, this.entropy_source, this.signer_provider); assert roundtrip_two instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK; must_free_objs.add(new WeakReference<>(((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_two).res.get_b())); must_free_objs.add(new WeakReference<>(((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) roundtrip_two).res)); @@ -304,10 +299,16 @@ class HumanObjectPeerTestInstance { } KeysManager keys = KeysManager.of(key_seed, System.currentTimeMillis() / 1000, (int) (System.currentTimeMillis() * 1000)); if (use_km_wrapper) { - this.keys_interface = manual_keysif(keys.as_KeysInterface()); + this.signer_provider = manual_signer_provider(keys); + this.node_signer = manual_node_signer(keys); + this.entropy_source = EntropySource.new_impl(new EntropySource.EntropySourceInterface() { + @Override public byte[] get_secure_random_bytes() { return keys.as_EntropySource().get_secure_random_bytes(); } + }); this.explicit_keys_manager = null; } else { - this.keys_interface = keys.as_KeysInterface(); + this.signer_provider = keys.as_SignerProvider(); + this.entropy_source = keys.as_EntropySource(); + this.node_signer = keys.as_NodeSigner(); this.explicit_keys_manager = keys; } @@ -364,29 +365,18 @@ class HumanObjectPeerTestInstance { } } private void setup_route_handler() { - this.route_handler = P2PGossipSync.of(this.router, - Option_AccessZ.some(Access.new_impl((genesis_hash, short_channel_id) -> Result_TxOutAccessErrorZ.ok(gossip_txout))), this.logger); + this.route_handler = P2PGossipSync.of(this.net_graph, + Option_UtxoLookupZ.some(UtxoLookup.new_impl((genesis_hash, short_channel_id) -> UtxoResult.sync(Result_TxOutUtxoLookupErrorZ.ok(gossip_txout)))), this.logger); } Peer(byte seed) { this(null, seed); - this.router = NetworkGraph.of(new byte[32], this.logger); + this.net_graph = NetworkGraph.of(Network.LDKNetwork_Bitcoin, this.logger); this.setup_route_handler(); if (use_chan_manager_constructor) { - if (use_ignore_handler) { - this.constructor = new ChannelManagerConstructor(Network.LDKNetwork_Bitcoin, get_config(), new byte[32], 0, - this.keys_interface, this.fee_estimator, this.chain_monitor, null, this.tx_broadcaster, this.logger); - } else { - this.constructor = new ChannelManagerConstructor(Network.LDKNetwork_Bitcoin, get_config(), new byte[32], 0, - this.keys_interface, this.fee_estimator, this.chain_monitor, this.router, this.tx_broadcaster, this.logger); - } - ProbabilisticScoringParameters params = ProbabilisticScoringParameters.with_default(); - ProbabilisticScorer default_scorer = ProbabilisticScorer.of(params, this.router, this.logger); - Result_ProbabilisticScorerDecodeErrorZ score_res = ProbabilisticScorer.read(default_scorer.write(), params, this.router, this.logger); - assert score_res.is_ok(); - Score score = ((Result_ProbabilisticScorerDecodeErrorZ.Result_ProbabilisticScorerDecodeErrorZ_OK) score_res).res.as_Score(); - MultiThreadedLockableScore scorer = null; - if (use_invoice_payer) { scorer = MultiThreadedLockableScore.of(score); } + this.constructor = new ChannelManagerConstructor(Network.LDKNetwork_Bitcoin, get_config(), new byte[32], 0, + this.explicit_keys_manager, this.fee_estimator, this.chain_monitor, this.net_graph, + ProbabilisticScoringParameters.with_default(), this.tx_broadcaster, this.logger); constructor.chain_sync_completed(new ChannelManagerConstructor.EventHandler() { @Override public void handle_event(Event event) { synchronized (pending_manager_events) { @@ -397,71 +387,53 @@ class HumanObjectPeerTestInstance { @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; } @Override public void persist_network_graph(byte[] graph_bytes) { assert graph_bytes.length > 1; } @Override public void persist_scorer(byte[] scorer_bytes) { assert scorer_bytes.length > 1; } - }, scorer); + }, !use_ignore_handler); this.chan_manager = constructor.channel_manager; this.peer_manager = constructor.peer_manager; - this.payer = constructor.payer; must_free_objs.add(new WeakReference<>(this.chan_manager)); } else { - ChainParameters params = ChainParameters.of(Network.LDKNetwork_Bitcoin, BestBlock.of(new byte[32], 0)); - this.chan_manager = ChannelManager.of(this.fee_estimator, chain_watch, tx_broadcaster, logger, this.keys_interface, get_config(), params); - byte[] random_data = keys_interface.get_secure_random_bytes(); - Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node); - assert node_secret.is_ok(); - this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), route_handler.as_RoutingMessageHandler(), - IgnoringMessageHandler.of().as_OnionMessageHandler(), - ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res, (int)(System.currentTimeMillis() / 1000), - random_data, logger, this.custom_message_handler); - if (use_invoice_payer) { - this.payer = InvoicePayer.of(this.chan_manager.as_Payer(), Router.new_impl(new Router.RouterInterface() { - @Override public void notify_payment_path_failed(RouteHop[] path, long short_channel_id) {} - @Override public void notify_payment_path_successful(RouteHop[] path) {} - @Override public void notify_payment_probe_successful(RouteHop[] path) {} - @Override public void notify_payment_probe_failed(RouteHop[] path, long short_channel_id) {} - - @Override - public Result_RouteLightningErrorZ find_route_with_id(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs, byte[] _payment_hash, byte[] _payment_id) { - return find_route(payer, route_params, first_hops, inflight_htlcs); - } + Router router = Router.new_impl(new Router.RouterInterface() { + @Override + public Result_RouteLightningErrorZ find_route_with_id(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs, byte[] _payment_hash, byte[] _payment_id) { + return find_route(payer, route_params, first_hops, inflight_htlcs); + } - @Override - public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) { - while (true) { - try (ReadOnlyNetworkGraph graph = router.read_only()) { - assert graph.channel(424242) == null; - long[] channels = graph.list_channels(); - if (channels.length != 1) { - // If we're using a NioPeerHandler, the handling of announcement signatures and - // channel broadcasting may be done async, so just wait until the channel shows up. - assert use_nio_peer_handler; - continue; - } - ChannelInfo chan = graph.channel(channels[0]); - assert Arrays.equals(chan.get_node_one().as_slice(), chan.get_node_one().write()); - assert Arrays.equals(chan.get_node_one().as_slice(), chan_manager.get_our_node_id()) || - Arrays.equals(chan.get_node_two().as_slice(), chan_manager.get_our_node_id()); - break; + @Override + public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) { + while (true) { + try (ReadOnlyNetworkGraph graph = net_graph.read_only()) { + assert graph.channel(424242) == null; + long[] channels = graph.list_channels(); + if (channels.length != 1) { + // If we're using a NioPeerHandler, the handling of announcement signatures and + // channel broadcasting may be done async, so just wait until the channel shows up. + assert use_nio_peer_handler; + continue; } + ChannelInfo chan = graph.channel(channels[0]); + assert Arrays.equals(chan.get_node_one().as_slice(), chan.get_node_one().write()); + assert Arrays.equals(chan.get_node_one().as_slice(), chan_manager.get_our_node_id()) || + Arrays.equals(chan.get_node_two().as_slice(), chan_manager.get_our_node_id()); + break; } - return UtilMethods.find_route(payer, params, router, first_hops, logger, Score.new_impl(new Score.ScoreInterface() { - @Override public void payment_path_failed(RouteHop[] path, long scid) {} - @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage) { return 0; } - @Override public void payment_path_successful(RouteHop[] path) {} - @Override public void probe_failed(RouteHop[] path, long short_channel_id) { assert false; } - @Override public void probe_successful(RouteHop[] path) { assert false; } - @Override public byte[] write() { assert false; return null; } - }), new byte[32]); } - }), logger, EventHandler.new_impl(new EventHandler.EventHandlerInterface() { - @Override public void handle_event(Event event) { - synchronized (pending_manager_events) { - pending_manager_events.add(event); - pending_manager_events.notifyAll(); - } - } - }), Retry.attempts(0)); - } - } + return UtilMethods.find_route(payer, params, net_graph, first_hops, logger, Score.new_impl(new Score.ScoreInterface() { + @Override public void payment_path_failed(RouteHop[] path, long scid) {} + @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage) { return 0; } + @Override public void payment_path_successful(RouteHop[] path) {} + @Override public void probe_failed(RouteHop[] path, long short_channel_id) { assert false; } + @Override public void probe_successful(RouteHop[] path) { assert false; } + @Override public byte[] write() { assert false; return null; } + }), new byte[32]); + } + }); + ChainParameters params = ChainParameters.of(Network.LDKNetwork_Bitcoin, BestBlock.of(new byte[32], 0)); + this.chan_manager = ChannelManager.of(this.fee_estimator, chain_watch, tx_broadcaster, router, logger, + this.entropy_source, this.node_signer, this.signer_provider, get_config(), params); + this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), route_handler.as_RoutingMessageHandler(), + IgnoringMessageHandler.of().as_OnionMessageHandler(), 0xdeadbeef, + this.entropy_source.get_secure_random_bytes(), logger, this.custom_message_handler, this.node_signer); + } this.node_id = chan_manager.get_our_node_id(); this.filter = null; @@ -475,35 +447,30 @@ class HumanObjectPeerTestInstance { if (use_chan_manager_constructor) { byte[][] monitors = {orig.monitors.values().stream().iterator().next().write()}; byte[] serialized = orig.chan_manager.write(); - byte[] serialized_router = orig.router.write(); + byte[] serialized_graph = orig.net_graph.write(); + byte[] serialized_scorer = orig.constructor.scorer.write(); try { Filter filter_nullable = null; if (this.filter instanceof Option_FilterZ.Some) { filter_nullable = ((Option_FilterZ.Some) this.filter).some; } - if (use_ignore_handler) { - this.constructor = new ChannelManagerConstructor(serialized, monitors, get_config(), - this.keys_interface, this.fee_estimator, this.chain_monitor, filter_nullable, - null, this.tx_broadcaster, this.logger); - } else { - this.constructor = new ChannelManagerConstructor(serialized, monitors, get_config(), - this.keys_interface, this.fee_estimator, this.chain_monitor, filter_nullable, - serialized_router, this.tx_broadcaster, this.logger); - try { - // Test that ChannelManagerConstructor correctly rejects duplicate ChannelMonitors - byte[][] monitors_dupd = new byte[2][]; - monitors_dupd[0] = monitors[0]; - monitors_dupd[1] = monitors[0]; - ChannelManagerConstructor constr = this.constructor = new ChannelManagerConstructor(serialized, monitors_dupd, get_config(), - this.keys_interface, this.fee_estimator, this.chain_monitor, filter_nullable, - null, this.tx_broadcaster, this.logger); - assert false; - } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {} - } - this.router = this.constructor.net_graph; + this.constructor = new ChannelManagerConstructor(serialized, monitors, get_config(), + this.explicit_keys_manager, this.fee_estimator, this.chain_monitor, filter_nullable, + serialized_graph, ProbabilisticScoringParameters.with_default(), serialized_scorer, + this.tx_broadcaster, this.logger); + try { + // Test that ChannelManagerConstructor correctly rejects duplicate ChannelMonitors + byte[][] monitors_dupd = new byte[2][]; + monitors_dupd[0] = monitors[0]; + monitors_dupd[1] = monitors[0]; + ChannelManagerConstructor constr = new ChannelManagerConstructor(serialized, monitors_dupd, get_config(), + this.explicit_keys_manager, this.fee_estimator, this.chain_monitor, filter_nullable, + serialized_graph, ProbabilisticScoringParameters.with_default(), serialized_scorer, + this.tx_broadcaster, this.logger); + assert false; + } catch (ChannelManagerConstructor.InvalidSerializedDataException e) {} + this.net_graph = this.constructor.net_graph; setup_route_handler(); - MultiThreadedLockableScore scorer = null; - if (use_invoice_payer) { scorer = MultiThreadedLockableScore.of(ProbabilisticScorer.of(ProbabilisticScoringParameters.with_default(), this.router, this.logger).as_Score()); } constructor.chain_sync_completed(new ChannelManagerConstructor.EventHandler() { @Override public void handle_event(Event event) { synchronized (pending_manager_events) { @@ -514,9 +481,8 @@ class HumanObjectPeerTestInstance { @Override public void persist_manager(byte[] channel_manager_bytes) { assert channel_manager_bytes.length > 1; } @Override public void persist_network_graph(byte[] graph_bytes) { assert graph_bytes.length > 1; } @Override public void persist_scorer(byte[] scorer_bytes) { assert scorer_bytes.length > 1; } - }, scorer); + }, !use_ignore_handler); this.chan_manager = constructor.channel_manager; - this.payer = constructor.payer; this.peer_manager = constructor.peer_manager; must_free_objs.add(new WeakReference<>(this.chan_manager)); // If we are using a ChannelManagerConstructor, we may have pending events waiting on the old peer @@ -530,7 +496,42 @@ class HumanObjectPeerTestInstance { assert false; } } else { - this.router = NetworkGraph.of(new byte[32], this.logger); + this.net_graph = NetworkGraph.of(Network.LDKNetwork_Bitcoin, this.logger); + Router router = Router.new_impl(new Router.RouterInterface() { + @Override + public Result_RouteLightningErrorZ find_route_with_id(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs, byte[] _payment_hash, byte[] _payment_id) { + return find_route(payer, route_params, first_hops, inflight_htlcs); + } + + @Override + public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) { + while (true) { + try (ReadOnlyNetworkGraph graph = net_graph.read_only()) { + assert graph.channel(424242) == null; + long[] channels = graph.list_channels(); + if (channels.length != 1) { + // If we're using a NioPeerHandler, the handling of announcement signatures and + // channel broadcasting may be done async, so just wait until the channel shows up. + assert use_nio_peer_handler; + continue; + } + ChannelInfo chan = graph.channel(channels[0]); + assert Arrays.equals(chan.get_node_one().as_slice(), chan.get_node_one().write()); + assert Arrays.equals(chan.get_node_one().as_slice(), chan_manager.get_our_node_id()) || + Arrays.equals(chan.get_node_two().as_slice(), chan_manager.get_our_node_id()); + break; + } + } + return UtilMethods.find_route(payer, params, net_graph, first_hops, logger, Score.new_impl(new Score.ScoreInterface() { + @Override public void payment_path_failed(RouteHop[] path, long scid) {} + @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage) { return 0; } + @Override public void payment_path_successful(RouteHop[] path) {} + @Override public void probe_failed(RouteHop[] path, long short_channel_id) { assert false; } + @Override public void probe_successful(RouteHop[] path) { assert false; } + @Override public byte[] write() { assert false; return null; } + }), new byte[32]); + } + }); this.setup_route_handler(); ChannelMonitor[] monitors = new ChannelMonitor[1]; assert orig.monitors.size() == 1; @@ -539,61 +540,25 @@ class HumanObjectPeerTestInstance { } else { byte[] serialized = orig.monitors.values().stream().iterator().next().write(); Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ res = - UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(serialized, this.keys_interface); + UtilMethods.C2Tuple_BlockHashChannelMonitorZ_read(serialized, this.entropy_source, this.signer_provider); assert res instanceof Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK; monitors[0] = ((Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ.Result_C2Tuple_BlockHashChannelMonitorZDecodeErrorZ_OK) res).res.get_b(); } byte[] serialized = orig.chan_manager.write(); Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ read_res = - UtilMethods.C2Tuple_BlockHashChannelManagerZ_read(serialized, this.keys_interface, this.fee_estimator, this.chain_watch, this.tx_broadcaster, this.logger, get_config(), monitors); + UtilMethods.C2Tuple_BlockHashChannelManagerZ_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); assert read_res instanceof Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK; this.chan_manager = ((Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ.Result_C2Tuple_BlockHashChannelManagerZDecodeErrorZ_OK) read_res).res.get_b(); this.chain_watch.watch_channel(monitors[0].get_funding_txo().get_a(), monitors[0]); - byte[] random_data = keys_interface.get_secure_random_bytes(); - Result_SecretKeyNoneZ node_secret = keys_interface.get_node_secret(Recipient.LDKRecipient_Node); - assert node_secret.is_ok(); this.peer_manager = PeerManager.of(chan_manager.as_ChannelMessageHandler(), route_handler.as_RoutingMessageHandler(), - IgnoringMessageHandler.of().as_OnionMessageHandler(), - ((Result_SecretKeyNoneZ.Result_SecretKeyNoneZ_OK)node_secret).res, (int)(System.currentTimeMillis() / 1000), - random_data, logger, this.custom_message_handler); + IgnoringMessageHandler.of().as_OnionMessageHandler(), (int)(System.currentTimeMillis() / 1000), + this.entropy_source.get_secure_random_bytes(), logger, this.custom_message_handler, this.node_signer); if (!break_cross_peer_refs && (use_manual_watch || use_km_wrapper)) { // When we pass monitors[0] into chain_watch.watch_channel we create a reference from the new Peer to a // field in the old peer, preventing freeing of the original Peer until the new Peer is freed. Thus, we // shouldn't bother waiting for the original to be freed later on. cross_reload_ref_pollution = true; } - if (use_invoice_payer) { - this.payer = InvoicePayer.of(this.chan_manager.as_Payer(), Router.new_impl(new Router.RouterInterface() { - @Override public void notify_payment_path_failed(RouteHop[] path, long short_channel_id) {} - @Override public void notify_payment_path_successful(RouteHop[] path) {} - @Override public void notify_payment_probe_successful(RouteHop[] path) {} - @Override public void notify_payment_probe_failed(RouteHop[] path, long short_channel_id) {} - - @Override - public Result_RouteLightningErrorZ find_route_with_id(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs, byte[] _payment_hash, byte[] _payment_id) { - return find_route(payer, route_params, first_hops, inflight_htlcs); - } - - @Override - public Result_RouteLightningErrorZ find_route(byte[] payer, RouteParameters route_params, ChannelDetails[] first_hops, InFlightHtlcs inflight_htlcs) { - return UtilMethods.find_route(payer, route_params, router, first_hops, logger, Score.new_impl(new Score.ScoreInterface() { - @Override public long channel_penalty_msat(long short_channel_id, NodeId source, NodeId target, ChannelUsage usage) { return 0; } - @Override public void payment_path_failed(RouteHop[] path, long scid) {} - @Override public void payment_path_successful(RouteHop[] path) {} - @Override public void probe_failed(RouteHop[] path, long short_channel_id) { assert false; } - @Override public void probe_successful(RouteHop[] path) { assert false; } - @Override public byte[] write() { assert false; return null; } - }), new byte[32]); - } - }), logger, EventHandler.new_impl(new EventHandler.EventHandlerInterface() { - @Override public void handle_event(Event event) { - synchronized (pending_manager_events) { - pending_manager_events.add(event); - pending_manager_events.notifyAll(); - } - } - }), Retry.attempts(0)); - } } this.node_id = chan_manager.get_our_node_id(); bind_nio(); @@ -899,7 +864,7 @@ class HumanObjectPeerTestInstance { assert Arrays.equals(peer1_chans[0].get_channel_id(), funding.getTxId().getReversedBytes()); assert Arrays.equals(peer2_chans[0].get_channel_id(), funding.getTxId().getReversedBytes()); - Result_InvoiceSignOrCreationErrorZ invoice = UtilMethods.create_invoice_from_channelmanager(peer2.chan_manager, peer2.keys_interface, peer2.logger, Currency.LDKCurrency_Bitcoin, Option_u64Z.some(10000000), "Invoice Description", 7200); + Result_InvoiceSignOrCreationErrorZ 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()); assert invoice instanceof Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK; System.out.println("Got invoice: " + ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.to_str()); @@ -921,11 +886,11 @@ class HumanObjectPeerTestInstance { InvoiceFeatures invoice_features = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.features(); RouteHint[] route_hints = ((Result_InvoiceSignOrCreationErrorZ.Result_InvoiceSignOrCreationErrorZ_OK) invoice).res.route_hints(); - PaymentParameters payee = PaymentParameters.of(peer2.node_id, invoice_features, route_hints, Option_u64Z.none(), 6*24*14, (byte)1, (byte)2, new long[0]); - RouteParameters route_params = RouteParameters.of(payee, 10000000, 42); + PaymentParameters payee = PaymentParameters.of(peer2.node_id, invoice_features, route_hints, Option_u64Z.none(), 6*24*14, (byte)1, (byte)2, new long[0], 42); + RouteParameters route_params = RouteParameters.of(payee, 10000000); Result_RouteLightningErrorZ route_res = UtilMethods.find_route( - peer1.chan_manager.get_our_node_id(), route_params, peer1.router, - peer1_chans, peer1.logger, ProbabilisticScorer.of(ProbabilisticScoringParameters.with_default(), peer1.router, peer1.logger).as_Score(), new byte[32]); + peer1.chan_manager.get_our_node_id(), route_params, peer1.net_graph, + peer1_chans, peer1.logger, ProbabilisticScorer.of(ProbabilisticScoringParameters.with_default(), peer1.net_graph, peer1.logger).as_Score(), new byte[32]); assert route_res instanceof Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK; Route route = ((Result_RouteLightningErrorZ.Result_RouteLightningErrorZ_OK) route_res).res; assert route.get_paths().length == 1; @@ -947,7 +912,7 @@ class HumanObjectPeerTestInstance { payment_res = peer1.chan_manager.send_payment(r2, payment_hash, payment_secret, payment_id); assert payment_res instanceof Result_NonePaymentSendFailureZ.Result_NonePaymentSendFailureZ_Err; } else { - Result_PaymentIdPaymentErrorZ send_res = peer1.payer.pay_invoice(((Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res); + Result_PaymentIdPaymentErrorZ send_res = UtilMethods.pay_invoice(((Result_InvoiceParseOrSemanticErrorZ.Result_InvoiceParseOrSemanticErrorZ_OK) parsed_invoice).res, Retry.attempts(0), peer1.chan_manager); assert send_res instanceof Result_PaymentIdPaymentErrorZ.Result_PaymentIdPaymentErrorZ_OK; } @@ -1137,7 +1102,7 @@ class HumanObjectPeerTestInstance { } if (use_nio_peer_handler) { - state.peer1.peer_manager.disconnect_by_node_id(state.peer2.chan_manager.get_our_node_id(), false); + state.peer1.peer_manager.disconnect_by_node_id(state.peer2.chan_manager.get_our_node_id()); while (state.peer1.peer_manager.get_peer_node_ids().length != 0) Thread.yield(); while (state.peer2.peer_manager.get_peer_node_ids().length != 0) Thread.yield(); state.peer1.nio_peer_handler.interrupt(); @@ -1154,8 +1119,8 @@ class HumanObjectPeerTestInstance { t.interrupt(); - if (state.peer1.router != null) - state.peer1.router.write(); + if (state.peer1.net_graph != null) + state.peer1.net_graph.write(); // Construct the only Option_Enum::Variant(OpaqueStruct) we have in the codebase as this used to cause double-frees: 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}; @@ -1232,6 +1197,11 @@ public class HumanObjectPeerTest { // InvoicePayer to send payments in this case. continue; } + if (use_chan_manager_constructor && use_km_wrapper) { + // ChannelManagerConstructor requires a full KeysManager, so using wrapped keys interfaces doesn't make + // any sense. + continue; + } statusFunction.accept(i); 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); } diff --git a/src/test/java/org/ldk/ManualMsgHandlingPeerTest.java b/src/test/java/org/ldk/ManualMsgHandlingPeerTest.java deleted file mode 100644 index fd9fa7ef..00000000 --- a/src/test/java/org/ldk/ManualMsgHandlingPeerTest.java +++ /dev/null @@ -1,209 +0,0 @@ -package org.ldk; - -import org.junit.jupiter.api.Test; -import org.ldk.impl.bindings; -import org.ldk.enums.*; -import org.ldk.structs.Record; - -public class ManualMsgHandlingPeerTest { - @Test - void test_message_handler() { - long logger = bindings.LDKLogger_new((long arg)->{ - System.out.println(bindings.Record_get_args(arg)); - bindings.Record_free(arg); - }); - long chan_handler = bindings.LDKChannelMessageHandler_new(new bindings.LDKChannelMessageHandler() { - @Override - public void handle_open_channel(byte[] their_node_id, long their_features, long msg) { - - } - - @Override - public void handle_accept_channel(byte[] their_node_id, long their_features, long msg) { - - } - - @Override - public void handle_funding_created(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_funding_signed(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_channel_ready(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_shutdown(byte[] their_node_id, long their_features, long msg) { - - } - - @Override - public void handle_closing_signed(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_update_add_htlc(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_update_fulfill_htlc(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_update_fail_htlc(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_update_fail_malformed_htlc(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_commitment_signed(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_revoke_and_ack(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_update_fee(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_announcement_signatures(byte[] their_node_id, long msg) { - - } - - @Override - public void peer_disconnected(byte[] their_node_id, boolean no_connection_possible) { - - } - - @Override - public long peer_connected(byte[] their_node_id, long msg) { - assert false; - return 0; - } - - @Override - public void handle_channel_reestablish(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_channel_update(byte[] their_node_id, long msg) { - - } - - @Override - public void handle_error(byte[] their_node_id, long msg) { - - } - - @Override - public long provided_node_features() { - assert false; - return 0; - } - - @Override - public long provided_init_features(byte[] their_node_id) { - assert false; - return 0; - } - }, () -> new long[0]); - long route_handler = bindings.LDKRoutingMessageHandler_new(new bindings.LDKRoutingMessageHandler() { - @Override public long handle_node_announcement(long msg) { - return 0; - } - @Override public long handle_channel_announcement(long msg) { - return 0; - } - @Override public long handle_channel_update(long msg) { - return 0; - } - - @Override - public long get_next_channel_announcement(long starting_point) { - assert false; - return 0; - } - - @Override - public long get_next_node_announcement(byte[] starting_point) { - assert false; - return 0; - } - - @Override public long peer_connected(byte[] their_node_id, long init) { assert false; return 0; } - - @Override - public long handle_reply_channel_range(byte[] their_node_id, long msg) { - return 0; - } - - @Override - public long handle_reply_short_channel_ids_end(byte[] their_node_id, long msg) { - return 0; - } - - @Override - public long handle_query_channel_range(byte[] their_node_id, long msg) { - return 0; - } - - @Override - public long handle_query_short_channel_ids(byte[] their_node_id, long msg) { - return 0; - } - - @Override - public long provided_node_features() { - assert false; - return 0; - } - - @Override - public long provided_init_features(byte[] their_node_id) { - assert false; - return 0; - } - }, () -> new long[0]); - long ignoring_message_handler = bindings.IgnoringMessageHandler_new(); - long onion_message_handler = bindings.IgnoringMessageHandler_as_OnionMessageHandler(ignoring_message_handler); - long message_handler = bindings.MessageHandler_new(chan_handler, route_handler, onion_message_handler); - byte[] our_node_secret = new byte[32]; - byte[] random_data = new byte[32]; - for (byte i = 0; i < 32; i++) { random_data[i] = i; our_node_secret[i] = (byte) (i ^ 0xff); } - - long peer_manager = bindings.PeerManager_new(message_handler, our_node_secret, (int)(System.currentTimeMillis() / 1000), - random_data, logger, - bindings.IgnoringMessageHandler_as_CustomMessageHandler(ignoring_message_handler)); - - // Test Level_max() since its the only place we create a java object from a Rust-returned enum. - assert bindings.Level_max() == Level.LDKLevel_Gossip; - - // Note that we can't rely on finalizer order, so don't bother trying to rely on it here - bindings.Logger_free(logger); - bindings.ChannelMessageHandler_free(chan_handler); - bindings.RoutingMessageHandler_free(route_handler); - bindings.OnionMessageHandler_free(onion_message_handler); - bindings.IgnoringMessageHandler_free(ignoring_message_handler); - //bindings.MessageHandler_free(message_handler); - bindings.PeerManager_free(peer_manager); - } -} diff --git a/src/test/java/org/ldk/PeerTest.java b/src/test/java/org/ldk/PeerTest.java deleted file mode 100644 index 19bde2ab..00000000 --- a/src/test/java/org/ldk/PeerTest.java +++ /dev/null @@ -1,409 +0,0 @@ -package org.ldk; - -import org.bitcoinj.core.*; -import org.bitcoinj.script.Script; -import org.junit.jupiter.api.Test; -import org.ldk.enums.ChannelMonitorUpdateStatus; -import org.ldk.enums.Network; -import org.ldk.enums.Recipient; -import org.ldk.impl.bindings; -import org.ldk.util.UInt128; - -import java.lang.ref.Reference; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.LinkedList; -import java.util.concurrent.ConcurrentHashMap; -import java.util.concurrent.ConcurrentLinkedQueue; - -public class PeerTest { - class Peer { - final long logger; - final long fee_estimator; - final long tx_broadcaster; - final long chain_monitor; - final long keys; - final long keys_interface; - final long config; - final long chan_manager; - final long chan_manager_events; - final long chan_handler; - final long router; - final long router_wrapper; - final long route_handler; - final long message_handler; - final long ignoring_message_handler; - final long custom_message_handler; - final long onion_message_handler; - final long peer_manager; - HashMap monitors; // Wow I forgot just how terrible Java is - we can't put a byte array here. - byte[] node_id; - bindings.LDKFeeEstimator fee_est; - bindings.LDKBroadcasterInterface broad_trait; - bindings.LDKLogger log_trait; - bindings.LDKWatch watcher; - - Peer(byte seed) { - this.log_trait = (long arg) -> { - System.out.println(seed + ": " + bindings.Record_get_args(arg)); - bindings.Record_free(arg); - }; - logger = bindings.LDKLogger_new(this.log_trait); - this.fee_est = confirmation_target -> 0; - this.fee_estimator = bindings.LDKFeeEstimator_new(this.fee_est); - this.broad_trait = tx -> { - // We should broadcast - }; - this.tx_broadcaster = bindings.LDKBroadcasterInterface_new(this.broad_trait); - this.monitors = new HashMap<>(); - this.watcher = new bindings.LDKWatch() { - @Override - public ChannelMonitorUpdateStatus watch_channel(long funding_txo, long monitor) { - synchronized (monitors) { - assert monitors.put(Arrays.toString(bindings.OutPoint_get_txid(funding_txo)), monitor) == null; - } - bindings.OutPoint_free(funding_txo); - return ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed; - } - - @Override - public ChannelMonitorUpdateStatus update_channel(long funding_txo, long update) { - synchronized (monitors) { - String txid = Arrays.toString(bindings.OutPoint_get_txid(funding_txo)); - assert monitors.containsKey(txid); - long update_res = bindings.ChannelMonitor_update_monitor(monitors.get(txid), update, tx_broadcaster, fee_estimator, logger); - assert bindings.CResult_NoneNoneZ_is_ok(update_res); - bindings.CResult_NoneNoneZ_free(update_res); - } - bindings.OutPoint_free(funding_txo); - bindings.ChannelMonitorUpdate_free(update); - return ChannelMonitorUpdateStatus.LDKChannelMonitorUpdateStatus_Completed; - } - - @Override - public long[] release_pending_monitor_events() { - synchronized (monitors) { - assert monitors.size() <= 1; - for (Long mon : monitors.values()) { - long funding_info = bindings.ChannelMonitor_get_funding_txo(mon); - long funding_txo = bindings.C2Tuple_OutPointScriptZ_get_a(funding_info); - long[] mon_events = bindings.ChannelMonitor_get_and_clear_pending_monitor_events(mon); - byte[] counterparty_pk = bindings.ChannelMonitor_get_counterparty_node_id(mon); - long funding_mon_tuple = bindings.C3Tuple_OutPointCVec_MonitorEventZPublicKeyZ_new(funding_txo, mon_events, counterparty_pk); - bindings.C2Tuple_OutPointScriptZ_free(funding_info); - return new long[] {funding_mon_tuple}; - } - } - return new long[0]; - } - }; - this.chain_monitor = bindings.LDKWatch_new(this.watcher); - - byte[] key_seed = new byte[32]; - for (byte i = 0; i < 32; i++) { key_seed[i] = (byte) (i ^ seed); } - this.keys = bindings.KeysManager_new(key_seed, System.currentTimeMillis() / 1000, (int)(System.currentTimeMillis() * 1000) & 0xffffffff); - this.keys_interface = bindings.KeysManager_as_KeysInterface(keys); - this.config = bindings.UserConfig_default(); - long params = bindings.ChainParameters_new(Network.LDKNetwork_Bitcoin, bindings.BestBlock_new(new byte[32], 0)); - this.chan_manager = bindings.ChannelManager_new(fee_estimator, chain_monitor, tx_broadcaster, logger, keys_interface, config, params); - this.node_id = bindings.ChannelManager_get_our_node_id(chan_manager); - this.chan_manager_events = bindings.ChannelManager_as_EventsProvider(chan_manager); - - this.chan_handler = bindings.ChannelManager_as_ChannelMessageHandler(chan_manager); - this.router = bindings.NetworkGraph_new(new byte[32], logger); - this.router_wrapper = bindings.P2PGossipSync_new(router, bindings.COption_AccessZ_none(), logger); - this.route_handler = bindings.P2PGossipSync_as_RoutingMessageHandler(router_wrapper); - this.ignoring_message_handler = bindings.IgnoringMessageHandler_new(); - this.custom_message_handler = bindings.IgnoringMessageHandler_as_CustomMessageHandler(this.ignoring_message_handler); - this.onion_message_handler = bindings.IgnoringMessageHandler_as_OnionMessageHandler(this.ignoring_message_handler); - this.message_handler = bindings.MessageHandler_new(chan_handler, route_handler, this.onion_message_handler); - - byte[] random_data = new byte[32]; - for (byte i = 0; i < 32; i++) { random_data[i] = (byte) ((i ^ seed) ^ 0xf0); } - - long node_id_result = bindings.KeysInterface_get_node_secret(keys_interface, Recipient.LDKRecipient_Node); - assert bindings.CResult_SecretKeyNoneZ_is_ok(node_id_result); - this.peer_manager = bindings.PeerManager_new(message_handler, bindings.CResult_SecretKeyNoneZ_get_ok(node_id_result), - (int)(System.currentTimeMillis() / 1000), random_data, logger, this.custom_message_handler); - bindings.CResult_SecretKeyNoneZ_free(node_id_result); - } - - void connect_block(Block b, Transaction t, int height) { - long listen = bindings.ChannelManager_as_Listen(chan_manager); - bindings.Listen_block_connected(listen, b.bitcoinSerialize(), height); - bindings.Listen_free(listen); - synchronized (monitors) { - for (Long mon : monitors.values()) { - long[] txn; - if (t != null) - txn = new long[]{bindings.C2Tuple_usizeTransactionZ_new(1, t.bitcoinSerialize())}; - else - txn = new long[0]; - byte[] header = Arrays.copyOfRange(b.bitcoinSerialize(), 0, 80); - long[] ret = bindings.ChannelMonitor_block_connected(mon, header, txn, height, tx_broadcaster, fee_estimator, logger); - for (long r : ret) { - bindings.C2Tuple_TxidCVec_C2Tuple_u32TxOutZZZ_free(r); - } - } - } - } - - void free() { - // Note that we can't rely on finalizer order, so don't bother trying to rely on it here - bindings.Logger_free(logger); - bindings.FeeEstimator_free(fee_estimator); - bindings.BroadcasterInterface_free(tx_broadcaster); - bindings.Watch_free(chain_monitor); - bindings.KeysManager_free(keys); - bindings.KeysInterface_free(keys_interface); - bindings.UserConfig_free(config); - bindings.ChannelManager_free(chan_manager); - bindings.EventsProvider_free(chan_manager_events); - bindings.ChannelMessageHandler_free(chan_handler); - bindings.NetworkGraph_free(router); - bindings.P2PGossipSync_free(router_wrapper); - bindings.RoutingMessageHandler_free(route_handler); - bindings.CustomMessageHandler_free(custom_message_handler); - bindings.OnionMessageHandler_free(onion_message_handler); - //MessageHandler was actually moved into the route_handler!: bindings.MessageHandler_free(message_handler); - bindings.PeerManager_free(peer_manager); - synchronized (monitors) { - for (Long mon : monitors.values()) { - bindings.ChannelMonitor_free(mon); - } - } - } - } - - class LongHolder { long val; } - class PendingWrite { - long pm; - long descriptor; - byte[] array; - PendingWrite(long pm, long descriptor, byte[] array) { this.pm = pm; this.descriptor = descriptor; this.array = array; } - void process() { - long res = bindings.PeerManager_read_event(pm, descriptor, array); - assert bindings.CResult_boolPeerHandleErrorZ_is_ok(res); - assert !bindings.CResult_boolPeerHandleErrorZ_get_ok(res); - bindings.CResult_boolPeerHandleErrorZ_free(res); - } - } - ConcurrentLinkedQueue pending_writes = new ConcurrentLinkedQueue<>(); - - void do_read_event(ConcurrentLinkedQueue list, long pm, long descriptor, byte[] arr) { - pending_writes.add(new PendingWrite(pm, descriptor, arr)); - Thread thread = new Thread(() -> { - synchronized (pending_writes) { - while (true) { - PendingWrite write = pending_writes.poll(); - if (write == null) break; - write.process(); - } - } - }); - thread.start(); - list.add(thread); - } - - void deliver_peer_messages(ConcurrentLinkedQueue list, long peer1, long peer2) throws InterruptedException { - bindings.PeerManager_process_events(peer1); - bindings.PeerManager_process_events(peer2); - while (!list.isEmpty()) { - list.poll().join(); - bindings.PeerManager_process_events(peer1); - bindings.PeerManager_process_events(peer2); - } - } - - @Test - void test_message_handler() throws InterruptedException { - Peer peer1 = new Peer((byte) 1); - Peer peer2 = new Peer((byte) 2); - - ConcurrentLinkedQueue list = new ConcurrentLinkedQueue(); - LongHolder descriptor1 = new LongHolder(); - LongHolder descriptor1ref = descriptor1; - bindings.LDKSocketDescriptor sock1 = new bindings.LDKSocketDescriptor() { - @Override - public long send_data(byte[] data, boolean resume_read) { - do_read_event(list, peer1.peer_manager, descriptor1ref.val, data); - return data.length; - } - - @Override public void disconnect_socket() { assert false; } - @Override public boolean eq(long other_arg) { boolean ret = bindings.SocketDescriptor_hash(other_arg) == 2; bindings.SocketDescriptor_free(other_arg); return ret; } - @Override public long hash() { return 2; } - }; - long descriptor2 = bindings.LDKSocketDescriptor_new(sock1); - - bindings.LDKSocketDescriptor sock2 = new bindings.LDKSocketDescriptor() { - @Override - public long send_data(byte[] data, boolean resume_read) { - do_read_event(list, peer2.peer_manager, descriptor2, data); - return data.length; - } - - @Override public void disconnect_socket() { assert false; } - @Override public boolean eq(long other_arg) { boolean ret = bindings.SocketDescriptor_hash(other_arg) == 1; bindings.SocketDescriptor_free(other_arg); return ret; } - @Override public long hash() { return 1; } - }; - descriptor1.val = bindings.LDKSocketDescriptor_new(sock2); - - long no_netaddr = bindings.COption_NetAddressZ_none(); - long init_vec = bindings.PeerManager_new_outbound_connection(peer1.peer_manager, peer2.node_id, descriptor1.val, no_netaddr); - assert(bindings.CResult_CVec_u8ZPeerHandleErrorZ_is_ok(init_vec)); - - long con_res = bindings.PeerManager_new_inbound_connection(peer2.peer_manager, descriptor2, no_netaddr); - assert(bindings.CResult_NonePeerHandleErrorZ_is_ok(con_res)); - bindings.CResult_NonePeerHandleErrorZ_free(con_res); - do_read_event(list, peer2.peer_manager, descriptor2, bindings.CResult_CVec_u8ZPeerHandleErrorZ_get_ok(init_vec)); - bindings.CResult_CVec_u8ZPeerHandleErrorZ_free(init_vec); - bindings.COption_NetAddressZ_free(no_netaddr); - - deliver_peer_messages(list, peer1.peer_manager, peer2.peer_manager); - - byte[] user_id = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }; - - long cc_res = bindings.ChannelManager_create_channel(peer1.chan_manager, peer2.node_id, 10000, 1000, user_id, 0); - assert bindings.CResult_NoneAPIErrorZ_is_ok(cc_res); - bindings.CResult_NoneAPIErrorZ_free(cc_res); - - deliver_peer_messages(list, peer1.peer_manager, peer2.peer_manager); - - ArrayList events = new ArrayList(); - bindings.LDKEventHandler events_adder = events::add; - long handler = bindings.LDKEventHandler_new(events_adder); - - bindings.EventsProvider_process_pending_events(peer1.chan_manager_events, handler); - assert events.size() == 1; - bindings.LDKEvent event = bindings.LDKEvent_ref_from_ptr(events.get(0)); - assert event instanceof bindings.LDKEvent.FundingGenerationReady; - assert ((bindings.LDKEvent.FundingGenerationReady)event).channel_value_satoshis == 10000; - assert Arrays.equals(((bindings.LDKEvent.FundingGenerationReady)event).user_channel_id, user_id); - byte[] funding_spk = ((bindings.LDKEvent.FundingGenerationReady)event).output_script; - assert funding_spk.length == 34 && funding_spk[0] == 0 && funding_spk[1] == 32; // P2WSH - byte[] chan_id = ((bindings.LDKEvent.FundingGenerationReady)event).temporary_channel_id; - bindings.Event_free(events.remove(0)); - - Transaction funding = new Transaction(NetworkParameters.fromID(NetworkParameters.ID_MAINNET)); - funding.addInput(new TransactionInput(NetworkParameters.fromID(NetworkParameters.ID_MAINNET), funding, new byte[0])); - funding.getInputs().get(0).setWitness(new TransactionWitness(2)); // Make sure we don't complain about lack of witness - funding.getInput(0).getWitness().setPush(0, new byte[] {0x1}); - funding.addOutput(Coin.SATOSHI.multiply(10000), new Script(funding_spk)); - bindings.ChannelManager_funding_transaction_generated(peer1.chan_manager, chan_id, peer2.node_id, funding.bitcoinSerialize()); - - deliver_peer_messages(list, peer1.peer_manager, peer2.peer_manager); - - Block b = new Block(NetworkParameters.fromID(NetworkParameters.ID_MAINNET), 2, Sha256Hash.ZERO_HASH, Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[]{funding})); - peer1.connect_block(b, funding, 1); - peer2.connect_block(b, funding, 1); - - for (int height = 2; height < 10; height++) { - b = new Block(NetworkParameters.fromID(NetworkParameters.ID_MAINNET), 2, b.getHash(), Sha256Hash.ZERO_HASH, 42, 0, 0, Arrays.asList(new Transaction[0])); - peer1.connect_block(b, null, height); - peer2.connect_block(b, null, height); - } - - deliver_peer_messages(list, peer1.peer_manager, peer2.peer_manager); - - long[] peer1_chans = bindings.ChannelManager_list_channels(peer1.chan_manager); - long[] peer2_chans = bindings.ChannelManager_list_channels(peer2.chan_manager); - assert peer1_chans.length == 1; - assert peer2_chans.length == 1; - assert bindings.ChannelDetails_get_channel_value_satoshis(peer1_chans[0]) == 10000; - assert bindings.ChannelDetails_get_is_usable(peer1_chans[0]); - assert Arrays.equals(bindings.ChannelDetails_get_channel_id(peer1_chans[0]), funding.getTxId().getReversedBytes()); - assert Arrays.equals(bindings.ChannelDetails_get_channel_id(peer2_chans[0]), funding.getTxId().getReversedBytes()); - for (long chan : peer2_chans) bindings.ChannelDetails_free(chan); - - bindings.EventsProvider_process_pending_events(peer1.chan_manager_events, handler); - assert events.size() == 1; - bindings.LDKEvent ready1 = bindings.LDKEvent_ref_from_ptr(events.get(0)); - assert ready1 instanceof bindings.LDKEvent.ChannelReady; - bindings.Event_free(events.remove(0)); - - bindings.EventsProvider_process_pending_events(peer2.chan_manager_events, handler); - assert events.size() == 1; - bindings.LDKEvent ready2 = bindings.LDKEvent_ref_from_ptr(events.get(0)); - assert ready2 instanceof bindings.LDKEvent.ChannelReady; - bindings.Event_free(events.remove(0)); - - long no_min_val = bindings.COption_u64Z_none(); - long inbound_payment = bindings.ChannelManager_create_inbound_payment(peer2.chan_manager, no_min_val, 7200); - assert bindings.CResult_C2Tuple_PaymentHashPaymentSecretZNoneZ_is_ok(inbound_payment); - long payment_tuple = bindings.CResult_C2Tuple_PaymentHashPaymentSecretZNoneZ_get_ok(inbound_payment); - bindings.COption_u64Z_free(no_min_val); - - long scorer = bindings.ProbabilisticScorer_new(bindings.ProbabilisticScoringParameters_default(), peer1.router, peer1.logger); - long scorer_interface = bindings.ProbabilisticScorer_as_Score(scorer); - - long no_u64 = bindings.COption_u64Z_none(); - long invoice_features = bindings.InvoiceFeatures_empty(); - bindings.InvoiceFeatures_set_payment_secret_required(invoice_features); - bindings.InvoiceFeatures_set_variable_length_onion_required(invoice_features); - long payee = bindings.PaymentParameters_new(peer2.node_id, invoice_features, new long[0], no_u64, 6*24*14, (byte)1, (byte)1, new long[0]); - bindings.InvoiceFeatures_free(invoice_features); - bindings.COption_u64Z_free(no_u64); - long route_params = bindings.RouteParameters_new(payee, 1000, 42); - long route = bindings.find_route(peer1.node_id, route_params, peer1.router, peer1_chans, peer1.logger, - scorer_interface, new byte[32]); - bindings.RouteParameters_free(route_params); - bindings.PaymentParameters_free(payee); - bindings.Score_free(scorer_interface); - bindings.ProbabilisticScorer_free(scorer); - - for (long chan : peer1_chans) bindings.ChannelDetails_free(chan); - assert bindings.CResult_RouteLightningErrorZ_is_ok(route); - long payment_res = bindings.ChannelManager_send_payment(peer1.chan_manager, bindings.CResult_RouteLightningErrorZ_get_ok(route), - bindings.C2Tuple_PaymentHashPaymentSecretZ_get_a(payment_tuple), - bindings.C2Tuple_PaymentHashPaymentSecretZ_get_b(payment_tuple), new byte[32]); - bindings.CResult_RouteLightningErrorZ_free(route); - bindings.CResult_C2Tuple_PaymentHashPaymentSecretZNoneZ_is_ok(inbound_payment); - assert bindings.CResult_NonePaymentSendFailureZ_is_ok(payment_res); - bindings.CResult_NonePaymentSendFailureZ_free(payment_res); - - deliver_peer_messages(list, peer1.peer_manager, peer2.peer_manager); - - bindings.EventsProvider_process_pending_events(peer2.chan_manager_events, handler); - assert events.size() == 1; - bindings.LDKEvent forwardable = bindings.LDKEvent_ref_from_ptr(events.get(0)); - assert forwardable instanceof bindings.LDKEvent.PendingHTLCsForwardable; - bindings.Event_free(events.remove(0)); - bindings.ChannelManager_process_pending_htlc_forwards(peer2.chan_manager); - - bindings.EventsProvider_process_pending_events(peer2.chan_manager_events, handler); - assert events.size() == 1; - bindings.LDKEvent payment_recvd = bindings.LDKEvent_ref_from_ptr(events.get(0)); - assert payment_recvd instanceof bindings.LDKEvent.PaymentClaimable; - bindings.LDKPaymentPurpose purpose = bindings.LDKPaymentPurpose_ref_from_ptr(((bindings.LDKEvent.PaymentClaimable) payment_recvd).purpose); - assert purpose instanceof bindings.LDKPaymentPurpose.InvoicePayment; - bindings.ChannelManager_claim_funds(peer2.chan_manager, ((bindings.LDKPaymentPurpose.InvoicePayment) purpose).payment_preimage); - bindings.Event_free(events.remove(0)); - - bindings.EventsProvider_process_pending_events(peer2.chan_manager_events, handler); - assert events.size() == 1; - bindings.LDKEvent payment_claimed = bindings.LDKEvent_ref_from_ptr(events.get(0)); - assert payment_claimed instanceof bindings.LDKEvent.PaymentClaimed; - bindings.Event_free(events.remove(0)); - - deliver_peer_messages(list, peer1.peer_manager, peer2.peer_manager); - - bindings.EventsProvider_process_pending_events(peer1.chan_manager_events, handler); - assert events.size() == 2; - bindings.LDKEvent sent = bindings.LDKEvent_ref_from_ptr(events.get(0)); - assert sent instanceof bindings.LDKEvent.PaymentSent; - bindings.Event_free(events.remove(0)); - bindings.LDKEvent sent_path = bindings.LDKEvent_ref_from_ptr(events.get(0)); - assert sent_path instanceof bindings.LDKEvent.PaymentPathSuccessful; - bindings.Event_free(events.remove(0)); - Reference.reachabilityFence(events_adder); - - bindings.EventHandler_free(handler); - - peer1.free(); - peer2.free(); - bindings.SocketDescriptor_free(descriptor2); - bindings.SocketDescriptor_free(descriptor1.val); - } -} -- 2.39.5