Skip to content

Commit 897ecbf

Browse files
committed
Compute InflightHtlcs from available information in ChannelManager
1 parent 50d4e28 commit 897ecbf

File tree

5 files changed

+82
-114
lines changed

5 files changed

+82
-114
lines changed

lightning-invoice/src/payment.rs

Lines changed: 42 additions & 113 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 {}
@@ -276,6 +277,10 @@ pub trait Payer {
276277

277278
/// Signals that no further retries for the given payment will occur.
278279
fn abandon_payment(&self, payment_id: PaymentId);
280+
281+
/// Construct an [`InFlightHtlcs`] containing information about currently used up liquidity
282+
/// across payments.
283+
fn inflight_htlcs(&self) -> InFlightHtlcs;
279284
}
280285

281286
/// A trait defining behavior for a [`Router`] implementation that also supports scoring channels
@@ -532,7 +537,7 @@ where
532537

533538
let payer = self.payer.node_id();
534539
let first_hops = self.payer.first_hops();
535-
let inflight_htlcs = self.create_inflight_map();
540+
let inflight_htlcs = self.payer.inflight_htlcs();
536541
let route = self.router.find_route(
537542
&payer, &params, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
538543
).map_err(|e| PaymentError::Routing(e))?;
@@ -635,7 +640,7 @@ where
635640

636641
let payer = self.payer.node_id();
637642
let first_hops = self.payer.first_hops();
638-
let inflight_htlcs = self.create_inflight_map();
643+
let inflight_htlcs = self.payer.inflight_htlcs();
639644

640645
let route = self.router.find_route(
641646
&payer, &params, Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs
@@ -690,23 +695,6 @@ where
690695
pub fn remove_cached_payment(&self, payment_hash: &PaymentHash) {
691696
self.payment_cache.lock().unwrap().remove(payment_hash);
692697
}
693-
694-
/// Use path information in the payment_cache to construct a HashMap mapping a channel's short
695-
/// channel id and direction to the amount being sent through it.
696-
///
697-
/// This function should be called whenever we need information about currently used up liquidity
698-
/// across payments.
699-
fn create_inflight_map(&self) -> InFlightHtlcs {
700-
let mut total_inflight_map = InFlightHtlcs::new();
701-
// Make an attempt at finding existing payment information from `payment_cache`.
702-
for payment_info in self.payment_cache.lock().unwrap().values() {
703-
for path in &payment_info.paths {
704-
total_inflight_map.process_path(path, self.payer.node_id());
705-
}
706-
}
707-
708-
total_inflight_map
709-
}
710698
}
711699

712700
fn expiry_time_from_unix_epoch(invoice: &Invoice) -> Duration {
@@ -818,7 +806,6 @@ mod tests {
818806
use std::time::{SystemTime, Duration};
819807
use crate::time_utils::tests::SinceEpoch;
820808
use crate::DEFAULT_EXPIRY_TIME;
821-
use lightning::util::errors::APIError::{ChannelUnavailable, MonitorUpdateInProgress};
822809

823810
fn invoice(payment_preimage: PaymentPreimage) -> Invoice {
824811
let payment_hash = Sha256::hash(&payment_preimage.0);
@@ -1544,20 +1531,17 @@ mod tests {
15441531

15451532
let payment_preimage = PaymentPreimage([1; 32]);
15461533
let invoice = invoice(payment_preimage);
1547-
let payment_hash = Some(PaymentHash(invoice.payment_hash().clone().into_inner()));
15481534
let final_value_msat = invoice.amount_milli_satoshis().unwrap();
15491535

15501536
let payer = TestPayer::new().expect_send(Amount::ForInvoice(final_value_msat));
1551-
let final_value_msat = invoice.amount_milli_satoshis().unwrap();
1552-
let route = TestRouter::route_for_value(final_value_msat);
15531537
let router = TestRouter::new(TestScorer::new());
15541538
let logger = TestLogger::new();
15551539
let invoice_payer =
15561540
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
15571541

1558-
let payment_id = invoice_payer.pay_invoice(&invoice).unwrap();
1542+
invoice_payer.pay_invoice(&invoice).unwrap();
15591543

1560-
let inflight_map = invoice_payer.create_inflight_map();
1544+
let inflight_map = invoice_payer.payer.inflight_htlcs();
15611545
// First path check
15621546
assert_eq!(inflight_map.0.get(&(0, false)).unwrap().clone(), 94);
15631547
assert_eq!(inflight_map.0.get(&(1, true)).unwrap().clone(), 84);
@@ -1566,20 +1550,6 @@ mod tests {
15661550
// Second path check
15671551
assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
15681552
assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64);
1569-
1570-
invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1571-
payment_id, payment_hash, path: route.paths[0].clone()
1572-
});
1573-
1574-
let inflight_map = invoice_payer.create_inflight_map();
1575-
1576-
assert_eq!(inflight_map.0.get(&(0, false)), None);
1577-
assert_eq!(inflight_map.0.get(&(1, true)), None);
1578-
assert_eq!(inflight_map.0.get(&(2, false)), None);
1579-
1580-
// Second path should still be inflight
1581-
assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74);
1582-
assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64)
15831553
}
15841554

