Skip to content

Commit 3545843

Browse files
Check and refresh served static invoices
As an async recipient, we need to interactively build offers and corresponding static invoices, the latter of which an always-online node will serve to payers on our behalf. Offers may be very long-lived and have a longer expiration than their corresponding static invoice. Therefore, persist a fresh invoice with the static invoice server when the current invoice gets close to expiration.
1 parent b8dbf64 commit 3545843

File tree

4 files changed

+152
-7
lines changed

4 files changed

+152
-7
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5107,7 +5107,10 @@ where
51075107
#[cfg(async_payments)]
51085108
fn check_refresh_async_receive_offers(&self) {
51095109
let peers = self.get_peers_for_blinded_path();
5110-
match self.flow.check_refresh_async_receive_offers(peers, &*self.entropy_source) {
5110+
let channels = self.list_usable_channels();
5111+
let entropy = &*self.entropy_source;
5112+
let router = &*self.router;
5113+
match self.flow.check_refresh_async_receive_offers(peers, channels, entropy, router) {
51115114
Err(()) => {
51125115
log_error!(
51135116
self.logger,

lightning/src/offers/async_receive_offer_cache.rs

Lines changed: 58 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use crate::util::ser::{Readable, Writeable, Writer};
2222
use core::time::Duration;
2323
#[cfg(async_payments)]
2424
use {
25-
crate::blinded_path::message::AsyncPaymentsContext,
25+
crate::blinded_path::message::AsyncPaymentsContext, crate::offers::offer::OfferId,
2626
crate::onion_message::async_payments::OfferPaths,
2727
};
2828

@@ -210,6 +210,63 @@ impl AsyncReceiveOfferCache {
210210
self.last_offer_paths_request_timestamp = Duration::from_secs(0);
211211
}
212212

213+
/// Returns an iterator over the list of cached offers where the invoice is expiring soon and we
214+
/// need to send an updated one to the static invoice server.
215+
pub(super) fn offers_needing_invoice_refresh(
216+
&self, duration_since_epoch: Duration,
217+
) -> impl Iterator<Item = (&Offer, Nonce, Duration, &Responder)> {
218+
self.offers.iter().filter_map(move |offer| {
219+
const ONE_DAY: Duration = Duration::from_secs(24 * 60 * 60);
220+
221+
if offer.offer.is_expired_no_std(duration_since_epoch) {
222+
return None;
223+
}
224+
if offer.invoice_update_attempts >= MAX_UPDATE_ATTEMPTS {
225+
return None;
226+
}
227+
228+
let time_until_invoice_expiry =
229+
offer.static_invoice_absolute_expiry.saturating_sub(duration_since_epoch);
230+
let time_until_offer_expiry = offer
231+
.offer
232+
.absolute_expiry()
233+
.unwrap_or_else(|| Duration::from_secs(u64::MAX))
234+
.saturating_sub(duration_since_epoch);
235+
236+
// Update the invoice if it expires in less than a day, as long as the offer has a longer
237+
// expiry than that.
238+
let needs_update = time_until_invoice_expiry < ONE_DAY
239+
&& time_until_offer_expiry > time_until_invoice_expiry;
240+
if needs_update {
241+
Some((
242+
&offer.offer,
243+
offer.offer_nonce,
244+
offer.offer_created_at,
245+
&offer.update_static_invoice_path,
246+
))
247+
} else {
248+
None
249+
}
250+
})
251+
}
252+
253+
/// Indicates that we've sent onion messages attempting to update the static invoice corresponding
254+
/// to the provided offer_id. Calling this method allows the cache to self-limit how many invoice
255+
/// update requests are sent.
256+
///
257+
/// Errors if the offer corresponding to the provided offer_id could not be found.
258+
pub(super) fn increment_invoice_update_attempts(
259+
&mut self, offer_id: OfferId,
260+
) -> Result<(), ()> {
261+
match self.offers.iter_mut().find(|offer| offer.offer.id() == offer_id) {
262+
Some(offer) => {
263+
offer.invoice_update_attempts += 1;
264+
Ok(())
265+
},
266+
None => return Err(()),
267+
}
268+
}
269+
213270
/// Should be called when we receive a [`StaticInvoicePersisted`] message from the static invoice
214271
/// server, which indicates that a new offer was persisted by the server and they are ready to
215272
/// serve the corresponding static invoice to payers on our behalf.

lightning/src/offers/flow.rs

Lines changed: 84 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1116,8 +1116,9 @@ where
11161116
core::mem::take(&mut self.pending_dns_onion_messages.lock().unwrap())
11171117
}
11181118

1119-
/// Sends out [`OfferPathsRequest`] onion messages if we are an often-offline recipient and are
1120-
/// configured to interactively build offers and static invoices with a static invoice server.
1119+
/// Sends out [`OfferPathsRequest`] and [`ServeStaticInvoice`] onion messages if we are an
1120+
/// often-offline recipient and are configured to interactively build offers and static invoices
1121+
/// with a static invoice server.
11211122
///
11221123
/// # Usage
11231124
///
@@ -1126,11 +1127,13 @@ where
11261127
///
11271128
/// Errors if we failed to create blinded reply paths when sending an [`OfferPathsRequest`] message.
11281129
#[cfg(async_payments)]
1129-
pub(crate) fn check_refresh_async_receive_offers<ES: Deref>(
1130-
&self, peers: Vec<MessageForwardNode>, entropy: ES,
1130+
pub(crate) fn check_refresh_async_receive_offers<ES: Deref, R: Deref>(
1131+
&self, peers: Vec<MessageForwardNode>, usable_channels: Vec<ChannelDetails>, entropy: ES,
1132+
router: R,
11311133
) -> Result<(), ()>
11321134
where
11331135
ES::Target: EntropySource,
1136+
R::Target: Router,
11341137
{
11351138
// Terminate early if this node does not intend to receive async payments.
11361139
if self.paths_to_static_invoice_server.is_empty() {
@@ -1157,7 +1160,7 @@ where
11571160
path_absolute_expiry: duration_since_epoch
11581161
.saturating_add(TEMP_REPLY_PATH_RELATIVE_EXPIRY),
11591162
});
1160-
let reply_paths = match self.create_blinded_paths(peers, context) {
1163+
let reply_paths = match self.create_blinded_paths(peers.clone(), context) {
11611164
Ok(paths) => paths,
11621165
Err(()) => {
11631166
return Err(());
@@ -1179,9 +1182,85 @@ where
11791182
);
11801183
}
11811184

1185+
self.check_refresh_static_invoices(peers, usable_channels, entropy, router);
1186+
11821187
Ok(())
11831188
}
11841189

1190+
/// If a static invoice server has persisted an offer for us but the corresponding invoice is
1191+
/// expiring soon, we need to refresh that invoice. Here we enqueue the onion messages that will
1192+
/// be used to request invoice refresh, based on the offers provided by the cache.
1193+
#[cfg(async_payments)]
1194+
fn check_refresh_static_invoices<ES: Deref, R: Deref>(
1195+
&self, peers: Vec<MessageForwardNode>, usable_channels: Vec<ChannelDetails>, entropy: ES,
1196+
router: R,
1197+
) where
1198+
ES::Target: EntropySource,
1199+
R::Target: Router,
1200+
{
1201+
let duration_since_epoch = self.duration_since_epoch();
1202+
1203+
let mut serve_static_invoice_messages = Vec::new();
1204+
{
1205+
let cache = self.async_receive_offer_cache.lock().unwrap();
1206+
for offer_and_metadata in cache.offers_needing_invoice_refresh(duration_since_epoch) {
1207+
let (offer, offer_nonce, offer_created_at, update_static_invoice_path) =
1208+
offer_and_metadata;
1209+
let offer_id = offer.id();
1210+
1211+
let (serve_invoice_msg, reply_path_ctx) = match self
1212+
.create_serve_static_invoice_message(
1213+
offer.clone(),
1214+
offer_nonce,
1215+
offer_created_at,
1216+
peers.clone(),
1217+
usable_channels.clone(),
1218+
update_static_invoice_path.clone(),
1219+
&*entropy,
1220+
&*router,
1221+
) {
1222+
Ok((msg, ctx)) => (msg, ctx),
1223+
Err(()) => continue,
1224+
};
1225+
serve_static_invoice_messages.push((
1226+
serve_invoice_msg,
1227+
update_static_invoice_path.clone(),
1228+
reply_path_ctx,
1229+
offer_id,
1230+
));
1231+
}
1232+
}
1233+
1234+
// Enqueue the new serve_static_invoice messages in a separate loop to avoid holding the offer
1235+
// cache lock and the pending_async_payments_messages lock at the same time.
1236+
for (serve_invoice_msg, serve_invoice_path, reply_path_ctx, offer_id) in
1237+
serve_static_invoice_messages
1238+
{
1239+
let context = MessageContext::AsyncPayments(reply_path_ctx);
1240+
let reply_paths = match self.create_blinded_paths(peers.clone(), context) {
1241+
Ok(paths) => paths,
1242+
Err(()) => continue,
1243+
};
1244+
1245+
{
1246+
// We can't fail past this point, so indicate to the cache that we've requested an invoice
1247+
// update.
1248+
let mut cache = self.async_receive_offer_cache.lock().unwrap();
1249+
if cache.increment_invoice_update_attempts(offer_id).is_err() {
1250+
continue;
1251+
}
1252+
}
1253+
1254+
let message = AsyncPaymentsMessage::ServeStaticInvoice(serve_invoice_msg);
1255+
enqueue_onion_message_with_reply_paths(
1256+
message,
1257+
&[serve_invoice_path.into_reply_path()],
1258+
reply_paths,
1259+
&mut self.pending_async_payments_messages.lock().unwrap(),
1260+
);
1261+
}
1262+
}
1263+
11851264
/// Handles an incoming [`OfferPaths`] message from the static invoice server, sending out
11861265
/// [`ServeStaticInvoice`] onion messages in response if we want to use the paths we've received
11871266
/// to build and cache an async receive offer.

lightning/src/onion_message/messenger.rs

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -432,6 +432,12 @@ impl Responder {
432432
context: Some(context),
433433
}
434434
}
435+
436+
/// Converts a [`Responder`] into its inner [`BlindedMessagePath`].
437+
#[cfg(async_payments)]
438+
pub(crate) fn into_reply_path(self) -> BlindedMessagePath {
439+
self.reply_path
440+
}
435441
}
436442

437443
/// Instructions for how and where to send the response to an onion message.

0 commit comments

Comments
 (0)