Skip to content

Commit d942501

Browse files
committed
Finish Bolt12 move from ChannelManager to Flow
1 parent 7777c3b commit d942501

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};
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::{AsyncBolt12OfferContext, BlindedPaymentPath, Bolt12OfferContext, Bolt12RefundContext, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs};
37+
use crate::blinded_path::message::MessageForwardNode;
38+
use crate::blinded_path::payment::{AsyncBolt12OfferContext, BlindedPaymentPath, Bolt12OfferContext, PaymentConstraints, PaymentContext, UnauthenticatedReceiveTlvs};
4039
use crate::chain;
4140
use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
4241
use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
@@ -49,6 +48,7 @@ use crate::ln::inbound_payment;
4948
use crate::ln::types::ChannelId;
5049
use crate::offers::flow::OffersMessageCommons;
5150
use crate::offers::invoice_request::InvoiceRequest;
51+
use crate::sign::ecdsa::EcdsaChannelSigner;
5252
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
5353
use crate::ln::channel::{self, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, ReconnectionMsg, InboundV1Channel, WithChannelContext};
5454
#[cfg(any(dual_funding, splicing))]
@@ -68,15 +68,11 @@ use crate::ln::msgs::{ChannelMessageHandler, CommitmentUpdate, DecodeError, Ligh
6868
#[cfg(test)]
6969
use crate::ln::outbound_payment;
7070
use crate::ln::outbound_payment::{OutboundPayments, PendingOutboundPayment, RetryableInvoiceRequest, SendAlongPathArgs, StaleExpiration};
71-
use crate::offers::invoice::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, InvoiceBuilder, UnsignedBolt12Invoice};
71+
use crate::offers::invoice::{Bolt12Invoice, UnsignedBolt12Invoice};
7272
use crate::offers::nonce::Nonce;
73-
use crate::offers::parse::Bolt12SemanticError;
74-
use crate::offers::refund::Refund;
7573
use crate::offers::signer;
76-
use crate::onion_message::messenger::{Destination, MessageRouter, MessageSendInstructions};
77-
use crate::onion_message::offers::OffersMessage;
74+
use crate::onion_message::messenger::MessageRouter;
7875
use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
79-
use crate::sign::ecdsa::EcdsaChannelSigner;
8076
use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
8177
use crate::util::wakers::{Future, Notifier};
8278
use crate::util::scid_utils::fake_scid;
@@ -109,7 +105,7 @@ use core::{cmp, mem};
109105
use core::borrow::Borrow;
110106
use core::cell::RefCell;
111107
use crate::io::Read;
112-
use crate::sync::{Arc, FairRwLock, LockHeldState, LockTestExt, Mutex, MutexGuard, RwLock, RwLockReadGuard};
108+
use crate::sync::{Arc, FairRwLock, LockHeldState, LockTestExt, Mutex, RwLock, RwLockReadGuard};
113109
use core::sync::atomic::{AtomicUsize, AtomicBool, Ordering};
114110
use core::time::Duration;
115111
use core::ops::Deref;
@@ -486,11 +482,15 @@ impl Ord for ClaimableHTLC {
486482
pub trait Verification {
487483
/// Constructs an HMAC to include in [`OffersContext`] for the data along with the given
488484
/// [`Nonce`].
485+
///
486+
/// [`OffersContext`]: crate::blinded_path::message::OffersContext
489487
fn hmac_for_offer_payment(
490488
&self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
491489
) -> Hmac<Sha256>;
492490

493491
/// Authenticates the data using an HMAC and a [`Nonce`] taken from an [`OffersContext`].
492+
///
493+
/// [`OffersContext`]: crate::blinded_path::message::OffersContext
494494
fn verify_for_offer_payment(
495495
&self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
496496
) -> Result<(), ()>;
@@ -499,6 +499,8 @@ pub trait Verification {
499499
impl Verification for PaymentHash {
500500
/// Constructs an HMAC to include in [`OffersContext::InboundPayment`] for the payment hash
501501
/// along with the given [`Nonce`].
502+
///
503+
/// [`OffersContext::InboundPayment`]: crate::blinded_path::message::OffersContext::InboundPayment
502504
fn hmac_for_offer_payment(
503505
&self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
504506
) -> Hmac<Sha256> {
@@ -507,6 +509,8 @@ impl Verification for PaymentHash {
507509

508510
/// Authenticates the payment id using an HMAC and a [`Nonce`] taken from an
509511
/// [`OffersContext::InboundPayment`].
512+
///
513+
/// [`OffersContext::InboundPayment`]: crate::blinded_path::message::OffersContext::InboundPayment
510514
fn verify_for_offer_payment(
511515
&self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
512516
) -> Result<(), ()> {
@@ -561,6 +565,8 @@ impl PaymentId {
561565
impl Verification for PaymentId {
562566
/// Constructs an HMAC to include in [`OffersContext::OutboundPayment`] for the payment id
563567
/// along with the given [`Nonce`].
568+
///
569+
/// [`OffersContext::OutboundPayment`]: crate::blinded_path::message::OffersContext::OutboundPayment
564570
fn hmac_for_offer_payment(
565571
&self, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
566572
) -> Hmac<Sha256> {
@@ -569,6 +575,8 @@ impl Verification for PaymentId {
569575

570576
/// Authenticates the payment id using an HMAC and a [`Nonce`] taken from an
571577
/// [`OffersContext::OutboundPayment`].
578+
///
579+
/// [`OffersContext::OutboundPayment`]: crate::blinded_path::message::OffersContext::OutboundPayment
572580
fn verify_for_offer_payment(
573581
&self, hmac: Hmac<Sha256>, nonce: Nonce, expanded_key: &inbound_payment::ExpandedKey,
574582
) -> Result<(), ()> {
@@ -2079,51 +2087,7 @@ where
20792087
///
20802088
/// For more information on creating refunds, see [`create_refund_builder`].
20812089
///
2082-
/// Use [`request_refund_payment`] to send a [`Bolt12Invoice`] for receiving the refund. Similar to
2083-
/// *creating* an [`Offer`], this is stateless as it represents an inbound payment.
2084-
///
2085-
/// ```
2086-
/// # use lightning::events::{Event, EventsProvider, PaymentPurpose};
2087-
/// # use lightning::ln::channelmanager::AChannelManager;
2088-
/// # use lightning::offers::refund::Refund;
2089-
/// #
2090-
/// # fn example<T: AChannelManager>(channel_manager: T, refund: &Refund) {
2091-
/// # let channel_manager = channel_manager.get_cm();
2092-
/// let known_payment_hash = match channel_manager.request_refund_payment(refund) {
2093-
/// Ok(invoice) => {
2094-
/// let payment_hash = invoice.payment_hash();
2095-
/// println!("Requesting refund payment {}", payment_hash);
2096-
/// payment_hash
2097-
/// },
2098-
/// Err(e) => panic!("Unable to request payment for refund: {:?}", e),
2099-
/// };
2100-
///
2101-
/// // On the event processing thread
2102-
/// channel_manager.process_pending_events(&|event| {
2103-
/// match event {
2104-
/// Event::PaymentClaimable { payment_hash, purpose, .. } => match purpose {
2105-
/// PaymentPurpose::Bolt12RefundPayment { payment_preimage: Some(payment_preimage), .. } => {
2106-
/// assert_eq!(payment_hash, known_payment_hash);
2107-
/// println!("Claiming payment {}", payment_hash);
2108-
/// channel_manager.claim_funds(payment_preimage);
2109-
/// },
2110-
/// PaymentPurpose::Bolt12RefundPayment { payment_preimage: None, .. } => {
2111-
/// println!("Unknown payment hash: {}", payment_hash);
2112-
/// },
2113-
/// // ...
2114-
/// # _ => {},
2115-
/// },
2116-
/// Event::PaymentClaimed { payment_hash, amount_msat, .. } => {
2117-
/// assert_eq!(payment_hash, known_payment_hash);
2118-
/// println!("Claimed {} msats", amount_msat);
2119-
/// },
2120-
/// // ...
2121-
/// # _ => {},
2122-
/// }
2123-
/// Ok(())
2124-
/// });
2125-
/// # }
2126-
/// ```
2090+
/// For requesting refund payments, see [`request_refund_payment`].
21272091
///
21282092
/// # Persistence
21292093
///
@@ -2207,7 +2171,7 @@ where
22072171
/// [`create_offer_builder`]: crate::offers::flow::OffersMessageFlow::create_offer_builder
22082172
/// [`InvoiceRequest`]: crate::offers::invoice_request::InvoiceRequest
22092173
/// [`create_refund_builder`]: crate::offers::flow::OffersMessageFlow::create_refund_builder
2210-
/// [`request_refund_payment`]: Self::request_refund_payment
2174+
/// [`request_refund_payment`]: crate::offers::flow::OffersMessageFlow::request_refund_payment
22112175
/// [`peer_disconnected`]: msgs::ChannelMessageHandler::peer_disconnected
22122176
/// [`funding_created`]: msgs::FundingCreated
22132177
/// [`funding_transaction_generated`]: Self::funding_transaction_generated
@@ -2478,11 +2442,6 @@ where
24782442
event_persist_notifier: Notifier,
24792443
needs_persist_flag: AtomicBool,
24802444

2481-
#[cfg(not(any(test, feature = "_test_utils")))]
2482-
pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
2483-
#[cfg(any(test, feature = "_test_utils"))]
2484-
pub(crate) pending_offers_messages: Mutex<Vec<(OffersMessage, MessageSendInstructions)>>,
2485-
24862445
/// Tracks the message events that are to be broadcasted when we are connected to some peer.
24872446
pending_broadcast_messages: Mutex<Vec<MessageSendEvent>>,
24882447

@@ -3402,7 +3361,6 @@ where
34023361
needs_persist_flag: AtomicBool::new(false),
34033362
funding_batch_states: Mutex::new(BTreeMap::new()),
34043363

3405-
pending_offers_messages: Mutex::new(Vec::new()),
34063364
pending_broadcast_messages: Mutex::new(Vec::new()),
34073365

34083366
last_days_feerates: Mutex::new(VecDeque::new()),
@@ -9676,23 +9634,8 @@ where
96769634
fn send_payment_for_static_invoice(&self, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
96779635
self.send_payment_for_static_invoice(payment_id)
96789636
}
9679-
9680-
// ----Temporary Functions----
9681-
// Set of functions temporarily moved to OffersMessageCommons for easier
9682-
// transition of code from ChannelManager to OffersMessageFlow
9683-
9684-
fn get_pending_offers_messages(&self) -> MutexGuard<'_, Vec<(OffersMessage, MessageSendInstructions)>> {
9685-
self.pending_offers_messages.lock().expect("Mutex is locked by other thread.")
9686-
}
96879637
}
96889638

9689-
/// Defines the maximum number of [`OffersMessage`] including different reply paths to be sent
9690-
/// along different paths.
9691-
/// Sending multiple requests increases the chances of successful delivery in case some
9692-
/// paths are unavailable. However, only one invoice for a given [`PaymentId`] will be paid,
9693-
/// even if multiple invoices are received.
9694-
pub(crate) const OFFERS_MESSAGE_REQUEST_LIMIT: usize = 10;
9695-
96969639
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>
96979640
where
96989641
M::Target: chain::Watch<<SP::Target as SignerProvider>::EcdsaSigner>,
@@ -9705,106 +9648,6 @@ where
97059648
MR::Target: MessageRouter,
97069649
L::Target: Logger,
97079650
{
9708-
/// Creates a [`Bolt12Invoice`] for a [`Refund`] and enqueues it to be sent via an onion
9709-
/// message.
9710-
///
9711-
/// The resulting invoice uses a [`PaymentHash`] recognized by the [`ChannelManager`] and a
9712-
/// [`BlindedPaymentPath`] containing the [`PaymentSecret`] needed to reconstruct the
9713-
/// corresponding [`PaymentPreimage`]. It is returned purely for informational purposes.
9714-
///
9715-
/// # Limitations
9716-
///
9717-
/// Requires a direct connection to an introduction node in [`Refund::paths`] or to
9718-
/// [`Refund::payer_signing_pubkey`], if empty. This request is best effort; an invoice will be
9719-
/// sent to each node meeting the aforementioned criteria, but there's no guarantee that they
9720-
/// will be received and no retries will be made.
9721-
///
9722-
/// # Errors
9723-
///
9724-
/// Errors if:
9725-
/// - the refund is for an unsupported chain, or
9726-
/// - the parameterized [`Router`] is unable to create a blinded payment path or reply path for
9727-
/// the invoice.
9728-
///
9729-
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
9730-
pub fn request_refund_payment(
9731-
&self, refund: &Refund
9732-
) -> Result<Bolt12Invoice, Bolt12SemanticError> {
9733-
let expanded_key = &self.inbound_payment_key;
9734-
let entropy = &*self.entropy_source;
9735-
let secp_ctx = &self.secp_ctx;
9736-
9737-
let amount_msats = refund.amount_msats();
9738-
let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
9739-
9740-
if refund.chain() != self.chain_hash {
9741-
return Err(Bolt12SemanticError::UnsupportedChain);
9742-
}
9743-
9744-
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
9745-
9746-
match self.create_inbound_payment(Some(amount_msats), relative_expiry, None) {
9747-
Ok((payment_hash, payment_secret)) => {
9748-
let payment_context = PaymentContext::Bolt12Refund(Bolt12RefundContext {});
9749-
let payment_paths = self.create_blinded_payment_paths(
9750-
Some(amount_msats), payment_secret, payment_context, relative_expiry,
9751-
)
9752-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9753-
9754-
#[cfg(feature = "std")]
9755-
let builder = refund.respond_using_derived_keys(
9756-
payment_paths, payment_hash, expanded_key, entropy
9757-
)?;
9758-
#[cfg(not(feature = "std"))]
9759-
let created_at = Duration::from_secs(
9760-
self.highest_seen_timestamp.load(Ordering::Acquire) as u64
9761-
);
9762-
#[cfg(not(feature = "std"))]
9763-
let builder = refund.respond_using_derived_keys_no_std(
9764-
payment_paths, payment_hash, created_at, expanded_key, entropy
9765-
)?;
9766-
let builder: InvoiceBuilder<DerivedSigningPubkey> = builder.into();
9767-
let invoice = builder.allow_mpp().build_and_sign(secp_ctx)?;
9768-
9769-
let nonce = Nonce::from_entropy_source(entropy);
9770-
let hmac = payment_hash.hmac_for_offer_payment(nonce, expanded_key);
9771-
let context = MessageContext::Offers(OffersContext::InboundPayment {
9772-
payment_hash: invoice.payment_hash(), nonce, hmac
9773-
});
9774-
let reply_paths = self.create_blinded_paths(context)
9775-
.map_err(|_| Bolt12SemanticError::MissingPaths)?;
9776-
9777-
let mut pending_offers_messages = self.pending_offers_messages.lock().unwrap();
9778-
if refund.paths().is_empty() {
9779-
for reply_path in reply_paths {
9780-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9781-
destination: Destination::Node(refund.payer_signing_pubkey()),
9782-
reply_path,
9783-
};
9784-
let message = OffersMessage::Invoice(invoice.clone());
9785-
pending_offers_messages.push((message, instructions));
9786-
}
9787-
} else {
9788-
reply_paths
9789-
.iter()
9790-
.flat_map(|reply_path| refund.paths().iter().map(move |path| (path, reply_path)))
9791-
.take(OFFERS_MESSAGE_REQUEST_LIMIT)
9792-
.for_each(|(path, reply_path)| {
9793-
let instructions = MessageSendInstructions::WithSpecifiedReplyPath {
9794-
destination: Destination::BlindedPath(path.clone()),
9795-
reply_path: reply_path.clone(),
9796-
};
9797-
let message = OffersMessage::Invoice(invoice.clone());
9798-
pending_offers_messages.push((message, instructions));
9799-
});
9800-
}
9801-
9802-
Ok(invoice)
9803-
},
9804-
Err(()) => Err(Bolt12SemanticError::InvalidAmount),
9805-
}
9806-
}
9807-
98089651
/// Gets a payment secret and payment hash for use in an invoice given to a third party wishing
98099652
/// to pay us.
98109653
///
@@ -9903,27 +9746,6 @@ where
99039746
inbound_payment::get_payment_preimage(payment_hash, payment_secret, &self.inbound_payment_key)
99049747
}
99059748

9906-
/// Creates a collection of blinded paths by delegating to
9907-
/// [`MessageRouter::create_blinded_paths`].
9908-
///
9909-
/// Errors if the `MessageRouter` errors.
9910-
fn create_blinded_paths(&self, context: MessageContext) -> Result<Vec<BlindedMessagePath>, ()> {
9911-
let recipient = self.get_our_node_id();
9912-
let secp_ctx = &self.secp_ctx;
9913-
9914-
let peers = self.per_peer_state.read().unwrap()
9915-
.iter()
9916-
.map(|(node_id, peer_state)| (node_id, peer_state.lock().unwrap()))
9917-
.filter(|(_, peer)| peer.is_connected)
9918-
.filter(|(_, peer)| peer.latest_features.supports_onion_messages())
9919-
.map(|(node_id, _)| *node_id)
9920-
.collect::<Vec<_>>();
9921-
9922-
self.message_router
9923-
.create_blinded_paths(recipient, context, peers, secp_ctx)
9924-
.and_then(|paths| (!paths.is_empty()).then(|| paths).ok_or(()))
9925-
}
9926-
99279749
#[cfg(async_payments)]
99289750
pub(super) fn duration_since_epoch(&self) -> Duration {
99299751
#[cfg(not(feature = "std"))]
@@ -12229,7 +12051,9 @@ where
1222912051
/// The [`MessageRouter`] used for constructing [`BlindedMessagePath`]s for [`Offer`]s,
1223012052
/// [`Refund`]s, and any reply paths.
1223112053
///
12054+
/// [`BlindedMessagePath`]: crate::blinded_path::message::BlindedMessagePath
1223212055
/// [`Offer`]: crate::offers::offer::Offer
12056+
/// [`Refund`]: crate::offers::refund::Refund
1223312057
pub message_router: MR,
1223412058
/// The Logger for use in the ChannelManager and which may be used to log information during
1223512059
/// deserialization.
@@ -13332,8 +13156,6 @@ where
1333213156

1333313157
funding_batch_states: Mutex::new(BTreeMap::new()),
1333413158

13335-
pending_offers_messages: Mutex::new(Vec::new()),
13336-
1333713159
pending_broadcast_messages: Mutex::new(Vec::new()),
1333813160

1333913161
entropy_source: args.entropy_source,

0 commit comments

Comments
 (0)