15851555
#[test]
@@ -1590,14 +1560,11 @@ mod tests {
15901560

15911561
let payment_preimage = PaymentPreimage([1; 32]);
15921562
let payment_invoice = invoice(payment_preimage);
1593-
let payment_hash = Some(PaymentHash(payment_invoice.payment_hash().clone().into_inner()));
15941563
let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
15951564

15961565
let payer = TestPayer::new()
15971566
.expect_send(Amount::ForInvoice(final_value_msat))
15981567
.expect_send(Amount::ForInvoice(final_value_msat));
1599-
let final_value_msat = payment_invoice.amount_milli_satoshis().unwrap();
1600-
let route = TestRouter::route_for_value(final_value_msat);
16011568
let scorer = TestScorer::new()
16021569
// 1st invoice, 1st path
16031570
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
@@ -1607,9 +1574,9 @@ mod tests {
16071574
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
16081575
.expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
16091576
// 2nd invoice, 1st path
1610-
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1611-
.expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1612-
.expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 0, effective_capacity: EffectiveCapacity::Unknown } )
1577+
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
1578+
.expect_usage(ChannelUsage { amount_msat: 84, inflight_htlc_msat: 84, effective_capacity: EffectiveCapacity::Unknown } )
1579+
.expect_usage(ChannelUsage { amount_msat: 94, inflight_htlc_msat: 94, effective_capacity: EffectiveCapacity::Unknown } )
16131580
// 2nd invoice, 2nd path
16141581
.expect_usage(ChannelUsage { amount_msat: 64, inflight_htlc_msat: 64, effective_capacity: EffectiveCapacity::Unknown } )
16151582
.expect_usage(ChannelUsage { amount_msat: 74, inflight_htlc_msat: 74, effective_capacity: EffectiveCapacity::Unknown } );
@@ -1618,16 +1585,12 @@ mod tests {
16181585
let invoice_payer =
16191586
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
16201587

1621-
// Succeed 1st path, leave 2nd path inflight
1622-
let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap();
1623-
invoice_payer.handle_event(&Event::PaymentPathSuccessful {
1624-
payment_id, payment_hash, path: route.paths[0].clone()
1625-
});
1588+
// Make first invoice payment.
1589+
invoice_payer.pay_invoice(&payment_invoice).unwrap();
16261590

16271591
// Let's pay a second invoice that will be using the same path. This should trigger the
1628-
// assertions that expect the last 4 ChannelUsage values above where TestScorer is initialized.
1629-
// Particularly, the 2nd path of the 1st payment, since it is not yet complete, should still
1630-
// have 64 msats inflight for paths considering the channel with scid of 1.
1592+
// assertions that expect `ChannelUsage` values of the first invoice payment that is still
1593+
// in-flight.
16311594
let payment_preimage_2 = PaymentPreimage([2; 32]);
16321595
let payment_invoice_2 = invoice(payment_preimage_2);
16331596
invoice_payer.pay_invoice(&payment_invoice_2).unwrap();
@@ -1678,6 +1641,7 @@ mod tests {
16781641

16791642
// Fail 1st path, leave 2nd path inflight
16801643
let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap());
1644+
invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat));
16811645
invoice_payer.handle_event(&Event::PaymentPathFailed {
16821646
payment_id,
16831647
payment_hash,
@@ -1690,6 +1654,7 @@ mod tests {
16901654
});
16911655

16921656
// Fails again the 1st path of our retry
1657+
invoice_payer.payer.fail_path(&TestRouter::path_for_value(final_value_msat / 2));
16931658
invoice_payer.handle_event(&Event::PaymentPathFailed {
16941659
payment_id,
16951660
payment_hash,
@@ -1705,66 +1670,6 @@ mod tests {
17051670
});
17061671
}
17071672

1708-
#[test]
1709-
fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() {
1710-
let event_handled = core::cell::RefCell::new(false);
1711-
let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1712-
1713-
let payment_preimage = PaymentPreimage([1; 32]);
1714-
let invoice_to_pay = invoice(payment_preimage);
1715-
let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1716-
1717-
let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1718-
let payer = TestPayer::new()
1719-
.fails_with_partial_failure(
1720-
retry.clone(), OnAttempt(1),
1721-
Some(vec![
1722-
Err(ChannelUnavailable { err: "abc".to_string() }), Err(MonitorUpdateInProgress)
1723-
]))
1724-
.expect_send(Amount::ForInvoice(final_value_msat));
1725-
1726-
let router = TestRouter::new(TestScorer::new());
1727-
let logger = TestLogger::new();
1728-
let invoice_payer =
1729-
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1730-
1731-
invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1732-
let inflight_map = invoice_payer.create_inflight_map();
1733-
1734-
// Only the second path, which failed with `MonitorUpdateInProgress` should be added to our
1735-
// inflight map because retries are disabled.
1736-
assert_eq!(inflight_map.0.len(), 2);
1737-
}
1738-
1739-
#[test]
1740-
fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() {
1741-
let event_handled = core::cell::RefCell::new(false);
1742-
let event_handler = |_: &_| { *event_handled.borrow_mut() = true; };
1743-
1744-
let payment_preimage = PaymentPreimage([1; 32]);
1745-
let invoice_to_pay = invoice(payment_preimage);
1746-
let final_value_msat = invoice_to_pay.amount_milli_satoshis().unwrap();
1747-
1748-
let retry = TestRouter::retry_for_invoice(&invoice_to_pay);
1749-
let payer = TestPayer::new()
1750-
.fails_with_partial_failure(
1751-
retry.clone(), OnAttempt(1),
1752-
Some(vec![
1753-
Ok(()), Err(MonitorUpdateInProgress)
1754-
]))
1755-
.expect_send(Amount::ForInvoice(final_value_msat));
1756-
1757-
let router = TestRouter::new(TestScorer::new());
1758-
let logger = TestLogger::new();
1759-
let invoice_payer =
1760-
InvoicePayer::new(&payer, router, &logger, event_handler, Retry::Attempts(0));
1761-
1762-
invoice_payer.pay_invoice(&invoice_to_pay).unwrap();
1763-
let inflight_map = invoice_payer.create_inflight_map();
1764-
1765-
// All paths successful, hence we check of the existence of all 5 hops.
1766-
assert_eq!(inflight_map.0.len(), 5);
1767-
}
17681673

17691674
struct TestRouter {
17701675
scorer: RefCell<TestScorer>,
@@ -2053,6 +1958,7 @@ mod tests {
20531958
expectations: core::cell::RefCell<VecDeque<Amount>>,
20541959
attempts: core::cell::RefCell<usize>,
20551960
failing_on_attempt: core::cell::RefCell<HashMap<usize, PaymentSendFailure>>,
1961+
inflight_htlcs_paths: core::cell::RefCell<Vec<Vec<RouteHop>>>,
20561962
}
20571963

20581964
#[derive(Clone, Debug, PartialEq, Eq)]
@@ -2070,6 +1976,7 @@ mod tests {
20701976
expectations: core::cell::RefCell::new(VecDeque::new()),
20711977
attempts: core::cell::RefCell::new(0),
20721978
failing_on_attempt: core::cell::RefCell::new(HashMap::new()),
1979+
inflight_htlcs_paths: core::cell::RefCell::new(Vec::new()),
20731980
}
20741981
}
20751982

@@ -2114,6 +2021,18 @@ mod tests {
21142021
panic!("Unexpected amount: {:?}", actual_value_msats);
21152022
}
21162023
}
2024+
2025+
fn process_route(&self, route: &Route) {
2026+
for path in &route.paths {
2027+
self.inflight_htlcs_paths.borrow_mut().push(path.clone());
2028+
}
2029+
}
2030+
2031+
fn fail_path(&self, path: &Vec<RouteHop>) {
2032+
if let Some(idx) = self.inflight_htlcs_paths.clone().into_inner().iter().position(|p| p == path) {
2033+
self.inflight_htlcs_paths.borrow_mut().swap_remove(idx);
2034+
}
2035+
}
21172036
}
21182037

