Skip to content

Commit c2e8b11

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 e718bce commit c2e8b11

File tree

3 files changed

+127
-9
lines changed

3 files changed

+127
-9
lines changed

lightning/src/ln/channelmanager.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4953,9 +4953,11 @@ where
49534953

49544954
#[cfg(async_payments)]
49554955
fn check_refresh_async_receive_offers(&self) {
4956-
match self.flow.check_refresh_async_receive_offers(
4957-
self.get_peers_for_blinded_path(), &*self.entropy_source
4958-
) {
4956+
let peers = self.get_peers_for_blinded_path();
4957+
let channels = self.list_usable_channels();
4958+
let entropy = &*self.entropy_source;
4959+
let router = &*self.router;
4960+
match self.flow.check_refresh_async_receive_offers(peers, channels, entropy, router) {
49594961
Err(()) => {
49604962
log_error!(self.logger, "Failed to create blinded paths when requesting async receive offer paths");
49614963
},

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

@@ -190,6 +190,63 @@ impl AsyncReceiveOfferCache {
190190
self.last_offer_paths_request_timestamp = Duration::from_secs(0);
191191
}
192192

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

lightning/src/offers/flow.rs

Lines changed: 64 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1141,16 +1141,19 @@ where
11411141
core::mem::take(&mut self.pending_dns_onion_messages.lock().unwrap())
11421142
}
11431143

1144-
/// Sends out [`OfferPathsRequest`] onion messages if we are an often-offline recipient and are
1145-
/// configured to interactively build offers and static invoices with a static invoice server.
1144+
/// Sends out [`OfferPathsRequest`] and [`ServeStaticInvoice`] onion messages if we are an
1145+
/// often-offline recipient and are configured to interactively build offers and static invoices
1146+
/// with a static invoice server.
11461147
///
11471148
/// Errors if we failed to create blinded reply paths when sending an [`OfferPathsRequest`] message.
11481149
#[cfg(async_payments)]
1149-
pub(crate) fn check_refresh_async_receive_offers<ES: Deref>(
1150-
&self, peers: Vec<MessageForwardNode>, entropy: ES,
1150+
pub(crate) fn check_refresh_async_receive_offers<ES: Deref, R: Deref>(
1151+
&self, peers: Vec<MessageForwardNode>, usable_channels: Vec<ChannelDetails>, entropy: ES,
1152+
router: R,
11511153
) -> Result<(), ()>
11521154
where
11531155
ES::Target: EntropySource,
1156+
R::Target: Router,
11541157
{
11551158
// Terminate early if this node does not intend to receive async payments.
11561159
if self.paths_to_static_invoice_server.is_empty() {
@@ -1176,7 +1179,7 @@ where
11761179
path_absolute_expiry: duration_since_epoch
11771180
.saturating_add(TEMP_REPLY_PATH_RELATIVE_EXPIRY),
11781181
});
1179-
let reply_paths = match self.create_blinded_paths(peers, context) {
1182+
let reply_paths = match self.create_blinded_paths(peers.clone(), context) {
11801183
Ok(paths) => paths,
11811184
Err(()) => {
11821185
return Err(());
@@ -1196,6 +1199,62 @@ where
11961199
);
11971200
}
11981201

1202+
// If a static invoice server has persisted an offer for us but the corresponding invoice is
1203+
// expiring soon, we need to refresh that invoice. Here we create the onion messages that will
1204+
// be used to request invoice refresh, based on the offers provided by the cache.
1205+
let mut serve_static_invoice_messages = Vec::new();
1206+
{
1207+
let cache = self.async_receive_offer_cache.lock().unwrap();
1208+
for offer_and_metadata in cache.offers_needing_invoice_refresh(duration_since_epoch) {
1209+
let (offer, offer_nonce, offer_created_at, update_static_invoice_path) =
1210+
offer_and_metadata;
1211+
let offer_id = offer.id();
1212+
1213+
let (serve_invoice_msg, reply_path_ctx) = match self
1214+
.create_serve_static_invoice_message(
1215+
offer.clone(),
1216+
offer_nonce,
1217+
offer_created_at,
1218+
peers.clone(),
1219+
usable_channels.clone(),
1220+
update_static_invoice_path.clone(),
1221+
&*entropy,
1222+
&*router,
1223+
) {
1224+
Ok((msg, ctx)) => (msg, ctx),
1225+
Err(()) => continue,
1226+
};
1227+
serve_static_invoice_messages.push((serve_invoice_msg, reply_path_ctx, offer_id));
1228+
}
1229+
}
1230+
1231+
// Enqueue the new serve_static_invoice messages in a separate loop to avoid holding the offer
1232+
// cache lock and the pending_async_payments_messages lock at the same time.
1233+
for (serve_invoice_msg, reply_path_ctx, offer_id) in serve_static_invoice_messages {
1234+
let context = MessageContext::AsyncPayments(reply_path_ctx);
1235+
let reply_paths = match self.create_blinded_paths(peers.clone(), context) {
1236+
Ok(paths) => paths,
1237+
Err(()) => continue,
1238+
};
1239+
1240+
{
1241+
// We can't fail past this point, so indicate to the cache that we've requested an invoice
1242+
// update.
1243+
let mut cache = self.async_receive_offer_cache.lock().unwrap();
1244+
if cache.increment_invoice_update_attempts(offer_id).is_err() {
1245+
continue;
1246+
}
1247+
}
1248+
1249+
let message = AsyncPaymentsMessage::ServeStaticInvoice(serve_invoice_msg);
1250+
enqueue_onion_message_with_reply_paths(
1251+
message,
1252+
&self.paths_to_static_invoice_server,
1253+
reply_paths,
1254+
&mut self.pending_async_payments_messages.lock().unwrap(),
1255+
);
1256+
}
1257+
11991258
Ok(())
12001259
}
12011260

0 commit comments

Comments
 (0)