Skip to content

Commit 9a1cb1a

Browse files
committed
OffersMessageHandler impl for ChannelManager
Define the BOLT 12 message flow in ChannelManager's OffersMessageHandler implementation. - An invoice_request message results in responding with an invoice message if it can be verified that the request is for a valid offer. - An invoice is paid if it can be verified to have originated from a sent invoice_request or a refund. - An invoice_error is sent in some failure cases.
1 parent a91a35b commit 9a1cb1a

File tree

3 files changed

+147
-4
lines changed

3 files changed

+147
-4
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 132 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,13 @@ use crate::ln::onion_utils::HTLCFailReason;
5353
use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError};
5454
#[cfg(test)]
5555
use crate::ln::outbound_payment;
56-
use crate::ln::outbound_payment::{OutboundPayments, PaymentAttempts, PendingOutboundPayment, SendAlongPathArgs};
56+
use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, PaymentAttempts, PendingOutboundPayment, SendAlongPathArgs};
5757
use crate::ln::wire::Encode;
58+
use crate::offers::invoice::{Bolt12Invoice, DEFAULT_RELATIVE_EXPIRY, DerivedSigningPubkey, InvoiceBuilder};
59+
use crate::offers::invoice_error::InvoiceError;
60+
use crate::offers::merkle::SignError;
61+
use crate::offers::parse::Bolt12SemanticError;
62+
use crate::onion_message::{OffersMessage, OffersMessageHandler};
5863
use crate::sign::{EntropySource, KeysManager, NodeSigner, Recipient, SignerProvider, WriteableEcdsaChannelSigner};
5964
use crate::util::config::{UserConfig, ChannelConfig, ChannelConfigUpdate};
6065
use crate::util::wakers::{Future, Notifier};
@@ -3390,6 +3395,17 @@ where
33903395
self.pending_outbound_payments.test_set_payment_metadata(payment_id, new_payment_metadata);
33913396
}
33923397

3398+
pub(super) fn send_payment_for_bolt12_invoice(&self, invoice: &Bolt12Invoice, payment_id: PaymentId) -> Result<(), Bolt12PaymentError> {
3399+
let best_block_height = self.best_block.read().unwrap().height();
3400+
let _persistence_guard = PersistenceNotifierGuard::notify_on_drop(self);
3401+
self.pending_outbound_payments
3402+
.send_payment_for_bolt12_invoice(
3403+
invoice, payment_id, &self.router, self.list_usable_channels(),
3404+
|| self.compute_inflight_htlcs(), &self.entropy_source, &self.node_signer,
3405+
best_block_height, &self.logger, &self.pending_events,
3406+
|args| self.send_payment_along_path(args)
3407+
)
3408+
}
33933409

33943410
/// Signals that no further attempts for the given payment should occur. Useful if you have a
33953411
/// pending outbound payment with retries remaining, but wish to stop retrying the payment before
@@ -7863,6 +7879,121 @@ where
78637879
}
78647880
}
78657881