21192038
impl Drop for TestPayer {
@@ -2143,6 +2062,7 @@ mod tests {
21432062
_payment_secret: &Option<PaymentSecret>, _payment_id: PaymentId,
21442063
) -> Result<(), PaymentSendFailure> {
21452064
self.check_value_msats(Amount::ForInvoice(route.get_total_amount()));
2065+
self.process_route(route);
21462066
self.check_attempts()
21472067
}
21482068

@@ -2157,10 +2077,19 @@ mod tests {
21572077
&self, route: &Route, _payment_id: PaymentId
21582078
) -> Result<(), PaymentSendFailure> {
21592079
self.check_value_msats(Amount::OnRetry(route.get_total_amount()));
2080+
self.process_route(route);
21602081
self.check_attempts()
21612082
}
21622083

21632084
fn abandon_payment(&self, _payment_id: PaymentId) { }
2085+
2086+
fn inflight_htlcs(&self) -> InFlightHtlcs {
2087+
let mut inflight_htlcs = InFlightHtlcs::new();
2088+
for path in self.inflight_htlcs_paths.clone().into_inner() {
2089+
inflight_htlcs.process_path(&path, self.node_id());
2090+
}
2091+
inflight_htlcs
2092+
}
21642093
}
21652094

21662095
// *** 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: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5936,6 +5936,23 @@ impl<Signer: Sign> Channel<Signer> {
59365936
self.update_time_counter += 1;
59375937
(monitor_update, dropped_outbound_htlcs)
59385938
}
5939+
5940+
pub fn inflight_htlc_sources(&self) -> Vec<&HTLCSource> {
5941+
let holding_cell_sources: Vec<&HTLCSource> = self.holding_cell_htlc_updates.iter()
5942+
.flat_map(|htlc_update| {
5943+
match htlc_update {
5944+
HTLCUpdateAwaitingACK::AddHTLC { source, .. } => { Some(source) }
5945+
_ => { None }
5946+
}
5947+
})
5948+
.collect();
5949+
5950+
let pending_outbound_sources: Vec<&HTLCSource> = self.pending_outbound_htlcs.iter()
5951+
.map(|htlc| &htlc.source)
5952+
.collect();
5953+
5954+
return holding_cell_sources.into_iter().chain(pending_outbound_sources.into_iter()).collect();
5955+
}
59395956
}
59405957

