Skip to content

Commit 5cdbb7f

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

File tree

5 files changed

+76
-115
lines changed

5 files changed

+76
-115
lines changed

lightning-invoice/src/payment.rs

Lines changed: 42 additions & 114 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);
@@ -1591,20 +1578,17 @@ mod tests {
15911578

15921579
let payment_preimage = PaymentPreimage([1; 32]);
15931580
let invoice = invoice(payment_preimage);
1594-
let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
15951581
let final_value_msat = invoice.amount_milli_satoshis().unwrap();
15961582

15971583
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);
16001584
let router = TestRouter::new(TestScorer::new());
16011585
let logger = TestLogger::new();
16021586
let invoice_payer =
16031587
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
16041588

1605-
let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1589+
invoice_payer.pay_invoice(&invoice).unwrap();
16061590

1607-
let inflight_map = invoice_payer.create_inflight_map();
1591+
let inflight_map = invoice_payer.payer.inflight_htlcs();
16081592
// First path check
16091593
assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
16101594
assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
@@ -1613,20 +1597,6 @@ mod tests {
16131597
// Second path check
16141598
assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
16151599
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)
16301600
}
16311601

16321602
#[test]
@@ -1637,14 +1607,11 @@ mod tests {
16371607

16381608
let payment_preimage = PaymentPreimage([1; 32]);
16391609
let payment_invoice = invoice(payment_preimage);
1640-
let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
16411610
let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
16421611

16431612
let payer = TestPayer::new()
16441613
.expect_send(Amount::ForInvoice(final_value_msat))
16451614
.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);
16481615
let scorer = TestScorer::new()
16491616
// 1st invoice, 1st path
16501617
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
@@ -1654,9 +1621,9 @@ mod tests {
16541621
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
16551622
.expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
16561623
// 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 } )
1624+
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1625+
.expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 84, effective_capacity: EffectiveCapacity::Unknown } )
1626+
.expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 94, effective_capacity: EffectiveCapacity::Unknown } )
16601627
// 2nd invoice, 2nd path
16611628
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
16621629
.expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
@@ -1665,16 +1632,12 @@ mod tests {
16651632
let invoice_payer =
16661633
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
16671634

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-
});
1635+
// Make first invoice payment.
1636+
invoice_payer.pay_invoice(&payment_invoice).unwrap();
16731637

16741638
// 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.
1639+
// assertions that expect `ChannelUsage` values of the first invoice payment that is still
1640+
// in-flight.
16781641
let payment_preimage_2 = PaymentPreimage([2; 32]);
16791642
let payment_invoice_2 = invoice(payment_preimage_2);
16801643
invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
@@ -1725,6 +1688,7 @@ mod tests {
17251688

17261689
// Fail 1st path, leave 2nd path inflight
17271690
let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1691+
invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat));
17281692
invoice_payer.handle_event(Event::PaymentPathFailed {
17291693
payment_id,
17301694
payment_hash,
@@ -1737,6 +1701,7 @@ mod tests {
17371701
});
17381702

17391703
// Fails again the 1st path of our retry
1704+
invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat / 2));
17401705
invoice_payer.handle_event(Event::PaymentPathFailed {
17411706
payment_id,
17421707
payment_hash,
@@ -1752,67 +1717,6 @@ mod tests {
17521717
});
17531718
}
17541719

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-
18161720
struct TestRouter {
18171721
scorer: RefCell<TestScorer>,
18181722
}
@@ -2100,6 +2004,7 @@ mod tests {
21002004
expectations: core::cell::RefCell<VecDeque<Amount>>,
21012005
attempts: core::cell::RefCell<usize>,
21022006
failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
2007+
inflight_htlcs_paths: core::cell::RefCell<Vec<Vec<RouteHop>>>,
21032008
}
21042009

21052010
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -2117,6 +2022,7 @@ mod tests {
21172022
expectations: core::cell::RefCell::new(VecDeque::new()),
21182023
attempts: core::cell::RefCell::new(0),
21192024
failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
2025+
inflight_htlcs_paths: core::cell::RefCell::new(Vec::new()),
21202026
}
21212027
}
21222028

@@ -2161,6 +2067,18 @@ mod tests {
21612067
panic!("Unexpected amount: {:?}", actual_value_msats);
21622068
}
21632069
}
2070+
2071+
fn process_route(&self, route: &Route) {
2072+
for path in &route.paths {
2073+
self.inflight_htlcs_paths.borrow_mut().push(path.clone());
2074+
}
2075+
}
2076+
2077+
fn fail_path(&self, path: &Vec<RouteHop>) {
2078+
if let Some(idx) = self.inflight_htlcs_paths.clone().into_inner().iter().position(|p| p == path) {
2079+
self.inflight_htlcs_paths.borrow_mut().swap_remove(idx);
2080+
}
2081+
}
21642082
}
21652083

21662084
impl Drop for TestPayer {
@@ -2190,6 +2108,7 @@ mod tests {
21902108
_payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
21912109
) -> Result<(), PaymentSendFailure> {
21922110
self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2111+
self.process_route(route);
21932112
self.check_attempts()
21942113
}
21952114

@@ -2204,10 +2123,19 @@ mod tests {
22042123
&self, route: &Route, _payment_id: PaymentId
22052124
) -> Result<(), PaymentSendFailure> {
22062125
self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2126+
self.process_route(route);
22072127
self.check_attempts()
22082128
}
22092129

22102130
fn abandon_payment(&self, _payment_id: PaymentId) { }
2131+
2132+
fn inflight_htlcs(&self) -> InFlightHtlcs {
2133+
let mut inflight_htlcs = InFlightHtlcs::new();
2134+
for path in self.inflight_htlcs_paths.clone().into_inner() {
2135+
inflight_htlcs.process_path(&path, self.node_id());
2136+
}
2137+
inflight_htlcs
2138+
}
22112139
}
22122140

22132141
// *** 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());

lightning/src/routing/router.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ pub trait Router {
4545
#[cfg(not(any(test, feature = "_test_utils")))]
4646
pub struct InFlightHtlcs(HashMap<(u64, bool), u64>);
4747
#[cfg(any(test, feature = "_test_utils"))]
48+
#[derive(Clone)]
4849
pub struct InFlightHtlcs(pub HashMap<(u64, bool), u64>);
4950

5051
impl InFlightHtlcs {

0 commit comments

Comments
 (0)