7882+
impl<M: Deref, T: Deref, ES: Deref, NS: Deref, SP: Deref, F: Deref, R: Deref, L: Deref>
7883+
OffersMessageHandler for ChannelManager<M, T, ES, NS, SP, F, R, L>
7884+
where
7885+
M::Target: chain::Watch<<SP::Target as SignerProvider>::Signer>,
7886+
T::Target: BroadcasterInterface,
7887+
ES::Target: EntropySource,
7888+
NS::Target: NodeSigner,
7889+
SP::Target: SignerProvider,
7890+
F::Target: FeeEstimator,
7891+
R::Target: Router,
7892+
L::Target: Logger,
7893+
{
7894+
fn handle_message(&self, message: OffersMessage) -> Option<OffersMessage> {
7895+
let secp_ctx = &self.secp_ctx;
7896+
let expanded_key = &self.inbound_payment_key;
7897+
7898+
match message {
7899+
OffersMessage::InvoiceRequest(invoice_request) => {
7900+
let amount_msats = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(
7901+
&invoice_request
7902+
) {
7903+
Ok(amount_msats) => Some(amount_msats),
7904+
Err(error) => return Some(OffersMessage::InvoiceError(error.into())),
7905+
};
7906+
let invoice_request = match invoice_request.verify(expanded_key, secp_ctx) {
7907+
Ok(invoice_request) => invoice_request,
7908+
Err(()) => {
7909+
let error = Bolt12SemanticError::InvalidMetadata;
7910+
return Some(OffersMessage::InvoiceError(error.into()));
7911+
},
7912+
};
7913+
let relative_expiry = DEFAULT_RELATIVE_EXPIRY.as_secs() as u32;
7914+
7915+
match self.create_inbound_payment(amount_msats, relative_expiry, None) {
7916+
Ok((payment_hash, _payment_secret)) if invoice_request.keys.is_some() => {
7917+
// TODO: Include payment_secret in payment_paths.
7918+
let payment_paths = vec![];
7919+
#[cfg(not(feature = "no-std"))]
7920+
let builder = invoice_request.respond_using_derived_keys(
7921+
payment_paths, payment_hash
7922+
);
7923+
#[cfg(feature = "no-std")]
7924+
let created_at = Duration::from_secs(
7925+
self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7926+
);
7927+
#[cfg(feature = "no-std")]
7928+
let builder = invoice_request.respond_using_derived_keys_no_std(
7929+
payment_paths, payment_hash, created_at
7930+
);
7931+
match builder.and_then(|b| b.allow_mpp().build_and_sign(secp_ctx)) {
7932+
Ok(invoice) => Some(OffersMessage::Invoice(invoice)),
7933+
Err(error) => Some(OffersMessage::InvoiceError(error.into())),
7934+
}
7935+
},
7936+
Ok((payment_hash, _payment_secret)) => {
7937+
// TODO: Include payment_secret in payment_paths.
7938+
let payment_paths = vec![];
7939+
#[cfg(not(feature = "no-std"))]
7940+
let builder = invoice_request.respond_with(payment_paths, payment_hash);
7941+
#[cfg(feature = "no-std")]
7942+
let created_at = Duration::from_secs(
7943+
self.highest_seen_timestamp.load(Ordering::Acquire) as u64
7944+
);
7945+
#[cfg(feature = "no-std")]
7946+
let builder = invoice_request.respond_with_no_std(
7947+
payment_paths, payment_hash, created_at
7948+
);
7949+
let response = builder.and_then(|builder| builder.allow_mpp().build())
7950+
.map_err(|e| OffersMessage::InvoiceError(e.into()))
7951+
.and_then(|invoice|
7952+
match invoice.sign(|invoice| self.node_signer.sign_bolt12_invoice(invoice)) {
7953+
Ok(invoice) => Ok(OffersMessage::Invoice(invoice)),
7954+
Err(SignError::Signing(())) => Err(OffersMessage::InvoiceError(
7955+
InvoiceError::from_str("Failed signing invoice")
7956+
)),
7957+
Err(SignError::Verification(_)) => Err(OffersMessage::InvoiceError(
7958+
InvoiceError::from_str("Failed invoice signature verification")
7959+
)),
7960+
});
7961+
match response {
7962+
Ok(invoice) => Some(invoice),
7963+
Err(error) => Some(error),
7964+
}
7965+
},
7966+
Err(()) => {
7967+
Some(OffersMessage::InvoiceError(Bolt12SemanticError::InvalidAmount.into()))
7968+
},
7969+
}
7970+
},
7971+
OffersMessage::Invoice(invoice) => {
7972+
match invoice.verify(expanded_key, secp_ctx) {
7973+
Err(()) => {
7974+
Some(OffersMessage::InvoiceError(InvoiceError::from_str("Unrecognized invoice")))
7975+
},
7976+
Ok(_) if invoice.invoice_features().requires_unknown_bits_from(&self.bolt12_invoice_features()) => {
7977+
Some(OffersMessage::InvoiceError(Bolt12SemanticError::UnknownRequiredFeatures.into()))
7978+
},
7979+
Ok(payment_id) => {
7980+
if let Err(e) = self.send_payment_for_bolt12_invoice(&invoice, payment_id) {
7981+
log_trace!(self.logger, "Failed paying invoice: {:?}", e);
7982+
Some(OffersMessage::InvoiceError(InvoiceError::from_str(&format!("{:?}", e))))
7983+
} else {
7984+
None
7985+
}
7986+
},
7987+
}
7988+
},
7989+
OffersMessage::InvoiceError(invoice_error) => {
7990+
log_trace!(self.logger, "Received invoice_error: {}", invoice_error);
7991+
None
7992+
},
7993+
}
7994+
}
7995+
}
7996+
78667997
/// Fetches the set of [`NodeFeatures`] flags that are provided by or required by
78677998
/// [`ChannelManager`].
78687999
pub(crate) fn provided_node_features(config: &UserConfig) -> NodeFeatures {

lightning/src/offers/invoice.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -174,7 +174,7 @@ impl<'a> InvoiceBuilder<'a, ExplicitSigningPubkey> {
174174
invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
175175
created_at: Duration, payment_hash: PaymentHash
176176
) -> Result<Self, Bolt12SemanticError> {
177-
let amount_msats = Self::check_amount_msats(invoice_request)?;
177+
let amount_msats = Self::amount_msats(invoice_request)?;
178178
let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
179179
let contents = InvoiceContents::ForOffer {
180180
invoice_request: invoice_request.contents.clone(),
@@ -207,7 +207,7 @@ impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
207207
invoice_request: &'a InvoiceRequest, payment_paths: Vec<(BlindedPayInfo, BlindedPath)>,
208208
created_at: Duration, payment_hash: PaymentHash, keys: KeyPair
209209
) -> Result<Self, Bolt12SemanticError> {
210-
let amount_msats = Self::check_amount_msats(invoice_request)?;
210+
let amount_msats = Self::amount_msats(invoice_request)?;
211211
let signing_pubkey = invoice_request.contents.inner.offer.signing_pubkey();
212212
let contents = InvoiceContents::ForOffer {
213213
invoice_request: invoice_request.contents.clone(),
@@ -237,7 +237,9 @@ impl<'a> InvoiceBuilder<'a, DerivedSigningPubkey> {
237237
}
238238

239239
impl<'a, S: SigningPubkeyStrategy> InvoiceBuilder<'a, S> {
240-
fn check_amount_msats(invoice_request: &InvoiceRequest) -> Result<u64, Bolt12SemanticError> {
240+
pub(crate) fn amount_msats(
241+
invoice_request: &InvoiceRequest
242+
) -> Result<u64, Bolt12SemanticError> {
241243
match invoice_request.amount_msats() {
242244
Some(amount_msats) => Ok(amount_msats),
243245
None => match invoice_request.contents.inner.offer.amount() {

lightning/src/offers/invoice_error.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,16 @@ pub struct ErroneousField {
4848
pub suggested_value: Option<Vec<u8>>,
4949
}
5050

51+
impl InvoiceError {
52+
/// Creates an [`InvoiceError`] with the given message.
53+
pub fn from_str(s: &str) -> Self {
54+
Self {
55+
erroneous_field: None,
56+
message: UntrustedString(s.to_string()),
57+
}
58+
}
59+
}
60+
5161
impl core::fmt::Display for InvoiceError {
5262
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
5363
self.message.fmt(f)

0 commit comments

Comments
 (0)