+ /// The first hop is not a peer and doesn't have a known [`SocketAddress`].
+ InvalidFirstHop(PublicKey),
+ /// A path from the sender to the destination could not be found by the [`MessageRouter`].
+ PathNotFound,
+ /// Onion message contents must have a TLV type >= 64.
+ InvalidMessage,
+ /// Our next-hop peer's buffer was full or our total outbound buffer was full.
+ BufferFull,
+ /// Failed to retrieve our node id from the provided [`NodeSigner`].
+ ///
+ /// [`NodeSigner`]: crate::sign::NodeSigner
+ GetNodeIdFailed,
+ /// We attempted to send to a blinded path where we are the introduction node, and failed to
+ /// advance the blinded path to make the second hop the new introduction node. Either
+ /// [`NodeSigner::ecdh`] failed, we failed to tweak the current blinding point to get the
+ /// new blinding point, or we were attempting to send to ourselves.
+ BlindedPathAdvanceFailed,
+}
+
+/// Handler for custom onion messages. If you are using [`SimpleArcOnionMessenger`],
+/// [`SimpleRefOnionMessenger`], or prefer to ignore inbound custom onion messages,
+/// [`IgnoringMessageHandler`] must be provided to [`OnionMessenger::new`]. Otherwise, a custom
+/// implementation of this trait must be provided, with [`CustomMessage`] specifying the supported
+/// message types.
+///
+/// See [`OnionMessenger`] for example usage.
+///
+/// [`IgnoringMessageHandler`]: crate::ln::peer_handler::IgnoringMessageHandler
+/// [`CustomMessage`]: Self::CustomMessage
+pub trait CustomOnionMessageHandler {
+ /// The message known to the handler. To support multiple message types, you may want to make this
+ /// an enum with a variant for each supported message.
+ type CustomMessage: OnionMessageContents;
+
+ /// Called with the custom message that was received, returning a response to send, if any.
+ ///
+ /// The returned [`Self::CustomMessage`], if any, is enqueued to be sent by [`OnionMessenger`].
+ fn handle_custom_message(&self, msg: Self::CustomMessage) -> Option<Self::CustomMessage>;
+
+ /// Read a custom message of type `message_type` from `buffer`, returning `Ok(None)` if the
+ /// message type is unknown.
+ fn read_custom_message<R: io::Read>(&self, message_type: u64, buffer: &mut R) -> Result<Option<Self::CustomMessage>, msgs::DecodeError>;
+
+ /// Releases any [`Self::CustomMessage`]s that need to be sent.
+ ///
+ /// Typically, this is used for messages initiating a message flow rather than in response to
+ /// another message. The latter should use the return value of [`Self::handle_custom_message`].
+ #[cfg(not(c_bindings))]
+ fn release_pending_custom_messages(&self) -> Vec<PendingOnionMessage<Self::CustomMessage>>;
+
+ /// Releases any [`Self::CustomMessage`]s that need to be sent.
+ ///
+ /// Typically, this is used for messages initiating a message flow rather than in response to
+ /// another message. The latter should use the return value of [`Self::handle_custom_message`].
+ #[cfg(c_bindings)]
+ fn release_pending_custom_messages(&self) -> Vec<(Self::CustomMessage, Destination, Option<BlindedPath>)>;
+}
+
+/// A processed incoming onion message, containing either a Forward (another onion message)
+/// or a Receive payload with decrypted contents.
+pub enum PeeledOnion<T: OnionMessageContents> {
+ /// Forwarded onion, with the next node id and a new onion
+ Forward(PublicKey, OnionMessage),
+ /// Received onion message, with decrypted contents, path_id, and reply path
+ Receive(ParsedOnionMessageContents<T>, Option<[u8; 32]>, Option<BlindedPath>)
+}
+
+/// Creates an [`OnionMessage`] with the given `contents` for sending to the destination of
+/// `path`.
+///
+/// Returns both the node id of the peer to send the message to and the message itself.
+pub fn create_onion_message<ES: Deref, NS: Deref, T: OnionMessageContents>(
+ entropy_source: &ES, node_signer: &NS, secp_ctx: &Secp256k1<secp256k1::All>,
+ path: OnionMessagePath, contents: T, reply_path: Option<BlindedPath>,
+) -> Result<(PublicKey, OnionMessage, Option<Vec<SocketAddress>>), SendError>
+where
+ ES::Target: EntropySource,
+ NS::Target: NodeSigner,
+{
+ let OnionMessagePath { intermediate_nodes, mut destination, addresses } = path;
+ if let Destination::BlindedPath(BlindedPath { ref blinded_hops, .. }) = destination {
+ if blinded_hops.is_empty() {
+ return Err(SendError::TooFewBlindedHops);
+ }
+ }
+
+ if contents.tlv_type() < 64 { return Err(SendError::InvalidMessage) }
+
+ // If we are sending straight to a blinded path and we are the introduction node, we need to
+ // advance the blinded path by 1 hop so the second hop is the new introduction node.
+ if intermediate_nodes.len() == 0 {
+ if let Destination::BlindedPath(ref mut blinded_path) = destination {
+ let our_node_id = node_signer.get_node_id(Recipient::Node)
+ .map_err(|()| SendError::GetNodeIdFailed)?;
+ if blinded_path.introduction_node_id == our_node_id {
+ advance_path_by_one(blinded_path, node_signer, &secp_ctx)
+ .map_err(|()| SendError::BlindedPathAdvanceFailed)?;
+ }
+ }
+ }
+
+ let blinding_secret_bytes = entropy_source.get_secure_random_bytes();
+ let blinding_secret = SecretKey::from_slice(&blinding_secret_bytes[..]).expect("RNG is busted");
+ let (first_node_id, blinding_point) = if let Some(first_node_id) = intermediate_nodes.first() {
+ (*first_node_id, PublicKey::from_secret_key(&secp_ctx, &blinding_secret))
+ } else {
+ match destination {
+ Destination::Node(pk) => (pk, PublicKey::from_secret_key(&secp_ctx, &blinding_secret)),
+ Destination::BlindedPath(BlindedPath { introduction_node_id, blinding_point, .. }) =>
+ (introduction_node_id, blinding_point),
+ }
+ };
+ let (packet_payloads, packet_keys) = packet_payloads_and_keys(
+ &secp_ctx, &intermediate_nodes, destination, contents, reply_path, &blinding_secret)
+ .map_err(|e| SendError::Secp256k1(e))?;
+
+ let prng_seed = entropy_source.get_secure_random_bytes();
+ let onion_routing_packet = construct_onion_message_packet(
+ packet_payloads, packet_keys, prng_seed).map_err(|()| SendError::TooBigPacket)?;
+
+ let message = OnionMessage { blinding_point, onion_routing_packet };
+ Ok((first_node_id, message, addresses))