Skip to content

Commit 5e0486c

Browse files
committed
Compute InflightHtlcs from available information in ChannelManager
1 parent c789368 commit 5e0486c

File tree

4 files changed

+76
-143
lines changed

4 files changed

+76
-143
lines changed

lightning-invoice/src/payment.rs

Lines changed: 43 additions & 142 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@
6969
//! # &self, route: &Route, payment_id: PaymentId
7070
//! # ) -> Result<(), PaymentSendFailure> { unimplemented!() }
7171
//! # fn abandon_payment(&self, payment_id: PaymentId) { unimplemented!() }
72+
//! # fn inflight_htlcs(&self) -> InFlightHtlcs { unimplemented!() }
7273
//! # }
7374
//! #
7475
//! # struct FakeRouter {}
@@ -289,6 +290,10 @@ pub trait Payer {
289290

290291
/// Signals that no further retries for the given payment will occur.
291292
fn abandon_payment(&self, payment_id: PaymentId);
293+
294+
/// Construct an [`InFlightHtlcs`] containing information about currently used up liquidity
295+
/// across payments.
296+
fn inflight_htlcs(&self) -> InFlightHtlcs;
292297
}
293298

294299
/// A trait defining behavior for a [`Router`] implementation that also supports scoring channels
@@ -546,7 +551,7 @@ where
546551

547552
let payer = self.payer.node_id();
548553
let first_hops = self.payer.first_hops();
549-
let inflight_htlcs = self.create_inflight_map();
554+
let inflight_htlcs = self.payer.inflight_htlcs();
550555
let route = self.router.find_route(
551556
&payer, &params, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
552557
).map_err(|e| PaymentError::Routing(e))?;
@@ -649,7 +654,7 @@ where
649654

650655
let payer = self.payer.node_id();
651656
let first_hops = self.payer.first_hops();
652-
let inflight_htlcs = self.create_inflight_map();
657+
let inflight_htlcs = self.payer.inflight_htlcs();
653658

654659
let route = self.router.find_route(
655660
&payer, &params, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
@@ -704,23 +709,6 @@ where
704709
pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
705710
self.payment_cache.lock().unwrap().remove(payment_hash);
706711
}
707-
708-
/// Use path information in the payment_cache to construct a HashMap mapping a channel's short
709-
/// channel id and direction to the amount being sent through it.
710-
///
711-
/// This function should be called whenever we need information about currently used up liquidity
712-
/// across payments.
713-
fn create_inflight_map(&self) -> InFlightHtlcs {
714-
let mut total_inflight_map = InFlightHtlcs::new();
715-
// Make an attempt at finding existing payment information from `payment_cache`.
716-
for payment_info in self.payment_cache.lock().unwrap().values() {
717-
for path in &payment_info.paths {
718-
total_inflight_map.process_path(path, self.payer.node_id());
719-
}
720-
}
721-
722-
total_inflight_map
723-
}
724712
}
725713

