From: Valentine Wallace Date: Wed, 5 Jun 2024 20:00:18 +0000 (-0400) Subject: AsyncPaymentsMessageHandler trait for OnionMessenger X-Git-Tag: v0.0.124-beta~70^2~4 X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=commitdiff_plain;h=e8f154dd3c299c7988762909df48b0c9d919d6f8;p=rust-lightning AsyncPaymentsMessageHandler trait for OnionMessenger Add a trait for handling async payments messages to OnionMessenger. This allows users to either provide their own custom handling for async payments messages or rely on a version provided by LDK. --- diff --git a/fuzz/src/onion_message.rs b/fuzz/src/onion_message.rs index a8a290fef..ba76815af 100644 --- a/fuzz/src/onion_message.rs +++ b/fuzz/src/onion_message.rs @@ -12,6 +12,9 @@ use lightning::ln::msgs::{self, DecodeError, OnionMessageHandler}; use lightning::ln::script::ShutdownScript; use lightning::offers::invoice::UnsignedBolt12Invoice; use lightning::offers::invoice_request::UnsignedInvoiceRequest; +use lightning::onion_message::async_payments::{ + AsyncPaymentsMessage, AsyncPaymentsMessageHandler, HeldHtlcAvailable, ReleaseHeldHtlc, +}; use lightning::onion_message::messenger::{ CustomOnionMessageHandler, Destination, MessageRouter, OnionMessagePath, OnionMessenger, PendingOnionMessage, Responder, ResponseInstruction, @@ -39,6 +42,7 @@ pub fn do_test(data: &[u8], logger: &L) { let node_id_lookup = EmptyNodeIdLookUp {}; let message_router = TestMessageRouter {}; let offers_msg_handler = TestOffersMessageHandler {}; + let async_payments_msg_handler = TestAsyncPaymentsMessageHandler {}; let custom_msg_handler = TestCustomMessageHandler {}; let onion_messenger = OnionMessenger::new( &keys_manager, @@ -47,6 +51,7 @@ pub fn do_test(data: &[u8], logger: &L) { &node_id_lookup, &message_router, &offers_msg_handler, + &async_payments_msg_handler, &custom_msg_handler, ); @@ -105,6 +110,17 @@ impl OffersMessageHandler for TestOffersMessageHandler { } } +struct TestAsyncPaymentsMessageHandler {} + +impl AsyncPaymentsMessageHandler for TestAsyncPaymentsMessageHandler { + fn held_htlc_available( + &self, _message: HeldHtlcAvailable, _responder: Option, + ) -> ResponseInstruction { + ResponseInstruction::NoResponse + } + fn release_held_htlc(&self, _message: ReleaseHeldHtlc) {} +} + #[derive(Debug)] struct TestCustomMessage {} diff --git a/lightning-background-processor/src/lib.rs b/lightning-background-processor/src/lib.rs index 4719d7e5c..aae64e981 100644 --- a/lightning-background-processor/src/lib.rs +++ b/lightning-background-processor/src/lib.rs @@ -568,7 +568,7 @@ use core::task; /// # type NetworkGraph = lightning::routing::gossip::NetworkGraph>; /// # type P2PGossipSync
    = lightning::routing::gossip::P2PGossipSync, Arc
      , Arc>; /// # type ChannelManager = lightning::ln::channelmanager::SimpleArcChannelManager, B, FE, Logger>; -/// # type OnionMessenger = lightning::onion_message::messenger::OnionMessenger, Arc, Arc, Arc>, Arc, Arc, Arc>>, Arc>, lightning::ln::peer_handler::IgnoringMessageHandler>; +/// # type OnionMessenger = lightning::onion_message::messenger::OnionMessenger, Arc, Arc, Arc>, Arc, Arc, Arc>>, Arc>, lightning::ln::peer_handler::IgnoringMessageHandler, lightning::ln::peer_handler::IgnoringMessageHandler>; /// # type Scorer = RwLock, Arc>>; /// # type PeerManager = lightning::ln::peer_handler::SimpleArcPeerManager, B, FE, Arc
        , Logger>; /// # @@ -996,7 +996,7 @@ mod tests { type PGS = Arc>>, Arc, Arc>>; type RGS = Arc>>, Arc>>; - type OM = OnionMessenger, Arc, Arc, Arc, Arc>>, Arc, Arc>>, IgnoringMessageHandler, IgnoringMessageHandler>; + type OM = OnionMessenger, Arc, Arc, Arc, Arc>>, Arc, Arc>>, IgnoringMessageHandler, IgnoringMessageHandler, IgnoringMessageHandler>; struct Node { node: Arc, @@ -1291,7 +1291,7 @@ mod tests { let best_block = BestBlock::from_network(network); let params = ChainParameters { network, best_block }; let manager = Arc::new(ChannelManager::new(fee_estimator.clone(), chain_monitor.clone(), tx_broadcaster.clone(), router.clone(), logger.clone(), keys_manager.clone(), keys_manager.clone(), keys_manager.clone(), UserConfig::default(), params, genesis_block.header.time)); - let messenger = Arc::new(OnionMessenger::new(keys_manager.clone(), keys_manager.clone(), logger.clone(), manager.clone(), msg_router.clone(), IgnoringMessageHandler {}, IgnoringMessageHandler {})); + let messenger = Arc::new(OnionMessenger::new(keys_manager.clone(), keys_manager.clone(), logger.clone(), manager.clone(), msg_router.clone(), IgnoringMessageHandler {}, IgnoringMessageHandler {}, IgnoringMessageHandler {})); let wallet = Arc::new(TestWallet {}); let sweeper = Arc::new(OutputSweeper::new(best_block, Arc::clone(&tx_broadcaster), Arc::clone(&fee_estimator), None::>, Arc::clone(&keys_manager), wallet, Arc::clone(&kv_store), Arc::clone(&logger))); diff --git a/lightning/src/ln/functional_test_utils.rs b/lightning/src/ln/functional_test_utils.rs index 7e57f2059..079f6345f 100644 --- a/lightning/src/ln/functional_test_utils.rs +++ b/lightning/src/ln/functional_test_utils.rs @@ -421,6 +421,7 @@ type TestOnionMessenger<'chan_man, 'node_cfg, 'chan_mon_cfg> = OnionMessenger< &'node_cfg test_utils::TestMessageRouter<'chan_mon_cfg>, &'chan_man TestChannelManager<'node_cfg, 'chan_mon_cfg>, IgnoringMessageHandler, + IgnoringMessageHandler, >; /// For use with [`OnionMessenger`] otherwise `test_restored_packages_retry` will fail. This is @@ -3228,7 +3229,7 @@ pub fn create_network<'a, 'b: 'a, 'c: 'b>(node_count: usize, cfgs: &'b Vec, + ) -> ResponseInstruction { + ResponseInstruction::NoResponse + } + fn release_held_htlc(&self, _message: ReleaseHeldHtlc) {} +} impl CustomOnionMessageHandler for IgnoringMessageHandler { type CustomMessage = Infallible; fn handle_custom_message(&self, _message: Self::CustomMessage, _responder: Option) -> ResponseInstruction { diff --git a/lightning/src/onion_message/async_payments.rs b/lightning/src/onion_message/async_payments.rs index aa6779fb3..f5953c636 100644 --- a/lightning/src/onion_message/async_payments.rs +++ b/lightning/src/onion_message/async_payments.rs @@ -11,13 +11,55 @@ use crate::io; use crate::ln::msgs::DecodeError; +use crate::onion_message::messenger::PendingOnionMessage; +use crate::onion_message::messenger::{Responder, ResponseInstruction}; use crate::onion_message::packet::OnionMessageContents; +use crate::prelude::*; use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer}; // TLV record types for the `onionmsg_tlv` TLV stream as defined in BOLT 4. const HELD_HTLC_AVAILABLE_TLV_TYPE: u64 = 72; const RELEASE_HELD_HTLC_TLV_TYPE: u64 = 74; +/// A handler for an [`OnionMessage`] containing an async payments message as its payload. +/// +/// [`OnionMessage`]: crate::ln::msgs::OnionMessage +pub trait AsyncPaymentsMessageHandler { + /// Handle a [`HeldHtlcAvailable`] message. A [`ReleaseHeldHtlc`] should be returned to release + /// the held funds. + fn held_htlc_available( + &self, message: HeldHtlcAvailable, responder: Option, + ) -> ResponseInstruction; + + /// Handle a [`ReleaseHeldHtlc`] message. If authentication of the message succeeds, an HTLC + /// should be released to the corresponding payee. + fn release_held_htlc(&self, message: ReleaseHeldHtlc); + + /// Release any [`AsyncPaymentsMessage`]s that need to be sent. + /// + /// Typically, this is used for messages initiating an async payment flow rather than in response + /// to another message. + #[cfg(not(c_bindings))] + fn release_pending_messages(&self) -> Vec> { + vec![] + } + + /// Release any [`AsyncPaymentsMessage`]s that need to be sent. + /// + /// Typically, this is used for messages initiating a payment flow rather than in response to + /// another message. + #[cfg(c_bindings)] + fn release_pending_messages( + &self, + ) -> Vec<( + AsyncPaymentsMessage, + crate::onion_message::messenger::Destination, + Option, + )> { + vec![] + } +} + /// Possible async payment messages sent and received via an [`OnionMessage`]. /// /// [`OnionMessage`]: crate::ln::msgs::OnionMessage diff --git a/lightning/src/onion_message/functional_tests.rs b/lightning/src/onion_message/functional_tests.rs index 08be1b2c5..9a2dc36f8 100644 --- a/lightning/src/onion_message/functional_tests.rs +++ b/lightning/src/onion_message/functional_tests.rs @@ -19,6 +19,7 @@ use crate::routing::test_utils::{add_channel, add_or_update_node}; use crate::sign::{NodeSigner, Recipient}; use crate::util::ser::{FixedLengthReader, LengthReadable, Writeable, Writer}; use crate::util::test_utils; +use super::async_payments::{AsyncPaymentsMessageHandler, HeldHtlcAvailable, ReleaseHeldHtlc}; use super::messenger::{CustomOnionMessageHandler, DefaultMessageRouter, Destination, OnionMessagePath, OnionMessenger, PendingOnionMessage, Responder, ResponseInstruction, SendError, SendSuccess}; use super::offers::{OffersMessage, OffersMessageHandler}; use super::packet::{OnionMessageContents, Packet}; @@ -50,6 +51,7 @@ struct MessengerNode { Arc >>, Arc, + Arc, Arc >, custom_message_handler: Arc, @@ -79,6 +81,17 @@ impl OffersMessageHandler for TestOffersMessageHandler { } } +struct TestAsyncPaymentsMessageHandler {} + +impl AsyncPaymentsMessageHandler for TestAsyncPaymentsMessageHandler { + fn held_htlc_available( + &self, _message: HeldHtlcAvailable, _responder: Option, + ) -> ResponseInstruction { + ResponseInstruction::NoResponse + } + fn release_held_htlc(&self, _message: ReleaseHeldHtlc) {} +} + #[derive(Clone, Debug, PartialEq)] enum TestCustomMessage { Ping, @@ -249,18 +262,19 @@ fn create_nodes_using_cfgs(cfgs: Vec) -> Vec { DefaultMessageRouter::new(network_graph.clone(), entropy_source.clone()) ); let offers_message_handler = Arc::new(TestOffersMessageHandler {}); + let async_payments_message_handler = Arc::new(TestAsyncPaymentsMessageHandler {}); let custom_message_handler = Arc::new(TestCustomMessageHandler::new()); let messenger = if cfg.intercept_offline_peer_oms { OnionMessenger::new_with_offline_peer_interception( entropy_source.clone(), node_signer.clone(), logger.clone(), node_id_lookup, message_router, offers_message_handler, - custom_message_handler.clone() + async_payments_message_handler, custom_message_handler.clone() ) } else { OnionMessenger::new( entropy_source.clone(), node_signer.clone(), logger.clone(), node_id_lookup, message_router, offers_message_handler, - custom_message_handler.clone() + async_payments_message_handler, custom_message_handler.clone() ) }; nodes.push(MessengerNode { diff --git a/lightning/src/onion_message/messenger.rs b/lightning/src/onion_message/messenger.rs index c991c5bcc..2e47e7c84 100644 --- a/lightning/src/onion_message/messenger.rs +++ b/lightning/src/onion_message/messenger.rs @@ -24,6 +24,7 @@ use crate::ln::features::{InitFeatures, NodeFeatures}; use crate::ln::msgs::{self, OnionMessage, OnionMessageHandler, SocketAddress}; use crate::ln::onion_utils; use crate::routing::gossip::{NetworkGraph, NodeId, ReadOnlyNetworkGraph}; +use super::async_payments::{AsyncPaymentsMessage, AsyncPaymentsMessageHandler}; use super::packet::OnionMessageContents; use super::packet::ParsedOnionMessageContents; use super::offers::OffersMessageHandler; @@ -76,22 +77,27 @@ pub trait AOnionMessenger { type OffersMessageHandler: OffersMessageHandler + ?Sized; /// A type that may be dereferenced to [`Self::OffersMessageHandler`] type OMH: Deref; + /// A type implementing [`AsyncPaymentsMessageHandler`] + type AsyncPaymentsMessageHandler: AsyncPaymentsMessageHandler + ?Sized; + /// A type that may be dereferenced to [`Self::AsyncPaymentsMessageHandler`] + type APH: Deref; /// A type implementing [`CustomOnionMessageHandler`] type CustomOnionMessageHandler: CustomOnionMessageHandler + ?Sized; /// A type that may be dereferenced to [`Self::CustomOnionMessageHandler`] type CMH: Deref; /// Returns a reference to the actual [`OnionMessenger`] object. - fn get_om(&self) -> &OnionMessenger; + fn get_om(&self) -> &OnionMessenger; } -impl AOnionMessenger -for OnionMessenger where +impl AOnionMessenger +for OnionMessenger where ES::Target: EntropySource, NS::Target: NodeSigner, L::Target: Logger, NL::Target: NodeIdLookUp, MR::Target: MessageRouter, OMH::Target: OffersMessageHandler, + APH:: Target: AsyncPaymentsMessageHandler, CMH::Target: CustomOnionMessageHandler, { type EntropySource = ES::Target; @@ -106,9 +112,11 @@ for OnionMessenger where type MR = MR; type OffersMessageHandler = OMH::Target; type OMH = OMH; + type AsyncPaymentsMessageHandler = APH::Target; + type APH = APH; type CustomOnionMessageHandler = CMH::Target; type CMH = CMH; - fn get_om(&self) -> &OnionMessenger { self } + fn get_om(&self) -> &OnionMessenger { self } } /// A sender, receiver and forwarder of [`OnionMessage`]s. @@ -180,11 +188,12 @@ for OnionMessenger where /// # let message_router = Arc::new(FakeMessageRouter {}); /// # let custom_message_handler = IgnoringMessageHandler {}; /// # let offers_message_handler = IgnoringMessageHandler {}; +/// # let async_payments_message_handler = IgnoringMessageHandler {}; /// // Create the onion messenger. This must use the same `keys_manager` as is passed to your /// // ChannelManager. /// let onion_messenger = OnionMessenger::new( /// &keys_manager, &keys_manager, logger, &node_id_lookup, message_router, -/// &offers_message_handler, &custom_message_handler +/// &offers_message_handler, &async_payments_message_handler, &custom_message_handler /// ); /// # #[derive(Debug)] @@ -225,14 +234,16 @@ for OnionMessenger where /// /// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest /// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice -pub struct OnionMessenger -where +pub struct OnionMessenger< + ES: Deref, NS: Deref, L: Deref, NL: Deref, MR: Deref, OMH: Deref, APH: Deref, CMH: Deref +> where ES::Target: EntropySource, NS::Target: NodeSigner, L::Target: Logger, NL::Target: NodeIdLookUp, MR::Target: MessageRouter, OMH::Target: OffersMessageHandler, + APH::Target: AsyncPaymentsMessageHandler, CMH::Target: CustomOnionMessageHandler, { entropy_source: ES, @@ -243,6 +254,7 @@ where node_id_lookup: NL, message_router: MR, offers_handler: OMH, + async_payments_handler: APH, custom_handler: CMH, intercept_messages_for_offline_peers: bool, pending_events: Mutex, @@ -986,8 +998,8 @@ where } } -impl -OnionMessenger +impl +OnionMessenger where ES::Target: EntropySource, NS::Target: NodeSigner, @@ -995,17 +1007,18 @@ where NL::Target: NodeIdLookUp, MR::Target: MessageRouter, OMH::Target: OffersMessageHandler, + APH::Target: AsyncPaymentsMessageHandler, CMH::Target: CustomOnionMessageHandler, { /// Constructs a new `OnionMessenger` to send, forward, and delegate received onion messages to /// their respective handlers. pub fn new( entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL, message_router: MR, - offers_handler: OMH, custom_handler: CMH + offers_handler: OMH, async_payments_handler: APH, custom_handler: CMH ) -> Self { Self::new_inner( entropy_source, node_signer, logger, node_id_lookup, message_router, - offers_handler, custom_handler, false + offers_handler, async_payments_handler, custom_handler, false ) } @@ -1032,17 +1045,17 @@ where /// peers. pub fn new_with_offline_peer_interception( entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL, - message_router: MR, offers_handler: OMH, custom_handler: CMH + message_router: MR, offers_handler: OMH, async_payments_handler: APH, custom_handler: CMH ) -> Self { Self::new_inner( entropy_source, node_signer, logger, node_id_lookup, message_router, - offers_handler, custom_handler, true + offers_handler, async_payments_handler, custom_handler, true ) } fn new_inner( entropy_source: ES, node_signer: NS, logger: L, node_id_lookup: NL, - message_router: MR, offers_handler: OMH, custom_handler: CMH, + message_router: MR, offers_handler: OMH, async_payments_handler: APH, custom_handler: CMH, intercept_messages_for_offline_peers: bool ) -> Self { let mut secp_ctx = Secp256k1::new(); @@ -1056,6 +1069,7 @@ where node_id_lookup, message_router, offers_handler, + async_payments_handler, custom_handler, intercept_messages_for_offline_peers, pending_events: Mutex::new(PendingEvents { @@ -1360,8 +1374,8 @@ fn outbound_buffer_full(peer_node_id: &PublicKey, buffer: &HashMap EventsProvider -for OnionMessenger +impl EventsProvider +for OnionMessenger where ES::Target: EntropySource, NS::Target: NodeSigner, @@ -1369,6 +1383,7 @@ where NL::Target: NodeIdLookUp, MR::Target: MessageRouter, OMH::Target: OffersMessageHandler, + APH::Target: AsyncPaymentsMessageHandler, CMH::Target: CustomOnionMessageHandler, { fn process_pending_events(&self, handler: H) where H::Target: EventHandler { @@ -1400,8 +1415,8 @@ where } } -impl OnionMessageHandler -for OnionMessenger +impl OnionMessageHandler +for OnionMessenger where ES::Target: EntropySource, NS::Target: NodeSigner, @@ -1409,6 +1424,7 @@ where NL::Target: NodeIdLookUp, MR::Target: MessageRouter, OMH::Target: OffersMessageHandler, + APH::Target: AsyncPaymentsMessageHandler, CMH::Target: CustomOnionMessageHandler, { fn handle_onion_message(&self, peer_node_id: &PublicKey, msg: &OnionMessage) { @@ -1428,7 +1444,18 @@ where let response_instructions = self.offers_handler.handle_message(msg, responder); let _ = self.handle_onion_message_response(response_instructions); }, - ParsedOnionMessageContents::AsyncPayments(_msg) => todo!(), + ParsedOnionMessageContents::AsyncPayments(AsyncPaymentsMessage::HeldHtlcAvailable(msg)) => { + let responder = reply_path.map( + |reply_path| Responder::new(reply_path, path_id) + ); + let response_instructions = self.async_payments_handler.held_htlc_available( + msg, responder + ); + let _ = self.handle_onion_message_response(response_instructions); + }, + ParsedOnionMessageContents::AsyncPayments(AsyncPaymentsMessage::ReleaseHeldHtlc(msg)) => { + self.async_payments_handler.release_held_htlc(msg); + }, ParsedOnionMessageContents::Custom(msg) => { let responder = reply_path.map( |reply_path| Responder::new(reply_path, path_id) @@ -1600,6 +1627,7 @@ pub type SimpleArcOnionMessenger = OnionMessenger< Arc>, Arc>>, Arc, Arc>>, Arc>, + IgnoringMessageHandler, IgnoringMessageHandler >; @@ -1620,6 +1648,7 @@ pub type SimpleRefOnionMessenger< &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>, &'j DefaultMessageRouter<&'g NetworkGraph<&'b L>, &'b L, &'a KeysManager>, &'i SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, 'f, 'g, 'h, M, T, F, L>, + IgnoringMessageHandler, IgnoringMessageHandler >;