59415958
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::{PaymentParameters, Route, RouteHop, RoutePath, RouteParameters, InFlightHtlcs};
5050
use crate::ln::msgs;
5151
use crate::ln::onion_utils;
5252
use crate::ln::msgs::{ChannelMessageHandler, DecodeError, LightningError, MAX_VALUE_MSAT};
@@ -5658,6 +5658,25 @@ impl<M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> ChannelManager<M, T, K, F
56585658
}
56595659
}
56605660

5661+
/// Gets inflight HTLC information by processing pending `HTLCSource`s that are in
5662+
/// `Channel::pending_outbound_htlcs`
5663+
pub fn compute_inflight_htlcs(&self) -> InFlightHtlcs {
5664+
let mut inflight_htlcs = InFlightHtlcs::new();
5665+
5666+
for chan in self.channel_state.lock().unwrap().by_id.values() {
5667+
for htlc_source in chan.inflight_htlc_sources() {
5668+
match htlc_source {
5669+
HTLCSource::OutboundRoute { path, .. } => {
5670+
inflight_htlcs.process_path(path, self.get_our_node_id());
5671+
},
5672+
_ => {},
5673+
}
5674+
}
5675+
}
5676+
5677+
inflight_htlcs
5678+
}
5679+
56615680
#[cfg(any(test, fuzzing, feature = "_test_utils"))]
56625681
pub fn get_and_clear_pending_events(&self) -> Vec<events::Event> {
56635682
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)