726714
fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
@@ -865,7 +853,6 @@ mod tests {
865853
use std::time::{SystemTime, Duration};
866854
use crate::time_utils::tests::SinceEpoch;
867855
use crate::DEFAULT_EXPIRY_TIME;
868-
use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
869856

870857
fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
871858
let payment_hash = Sha256::hash(&payment_preimage.0);
@@ -1585,66 +1572,17 @@ mod tests {
15851572
}
15861573

15871574
#[test]
1588-
fn generates_correct_inflight_map_data() {
1589-
let event_handled = core::cell::RefCell::new(false);
1590-
let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1591-
1592-
let payment_preimage = PaymentPreimage([1; 32]);
1593-
let invoice = invoice(payment_preimage);
1594-
let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
1595-
let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1596-
1597-
let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1598-
let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1599-
let route = TestRouter::route_for_value(final_value_msat);
1600-
let router = TestRouter::new(TestScorer::new());
1601-
let logger = TestLogger::new();
1602-
let invoice_payer =
1603-
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1604-
1605-
let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1606-
1607-
let inflight_map = invoice_payer.create_inflight_map();
1608-
// First path check
1609-
assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
1610-
assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
1611-
assert_eq!(inflight_map.0.get(&(2, false)).unwrap().clone(), 64);
1612-
1613-
// Second path check
1614-
assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1615-
assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1616-
1617-
invoice_payer.handle_event(Event::PaymentPathSuccessful {
1618-
payment_id, payment_hash, path: route.paths[0].clone()
1619-
});
1620-
1621-
let inflight_map = invoice_payer.create_inflight_map();
1622-
1623-
assert_eq!(inflight_map.0.get(&(0, false)), None);
1624-
assert_eq!(inflight_map.0.get(&(1, true)), None);
1625-
assert_eq!(inflight_map.0.get(&(2, false)), None);
1626-
1627-
// Second path should still be inflight
1628-
assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1629-
assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
1630-
}
1631-
1632-
#[test]
1633-
fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() {
1634-
// First, let's just send a payment through, but only make sure one of the path completes
1575+
fn considers_inflight_htlcs_between_invoice_payments() {
16351576
let event_handled = core::cell::RefCell::new(false);
16361577
let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
16371578

16381579
let payment_preimage = PaymentPreimage([1; 32]);
16391580
let payment_invoice = invoice(payment_preimage);
1640-
let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
16411581
let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
16421582

16431583
let payer = TestPayer::new()
16441584
.expect_send(Amount::ForInvoice(final_value_msat))
16451585
.expect_send(Amount::ForInvoice(final_value_msat));
1646-
let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1647-
let route = TestRouter::route_for_value(final_value_msat);
16481586
let scorer = TestScorer::new()
16491587
// 1st invoice, 1st path
16501588
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
@@ -1654,9 +1592,9 @@ mod tests {
16541592
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
16551593
.expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
16561594
// 2nd invoice, 1st path
1657-
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1658-
.expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1659-
.expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1595+
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1596+
.expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 84, effective_capacity: EffectiveCapacity::Unknown } )
1597+
.expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 94, effective_capacity: EffectiveCapacity::Unknown } )
16601598
// 2nd invoice, 2nd path
16611599
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
16621600
.expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
@@ -1665,16 +1603,12 @@ mod tests {
16651603
let invoice_payer =
16661604
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
16671605

1668-
// Succeed 1st path, leave 2nd path inflight
1669-
let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1670-
invoice_payer.handle_event(Event::PaymentPathSuccessful {
1671-
payment_id, payment_hash, path: route.paths[0].clone()
1672-
});
1606+
// Make first invoice payment.
1607+
invoice_payer.pay_invoice(&payment_invoice).unwrap();
16731608

16741609
// Let's pay a second invoice that will be using the same path. This should trigger the
1675-
// assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1676-
// Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1677-
// have 64 msats inflight for paths considering the channel with scid of 1.
1610+
// assertions that expect `ChannelUsage` values of the first invoice payment that is still
1611+
// in-flight.
16781612
let payment_preimage_2 = PaymentPreimage([2; 32]);
16791613
let payment_invoice_2 = invoice(payment_preimage_2);
16801614
invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
@@ -1725,6 +1659,7 @@ mod tests {
17251659

17261660
// Fail 1st path, leave 2nd path inflight
17271661
let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1662+
invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat));
17281663
invoice_payer.handle_event(Event::PaymentPathFailed {
17291664
payment_id,
17301665
payment_hash,
@@ -1737,6 +1672,7 @@ mod tests {
17371672
});
17381673

17391674
// Fails again the 1st path of our retry
1675+
invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat / 2));
17401676
invoice_payer.handle_event(Event::PaymentPathFailed {
17411677
payment_id,
17421678
payment_hash,
@@ -1752,67 +1688,6 @@ mod tests {
17521688
});
17531689
}
17541690

