Skip to content

Commit dd11cb4

Browse files
committed
Finish Bolt12 move from ChannelManager to Flow
1 parent d378166 commit dd11cb4

File tree

3 files changed

+222
-234
lines changed

3 files changed

+222
-234
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 22 additions & 200 deletions
Original file line numberDiff line numberDiff line change
@@ -33,10 +33,9 @@ use bitcoin::secp256k1::Secp256k1;
3333
use bitcoin::{secp256k1, Sequence, Weight};
3434

3535
use crate::events::FundingInfo;
36-
use crate::blinded_path::message::{MessageContext, OffersContext};
3736
use crate::blinded_path::NodeIdLookUp;
38-
use crate::blinded_path::message::{BlindedMessagePath, MessageForwardNode};
39-
use crate::blinded_path::payment::{BlindedPaymentPath, Bolt12RefundContext, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs};
37+
use crate::blinded_path::message::MessageForwardNode;
38+
use crate::blinded_path::payment::{BlindedPaymentPath, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs};
4039
use crate::chain;
4140
use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
4241
use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
@@ -48,6 +47,7 @@ use crate::events::{self, Event, EventHandler, EventsProvider, InboundChannelFun
4847
use crate::ln::inbound_payment;
4948
use crate::ln::types::ChannelId;
5049
use crate::offers::flow::OffersMessageCommons;
50+
use crate::sign::ecdsa::EcdsaChannelSigner;
5151
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
5252
use crate::ln::channel::{self, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, ReconnectionMsg, InboundV1Channel, WithChannelContext};
5353
#[cfg(any(dual_funding, splicing))]
@@ -65,15 +65,11 @@ use crate::ln::msgs::{ChannelMessageHandler, CommitmentUpdate, DecodeError, Ligh
6565
#[cfg(test)]
6666
use crate::ln::outbound_payment;
6767
use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, SendAlongPathArgs, StaleExpiration};
68-
use crate::offers::invoice::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, InvoiceBuilder, UnsignedBolt12Invoice};
68+
use crate::offers::invoice::{Bolt12Invoice, UnsignedBolt12Invoice};
6969
use crate::offers::nonce::Nonce;
70-
use crate::offers::parse::Bolt12SemanticError;
71-
use crate::offers::refund::Refund;
7270
use crate::offers::signer;
73-
use crate::onion_message::messenger::{Destination, MessageRouter, MessageSendInstructions};
74-
use crate::onion_message::offers::OffersMessage;
71+
use crate::onion_message::messenger::MessageRouter;
7572
use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
76-
use crate::sign::ecdsa::EcdsaChannelSigner;
7773
use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
7874
use crate::util::wakers::{Future, Notifier};
7975
use crate::util::scid_utils::fake_scid;
@@ -107,7 +103,7 @@ use core::{cmp, mem};
107103
use core::borrow::Borrow;
108104
use core::cell::RefCell;
109105
use crate::io::Read;
110-
use crate::sync::{Arc, FairRwLock, LockHeldState, LockTestExt, Mutex, MutexGuard, RwLock, RwLockReadGuard};
106+
use crate::sync::{Arc, FairRwLock, LockHeldState, LockTestExt, Mutex, RwLock, RwLockReadGuard};
111107
use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
112108
use core::time::Duration;
113109
use core::ops::Deref;
@@ -458,11 +454,15 @@ impl Ord for ClaimableHTLC {
458454
pub trait Verification {
459455
/// Constructs an HMAC to include in [`OffersContext`] for the data along with the given
460456
/// [`Nonce`].
457+
///
458+
/// [`OffersContext`]: crate::blinded_path::message::OffersContext
461459
fn hmac_for_offer_payment(
462460
&self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
463461
) -> Hmac<Sha256>;
464462

465463
/// Authenticates the data using an HMAC and a [`Nonce`] taken from an [`OffersContext`].
464+
///
465+
/// [`OffersContext`]: crate::blinded_path::message::OffersContext
466466
fn verify_for_offer_payment(
467467
&self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
468468
) -> Result<(), ()>;
@@ -471,6 +471,8 @@ pub trait Verification {
471471
impl Verification for PaymentHash {
472472
/// Constructs an HMAC to include in [`OffersContext::InboundPayment`] for the payment hash
473473
/// along with the given [`Nonce`].
474+
///
475+
/// [`OffersContext::InboundPayment`]: crate::blinded_path::message::OffersContext::InboundPayment
474476
fn hmac_for_offer_payment(
475477
&self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
476478
) -> Hmac<Sha256> {
@@ -479,6 +481,8 @@ impl Verification for PaymentHash {
479481

480482
/// Authenticates the payment id using an HMAC and a [`Nonce`] taken from an
481483
/// [`OffersContext::InboundPayment`].
484+
///
485+
/// [`OffersContext::InboundPayment`]: crate::blinded_path::message::OffersContext::InboundPayment
482486
fn verify_for_offer_payment(
483487
&self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
484488
) -> Result<(), ()> {
@@ -533,6 +537,8 @@ impl PaymentId {
533537
impl Verification for PaymentId {
534538
/// Constructs an HMAC to include in [`OffersContext::OutboundPayment`] for the payment id
535539
/// along with the given [`Nonce`].
540+
///
541+
/// [`OffersContext::OutboundPayment`]: crate::blinded_path::message::OffersContext::OutboundPayment
536542
fn hmac_for_offer_payment(
537543
&self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
538544
) -> Hmac<Sha256> {
@@ -541,6 +547,8 @@ impl Verification for PaymentId {
541547

542548
/// Authenticates the payment id using an HMAC and a [`Nonce`] taken from an
543549
/// [`OffersContext::OutboundPayment`].
550+
///
551+
/// [`OffersContext::OutboundPayment`]: crate::blinded_path::message::OffersContext::OutboundPayment
544552
fn verify_for_offer_payment(
545553
&self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
546554
) -> Result<(), ()> {
@@ -2051,51 +2059,7 @@ where
20512059
///
20522060
/// For more information on creating refunds, see [`create_refund_builder`].
20532061
///
2054-
/// Use [`request_refund_payment`] to send a [`Bolt12Invoice`] for receiving the refund. Similar to
2055-
/// *creating* an [`Offer`], this is stateless as it represents an inbound payment.
2056-
///
2057-
/// ```
2058-
/// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
2059-
/// # use lightning::ln::channelmanager::AChannelManager;
2060-
/// # use lightning::offers::refund::Refund;
2061-
/// #
2062-
/// # fn example<T: AChannelManager>(channel_manager: T, refund: &Refund) {
2063-
/// # let channel_manager = channel_manager.get_cm();
2064-
/// let known_payment_hash = match channel_manager.request_refund_payment(refund) {
2065-
/// Ok(invoice) => {
2066-
/// let payment_hash = invoice.payment_hash();
2067-
/// println!("Requesting refund payment {}", payment_hash);
2068-
/// payment_hash
2069-
/// },
2070-
/// Err(e) => panic!("Unable to request payment for refund: {:?}", e),
2071-
/// };
2072-
///
2073-
/// // On the event processing thread
2074-
/// channel_manager.process_pending_events(&|event| {
2075-
/// match event {
2076-
/// Event::PaymentClaimable { payment_hash, purpose, .. } => match purpose {
2077-
/// PaymentPurpose::Bolt12RefundPayment { payment_preimage: Some(payment_preimage), .. } => {
2078-
/// assert_eq!(payment_hash, known_payment_hash);
2079-
/// println!("Claiming payment {}", payment_hash);
2080-
/// channel_manager.claim_funds(payment_preimage);
2081-
/// },
2082-
/// PaymentPurpose::Bolt12RefundPayment { payment_preimage: None, .. } => {
2083-
/// println!("Unknown payment hash: {}", payment_hash);
2084-
/// },
2085-
/// // ...
2086-
/// # _ => {},
2087-
/// },
2088-
/// Event::PaymentClaimed { payment_hash, amount_msat, .. } => {
2089-
/// assert_eq!(payment_hash, known_payment_hash);
2090-
/// println!("Claimed {} msats", amount_msat);
2091-
/// },
2092-
/// // ...
2093-
/// # _ => {},
2094-
/// }
2095-
/// Ok(())
2096-
/// });
2097-
/// # }
2098-
/// ```
2062+
/// For requesting refund payments, see [`request_refund_payment`].
20992063
///
21002064
/// # Persistence
21012065
///
@@ -2179,7 +2143,7 @@ where
21792143
/// [`create_offer_builder`]: crate::offers::flow::OffersMessageFlow::create_offer_builder
21802144
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
21812145
/// [`create_refund_builder`]: crate::offers::flow::OffersMessageFlow::create_refund_builder
2182-
/// [`request_refund_payment`]: Self::request_refund_payment
2146+
/// [`request_refund_payment`]: crate::offers::flow::OffersMessageFlow::request_refund_payment
21832147
/// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
21842148
/// [`funding_created`]: msgs::FundingCreated
21852149
/// [`funding_transaction_generated`]: Self::funding_transaction_generated
@@ -2450,11 +2414,6 @@ where
24502414
event_persist_notifier: Notifier,
24512415
needs_persist_flag: AtomicBool,
24522416

2453-
#[cfg(not(any(test, feature = "_test_utils")))]
2454-
pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
2455-
#[cfg(any(test, feature = "_test_utils"))]
2456-
pub(crate) pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
2457-
24582417
/// Tracks the message events that are to be broadcasted when we are connected to some peer.
24592418
pending_broadcast_messages: Mutex<Vec<MessageSendEvent>>,
24602419

@@ -3374,7 +3333,6 @@ where
33743333
needs_persist_flag: AtomicBool::new(false),
33753334
funding_batch_states: Mutex::new(BTreeMap::new()),
33763335

3377-
pending_offers_messages: Mutex::new(Vec::new()),
33783336
pending_broadcast_messages: Mutex::new(Vec::new()),
33793337

33803338
last_days_feerates: Mutex::new(VecDeque::new()),
@@ -9573,23 +9531,8 @@ where
95739531
fn send_payment_for_static_invoice(&self, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
95749532
self.send_payment_for_static_invoice(payment_id)
95759533
}
9576-
9577-
// ----Temporary Functions----
9578-
// Set of functions temporarily moved to OffersMessageCommons for easier
9579-
// transition of code from ChannelManager to OffersMessageFlow
9580-
9581-
fn get_pending_offers_messages(&self) -> MutexGuard<'_, Vec<(OffersMessage, MessageSendInstructions)>> {
9582-
self.pending_offers_messages.lock().expect("Mutex is locked by other thread.")
9583-
}
95849534
}
95859535

9586-
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
9587-
/// along different paths.
9588-
/// Sending multiple requests increases the chances of successful delivery in case some
9589-
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
9590-
/// even if multiple invoices are received.
9591-
pub(crate) const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
9592-
95939536
impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, MR: Deref, L: Deref> ChannelManager<M, T, ES, NS, SP, F, R, MR, L>
95949537
where
95959538
M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
@@ -9602,106 +9545,6 @@ where
96029545
MR::Target: MessageRouter,
96039546
L::Target: Logger,
96049547
{
9605-
/// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
9606-
/// message.
9607-
///
9608-
/// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
9609-
/// [`BlindedPaymentPath`] containing the [`PaymentSecret`] needed to reconstruct the
9610-
/// corresponding [`PaymentPreimage`]. It is returned purely for informational purposes.
9611-
///
9612-
/// # Limitations
9613-
///
9614-
/// Requires a direct connection to an introduction node in [`Refund::paths`] or to
9615-
/// [`Refund::payer_signing_pubkey`], if empty. This request is best effort; an invoice will be
9616-
/// sent to each node meeting the aforementioned criteria, but there's no guarantee that they
9617-
/// will be received and no retries will be made.
9618-
///
9619-
/// # Errors
9620-
///
9621-
/// Errors if:
9622-
/// - the refund is for an unsupported chain, or
9623-
/// - the parameterized [`Router`] is unable to create a blinded payment path or reply path for
9624-
/// the invoice.
9625-
///
9626-
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
9627-
pub fn request_refund_payment(
9628-
&self, refund: &Refund
9629-
) -> Result<Bolt12Invoice, Bolt12SemanticError> {
9630-
let expanded_key = &self.inbound_payment_key;
9631-
let entropy = &*self.entropy_source;
9632-
let secp_ctx = &self.secp_ctx;
9633-
9634-
let amount_msats = refund.amount_msats();
9635-
let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9636-
9637-
if refund.chain() != self.chain_hash {
9638-
return Err(Bolt12SemanticError::UnsupportedChain);
9639-
}
9640-
9641-
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9642-
9643-
match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
9644-
Ok((payment_hash, payment_secret)) => {
9645-
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
9646-
let payment_paths = self.create_blinded_payment_paths(
9647-
Some(amount_msats), payment_secret, payment_context, relative_expiry,
9648-
)
9649-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9650-
9651-
#[cfg(feature = "std")]
9652-
let builder = refund.respond_using_derived_keys(
9653-
payment_paths, payment_hash, expanded_key, entropy
9654-
)?;
9655-
#[cfg(not(feature = "std"))]
9656-
let created_at = Duration::from_secs(
9657-
self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9658-
);
9659-
#[cfg(not(feature = "std"))]
9660-
let builder = refund.respond_using_derived_keys_no_std(
9661-
payment_paths, payment_hash, created_at, expanded_key, entropy
9662-
)?;
9663-
let builder: InvoiceBuilder<DerivedSigningPubkey> = builder.into();
9664-
let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
9665-
9666-
let nonce = Nonce::from_entropy_source(entropy);
9667-
let hmac = payment_hash.hmac_for_offer_payment(nonce, expanded_key);
9668-
let context = MessageContext::Offers(OffersContext::InboundPayment {
9669-
payment_hash: invoice.payment_hash(), nonce, hmac
9670-
});
9671-
let reply_paths = self.create_blinded_paths(context)
9672-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9673-
9674-
let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
9675-
if refund.paths().is_empty() {
9676-
for reply_path in reply_paths {
9677-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9678-
destination: Destination::Node(refund.payer_signing_pubkey()),
9679-
reply_path,
9680-
};
9681-
let message = OffersMessage::Invoice(invoice.clone());
9682-
pending_offers_messages.push((message, instructions));
9683-
}
9684-
} else {
9685-
reply_paths
9686-
.iter()
9687-
.flat_map(|reply_path| refund.paths().iter().map(move |path| (path, reply_path)))
9688-
.take(OFFERS_MESSAGE_REQUEST_LIMIT)
9689-
.for_each(|(path, reply_path)| {
9690-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9691-
destination: Destination::BlindedPath(path.clone()),
9692-
reply_path: reply_path.clone(),
9693-
};
9694-
let message = OffersMessage::Invoice(invoice.clone());
9695-
pending_offers_messages.push((message, instructions));
9696-
});
9697-
}
9698-
9699-
Ok(invoice)
9700-
},
9701-
Err(()) => Err(Bolt12SemanticError::InvalidAmount),
9702-
}
9703-
}
9704-
97059548
/// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
97069549
/// to pay us.
97079550
///
@@ -9800,27 +9643,6 @@ where
98009643
inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
98019644
}
98029645

9803-
/// Creates a collection of blinded paths by delegating to
9804-
/// [`MessageRouter::create_blinded_paths`].
9805-
///
9806-
/// Errors if the `MessageRouter` errors.
9807-
fn create_blinded_paths(&self, context: MessageContext) -> Result<Vec<BlindedMessagePath>, ()> {
9808-
let recipient = self.get_our_node_id();
9809-
let secp_ctx = &self.secp_ctx;
9810-
9811-
let peers = self.per_peer_state.read().unwrap()
9812-
.iter()
9813-
.map(|(node_id, peer_state)| (node_id, peer_state.lock().unwrap()))
9814-
.filter(|(_, peer)| peer.is_connected)
9815-
.filter(|(_, peer)| peer.latest_features.supports_onion_messages())
9816-
.map(|(node_id, _)| *node_id)
9817-
.collect::<Vec<_>>();
9818-
9819-
self.message_router
9820-
.create_blinded_paths(recipient, context, peers, secp_ctx)
9821-
.and_then(|paths| (!paths.is_empty()).then(|| paths).ok_or(()))
9822-
}
9823-
98249646
#[cfg(async_payments)]
98259647
pub(super) fn duration_since_epoch(&self) -> Duration {
98269648
#[cfg(not(feature = "std"))]
@@ -12078,7 +11900,9 @@ where
1207811900
/// The [`MessageRouter`] used for constructing [`BlindedMessagePath`]s for [`Offer`]s,
1207911901
/// [`Refund`]s, and any reply paths.
1208011902
///
11903+
/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
1208111904
/// [`Offer`]: crate::offers::offer::Offer
11905+
/// [`Refund`]: crate::offers::refund::Refund
1208211906
pub message_router: MR,
1208311907
/// The Logger for use in the ChannelManager and which may be used to log information during
1208411908
/// deserialization.
@@ -13181,8 +13005,6 @@ where
1318113005

1318213006
funding_batch_states: Mutex::new(BTreeMap::new()),
1318313007

13184-
pending_offers_messages: Mutex::new(Vec::new()),
13185-
1318613008
pending_broadcast_messages: Mutex::new(Vec::new()),
1318713009

1318813010
entropy_source: args.entropy_source,

0 commit comments

Comments
 (0)