+ Destination::BlindedPath(BlindedPath { blinded_hops, .. }) => blinded_hops.len(),
+ }
+ }
+
+ fn first_node(&self) -> PublicKey {
+ match self {
+ Destination::Node(node_id) => *node_id,
+ Destination::BlindedPath(BlindedPath { introduction_node_id: node_id, .. }) => *node_id,
+ }
+ }
+}
+
+/// Errors that may occur when [sending an onion message].
+///
+/// [sending an onion message]: OnionMessenger::send_onion_message
+#[derive(Debug, PartialEq, Eq)]
+pub enum SendError {
+ /// Errored computing onion message packet keys.
+ Secp256k1(secp256k1::Error),
+ /// Because implementations such as Eclair will drop onion messages where the message packet
+ /// exceeds 32834 bytes, we refuse to send messages where the packet exceeds this size.
+ TooBigPacket,
+ /// The provided [`Destination`] was an invalid [`BlindedPath`] due to not having any blinded
+ /// hops.
+ TooFewBlindedHops,
+ /// Our next-hop peer was offline or does not support onion message forwarding.
+ InvalidFirstHop,
+ /// 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), SendError>
+where
+ ES::Target: EntropySource,
+ NS::Target: NodeSigner,
+{
+ let OnionMessagePath { intermediate_nodes, mut destination } = 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)?;
+
+ Ok((first_node_id, OnionMessage {
+ blinding_point,
+ onion_routing_packet
+ }))
+}
+
+/// Decode one layer of an incoming [`OnionMessage`].
+///
+/// Returns either the next layer of the onion for forwarding or the decrypted content for the
+/// receiver.
+pub fn peel_onion_message<NS: Deref, L: Deref, CMH: Deref>(
+ msg: &OnionMessage, secp_ctx: &Secp256k1<secp256k1::All>, node_signer: NS, logger: L,
+ custom_handler: CMH,
+) -> Result<PeeledOnion<<<CMH>::Target as CustomOnionMessageHandler>::CustomMessage>, ()>
+where
+ NS::Target: NodeSigner,
+ L::Target: Logger,
+ CMH::Target: CustomOnionMessageHandler,
+{
+ let control_tlvs_ss = match node_signer.ecdh(Recipient::Node, &msg.blinding_point, None) {
+ Ok(ss) => ss,
+ Err(e) => {
+ log_error!(logger, "Failed to retrieve node secret: {:?}", e);
+ return Err(());