1755-
#[test]
1756-
fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1757-
let event_handled = core::cell::RefCell::new(false);
1758-
let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1759-
1760-
let payment_preimage = PaymentPreimage([1; 32]);
1761-
let invoice_to_pay = invoice(payment_preimage);
1762-
let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1763-
1764-
let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1765-
let payer = TestPayer::new()
1766-
.fails_with_partial_failure(
1767-
retry.clone(), OnAttempt(1),
1768-
Some(vec![
1769-
Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1770-
]))
1771-
.expect_send(Amount::ForInvoice(final_value_msat));
1772-
1773-
let router = TestRouter::new(TestScorer::new());
1774-
let logger = TestLogger::new();
1775-
let invoice_payer =
1776-
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1777-
1778-
invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1779-
let inflight_map = invoice_payer.create_inflight_map();
1780-
1781-
// Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1782-
// inflight map because retries are disabled.
1783-
assert_eq!(inflight_map.0.len(), 2);
1784-
}
1785-
1786-
#[test]
1787-
fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1788-
let event_handled = core::cell::RefCell::new(false);
1789-
let event_handler = |_: Event| { *event_handled.borrow_mut() = true; };
1790-
1791-
let payment_preimage = PaymentPreimage([1; 32]);
1792-
let invoice_to_pay = invoice(payment_preimage);
1793-
let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1794-
1795-
let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1796-
let payer = TestPayer::new()
1797-
.fails_with_partial_failure(
1798-
retry.clone(), OnAttempt(1),
1799-
Some(vec![
1800-
Ok(()), Err(MonitorUpdateInProgress)
1801-
]))
1802-
.expect_send(Amount::ForInvoice(final_value_msat));
1803-
1804-
let router = TestRouter::new(TestScorer::new());
1805-
let logger = TestLogger::new();
1806-
let invoice_payer =
1807-
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1808-
1809-
invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1810-
let inflight_map = invoice_payer.create_inflight_map();
1811-
1812-
// All paths successful, hence we check of the existence of all 5 hops.
1813-
assert_eq!(inflight_map.0.len(), 5);
1814-
}
1815-
18161691
struct TestRouter {
18171692
scorer: RefCell<TestScorer>,
18181693
}
@@ -2100,6 +1975,7 @@ mod tests {
21001975
expectations: core::cell::RefCell<VecDeque<Amount>>,
21011976
attempts: core::cell::RefCell<usize>,
21021977
failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1978+
inflight_htlcs_paths: core::cell::RefCell<Vec<Vec<RouteHop>>>,
21031979
}
21041980

21051981
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -2117,6 +1993,7 @@ mod tests {
21171993
expectations: core::cell::RefCell::new(VecDeque::new()),
21181994
attempts: core::cell::RefCell::new(0),
21191995
failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1996+
inflight_htlcs_paths: core::cell::RefCell::new(Vec::new()),
21201997
}
21211998
}
21221999

@@ -2161,6 +2038,20 @@ mod tests {
21612038
panic!("Unexpected amount: {:?}", actual_value_msats);
21622039
}
21632040
}
2041+
2042+
fn track_inflight_htlcs(&self, route: &Route) {
2043+
for path in &route.paths {
2044+
self.inflight_htlcs_paths.borrow_mut().push(path.clone());
2045+
}
2046+
}
2047+
2048+
fn fail_path(&self, path: &Vec<RouteHop>) {
2049+
let path_idx = self.inflight_htlcs_paths.borrow().iter().position(|p| p == path);
2050+
2051+
if let Some(idx) = path_idx {
2052+
self.inflight_htlcs_paths.borrow_mut().swap_remove(idx);
2053+
}
2054+
}
21642055
}
21652056

