1 package org.ldk.structs;
3 import org.ldk.impl.bindings;
4 import org.ldk.enums.*;
6 import java.util.Arrays;
7 import java.lang.ref.Reference;
8 import javax.annotation.Nullable;
12 * A sender, receiver and forwarder of [`OnionMessage`]s.
16 * `OnionMessenger` implements [`OnionMessageHandler`], making it responsible for either forwarding
17 * messages to peers or delegating to the appropriate handler for the message type. Currently, the
18 * available handlers are:
19 * [`OffersMessageHandler`], for responding to [`InvoiceRequest`]s and paying [`Bolt12Invoice`]s
20 * [`CustomOnionMessageHandler`], for handling user-defined message types
24 * [`OnionMessage`]s are sent initially using [`OnionMessenger::send_onion_message`]. When handling
25 * a message, the matched handler may return a response message which `OnionMessenger` will send
31 * # extern crate bitcoin;
32 * # use bitcoin::hashes::_export::_core::time::Duration;
33 * # use bitcoin::hashes::hex::FromHex;
34 * # use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey, self};
35 * # use lightning::blinded_path::{BlindedPath, EmptyNodeIdLookUp};
36 * # use lightning::sign::{EntropySource, KeysManager};
37 * # use lightning::ln::peer_handler::IgnoringMessageHandler;
38 * # use lightning::onion_message::messenger::{Destination, MessageRouter, OnionMessagePath, OnionMessenger};
39 * # use lightning::onion_message::packet::OnionMessageContents;
40 * # use lightning::util::logger::{Logger, Record};
41 * # use lightning::util::ser::{Writeable, Writer};
42 * # use lightning::io;
43 * # use std::sync::Arc;
44 * # struct FakeLogger;
45 * # impl Logger for FakeLogger {
46 * # fn log(&self, record: Record) { println!(\"{:?}\" , record); }
48 * # struct FakeMessageRouter {}
49 * # impl MessageRouter for FakeMessageRouter {
50 * # fn find_path(&self, sender: PublicKey, peers: Vec<PublicKey>, destination: Destination) -> Result<OnionMessagePath, ()> {
51 * # let secp_ctx = Secp256k1::new();
52 * # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex(\"0101010101010101010101010101010101010101010101010101010101010101\").unwrap()[..]).unwrap();
53 * # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
54 * # let hop_node_id2 = hop_node_id1;
55 * # Ok(OnionMessagePath {
56 * # intermediate_nodes: vec![hop_node_id1, hop_node_id2],
58 * # first_node_addresses: None,
61 * # fn create_blinded_paths<T: secp256k1::Signing + secp256k1::Verification>(
62 * # &self, _recipient: PublicKey, _peers: Vec<PublicKey>, _secp_ctx: &Secp256k1<T>
63 * # ) -> Result<Vec<BlindedPath>, ()> {
67 * # let seed = [42u8; 32];
68 * # let time = Duration::from_secs(123456);
69 * # let keys_manager = KeysManager::new(&seed, time.as_secs(), time.subsec_nanos());
70 * # let logger = Arc::new(FakeLogger {});
71 * # let node_secret = SecretKey::from_slice(&<Vec<u8>>::from_hex(\"0101010101010101010101010101010101010101010101010101010101010101\").unwrap()[..]).unwrap();
72 * # let secp_ctx = Secp256k1::new();
73 * # let hop_node_id1 = PublicKey::from_secret_key(&secp_ctx, &node_secret);
74 * # let (hop_node_id3, hop_node_id4) = (hop_node_id1, hop_node_id1);
75 * # let destination_node_id = hop_node_id1;
76 * # let node_id_lookup = EmptyNodeIdLookUp {};
77 * # let message_router = Arc::new(FakeMessageRouter {});
78 * # let custom_message_handler = IgnoringMessageHandler {};
79 * # let offers_message_handler = IgnoringMessageHandler {};
80 * Create the onion messenger. This must use the same `keys_manager` as is passed to your
82 * let onion_messenger = OnionMessenger::new(
83 * &keys_manager, &keys_manager, logger, &node_id_lookup, message_router,
84 * &offers_message_handler, &custom_message_handler
87 * # #[derive(Debug, Clone)]
88 * # struct YourCustomMessage {}
89 * impl Writeable for YourCustomMessage {
90 * \tfn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
92 * \t\t// Write your custom onion message to `w`
95 * impl OnionMessageContents for YourCustomMessage {
96 * \tfn tlv_type(&self) -> u64 {
97 * \t\t# let your_custom_message_type = 42;
98 * \t\tyour_custom_message_type
101 * Send a custom onion message to a node id.
102 * let destination = Destination::Node(destination_node_id);
103 * let reply_path = None;
104 * # let message = YourCustomMessage {};
105 * onion_messenger.send_onion_message(message, destination, reply_path);
107 * Create a blinded path to yourself, for someone to send an onion message to.
108 * # let your_node_id = hop_node_id1;
109 * let hops = [hop_node_id3, hop_node_id4, your_node_id];
110 * let blinded_path = BlindedPath::new_for_message(&hops, &keys_manager, &secp_ctx).unwrap();
112 * Send a custom onion message to a blinded path.
113 * let destination = Destination::BlindedPath(blinded_path);
114 * let reply_path = None;
115 * # let message = YourCustomMessage {};
116 * onion_messenger.send_onion_message(message, destination, reply_path);
119 * [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
120 * [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
122 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
123 public class OnionMessenger extends CommonBase {
124 OnionMessenger(Object _dummy, long ptr) { super(ptr); }
125 @Override @SuppressWarnings("deprecation")
126 protected void finalize() throws Throwable {
128 if (ptr != 0) { bindings.OnionMessenger_free(ptr); }
132 * Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to
133 * their respective handlers.
135 public static OnionMessenger of(org.ldk.structs.EntropySource entropy_source, org.ldk.structs.NodeSigner node_signer, org.ldk.structs.Logger logger, org.ldk.structs.NodeIdLookUp node_id_lookup, org.ldk.structs.MessageRouter message_router, org.ldk.structs.OffersMessageHandler offers_handler, org.ldk.structs.CustomOnionMessageHandler custom_handler) {
136 long ret = bindings.OnionMessenger_new(entropy_source.ptr, node_signer.ptr, logger.ptr, node_id_lookup.ptr, message_router.ptr, offers_handler.ptr, custom_handler.ptr);
137 Reference.reachabilityFence(entropy_source);
138 Reference.reachabilityFence(node_signer);
139 Reference.reachabilityFence(logger);
140 Reference.reachabilityFence(node_id_lookup);
141 Reference.reachabilityFence(message_router);
142 Reference.reachabilityFence(offers_handler);
143 Reference.reachabilityFence(custom_handler);
144 if (ret >= 0 && ret <= 4096) { return null; }
145 org.ldk.structs.OnionMessenger ret_hu_conv = null; if (ret < 0 || ret > 4096) { ret_hu_conv = new org.ldk.structs.OnionMessenger(null, ret); }
146 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(ret_hu_conv); };
147 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(entropy_source); };
148 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(node_signer); };
149 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(logger); };
150 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(node_id_lookup); };
151 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(message_router); };
152 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(offers_handler); };
153 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(custom_handler); };
158 * Sends an [`OnionMessage`] with the given `contents` to `destination`.
160 * See [`OnionMessenger`] for example usage.
162 * Note that reply_path (or a relevant inner pointer) may be NULL or all-0s to represent None
164 public Result_SendSuccessSendErrorZ send_onion_message(org.ldk.structs.OnionMessageContents contents, org.ldk.structs.Destination destination, @Nullable org.ldk.structs.BlindedPath reply_path) {
165 long ret = bindings.OnionMessenger_send_onion_message(this.ptr, contents.ptr, destination.ptr, reply_path == null ? 0 : reply_path.ptr);
166 Reference.reachabilityFence(this);
167 Reference.reachabilityFence(contents);
168 Reference.reachabilityFence(destination);
169 Reference.reachabilityFence(reply_path);
170 if (ret >= 0 && ret <= 4096) { return null; }
171 Result_SendSuccessSendErrorZ ret_hu_conv = Result_SendSuccessSendErrorZ.constr_from_ptr(ret);
172 if (this != null) { this.ptrs_to.add(contents); };
173 if (this != null) { this.ptrs_to.add(destination); };
174 if (this != null) { this.ptrs_to.add(reply_path); };
179 * Constructs a new OnionMessageHandler which calls the relevant methods on this_arg.
180 * This copies the `inner` pointer in this_arg and thus the returned OnionMessageHandler must be freed before this_arg is
182 public OnionMessageHandler as_OnionMessageHandler() {
183 long ret = bindings.OnionMessenger_as_OnionMessageHandler(this.ptr);
184 Reference.reachabilityFence(this);
185 if (ret >= 0 && ret <= 4096) { return null; }
186 OnionMessageHandler ret_hu_conv = new OnionMessageHandler(null, ret);
187 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(this); };