21662057
impl Drop for TestPayer {
@@ -2190,6 +2081,7 @@ mod tests {
21902081
_payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
21912082
) -> Result<(), PaymentSendFailure> {
21922083
self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2084+
self.track_inflight_htlcs(route);
21932085
self.check_attempts()
21942086
}
21952087

@@ -2204,10 +2096,19 @@ mod tests {
22042096
&self, route: &Route, _payment_id: PaymentId
22052097
) -> Result<(), PaymentSendFailure> {
22062098
self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2099+
self.track_inflight_htlcs(route);
22072100
self.check_attempts()
22082101
}
22092102

22102103
fn abandon_payment(&self, _payment_id: PaymentId) { }
2104+
2105+
fn inflight_htlcs(&self) -> InFlightHtlcs {
2106+
let mut inflight_htlcs = InFlightHtlcs::new();
2107+
for path in self.inflight_htlcs_paths.clone().into_inner() {
2108+
inflight_htlcs.process_path(&path, self.node_id());
2109+
}
2110+
inflight_htlcs
2111+
}
22112112
}
22122113

22132114
// *** Full Featured Functional Tests with a Real ChannelManager ***

lightning-invoice/src/utils.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -628,6 +628,8 @@ where
628628
fn abandon_payment(&self, payment_id: PaymentId) {
629629
self.abandon_payment(payment_id)
630630
}
631+
632+
fn inflight_htlcs(&self) -> InFlightHtlcs { self.compute_inflight_htlcs() }
631633
}
632634

633635

lightning/src/ln/channel.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5941,6 +5941,17 @@ impl<Signer: Sign> Channel<Signer> {
59415941
self.update_time_counter += 1;
59425942
(monitor_update, dropped_outbound_htlcs)
59435943
}
5944+
5945+
pub fn inflight_htlc_sources(&self) -> impl Iterator<Item=&HTLCSource> {
5946+
self.holding_cell_htlc_updates.iter()
5947+
.flat_map(|htlc_update| {
5948+
match htlc_update {
5949+
HTLCUpdateAwaitingACK::AddHTLC { source, .. } => { Some(source) }
5950+
_ => { None }
5951+
}
5952+
})
5953+
.chain(self.pending_outbound_htlcs.iter().map(|htlc| &htlc.source))
5954+
}
59445955
}
59455956

59465957
const SERIALIZATION_VERSION: u8 = 2;

lightning/src/ln/channelmanager.rs

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ use crate::ln::channel::{Channel, ChannelError, ChannelUpdateStatus, UpdateFulfi
4646
use crate::ln::features::{ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
4747
#[cfg(any(feature = "_test_utils", test))]
4848
use crate::ln::features::InvoiceFeatures;
49-
use crate::routing::router::{PaymentParameters, Route, RouteHop, RoutePath, RouteParameters};
49+
use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RoutePath, RouteParameters};
5050
use crate::ln::msgs;
5151
use crate::ln::onion_utils;
5252
use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT};
@@ -5703,6 +5703,25 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
57035703
}
57045704
}
57055705

5706+
/// Gets inflight HTLC information by processing pending outbound `HTLCSource`s that are in
5707+
/// our channels. It is then used to ensure that we take them into account for pathfinding.
5708+
pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
5709+
let mut inflight_htlcs = InFlightHtlcs::new();
5710+
5711+
for chan in self.channel_state.lock().unwrap().by_id.values() {
5712+
for htlc_source in chan.inflight_htlc_sources() {
5713+
match htlc_source {
5714+
HTLCSource::OutboundRoute { path, .. } => {
5715+
inflight_htlcs.process_path(path, self.get_our_node_id());
5716+
},
5717+
_ => {},
5718+
}
5719+
}
5720+
}
5721+
5722+
inflight_htlcs
5723+
}
5724+
57065725
#[cfg(any(test, fuzzing, feature = "_test_utils"))]
57075726
pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
57085727
let events = core::cell::RefCell::new(Vec::new());

0 commit comments

Comments
 (0)