X-Git-Url: http://git.bitcoin.ninja/index.cgi?a=blobdiff_plain;f=lightning-invoice%2Fsrc%2Fpayment.rs;h=cbd760c37d02d045c82cbc942432c1f2c82dc419;hb=593d8c4610f082441563d4906d64175a354b1cfc;hp=7d5b87cf457def69b76bd94064952aa6f2744799;hpb=790d26f63f1ed6fff8742bd0df58bf010a11b567;p=rust-lightning diff --git a/lightning-invoice/src/payment.rs b/lightning-invoice/src/payment.rs index 7d5b87cf..cbd760c3 100644 --- a/lightning-invoice/src/payment.rs +++ b/lightning-invoice/src/payment.rs @@ -38,13 +38,13 @@ //! # use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure}; //! # use lightning::ln::msgs::LightningError; //! # use lightning::routing::gossip::NodeId; -//! # use lightning::routing::router::{Route, RouteHop, RouteParameters}; +//! # use lightning::routing::router::{InFlightHtlcs, Route, RouteHop, RouteParameters, Router}; //! # use lightning::routing::scoring::{ChannelUsage, Score}; //! # use lightning::util::events::{Event, EventHandler, EventsProvider}; //! # use lightning::util::logger::{Logger, Record}; //! # use lightning::util::ser::{Writeable, Writer}; //! # use lightning_invoice::Invoice; -//! # use lightning_invoice::payment::{InFlightHtlcs, InvoicePayer, Payer, Retry, Router}; +//! # use lightning_invoice::payment::{InvoicePayer, Payer, Retry, ScoringRouter}; //! # use secp256k1::PublicKey; //! # use std::cell::RefCell; //! # use std::ops::Deref; @@ -74,10 +74,11 @@ //! # struct FakeRouter {} //! # impl Router for FakeRouter { //! # fn find_route( -//! # &self, payer: &PublicKey, params: &RouteParameters, payment_hash: &PaymentHash, +//! # &self, payer: &PublicKey, params: &RouteParameters, //! # first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs //! # ) -> Result { unimplemented!() } -//! # +//! # } +//! # impl ScoringRouter for FakeRouter { //! # fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) { unimplemented!() } //! # fn notify_payment_path_successful(&self, path: &[&RouteHop]) { unimplemented!() } //! # fn notify_payment_probe_successful(&self, path: &[&RouteHop]) { unimplemented!() } @@ -104,7 +105,7 @@ //! # } //! # //! # fn main() { -//! let event_handler = |event: &Event| { +//! let event_handler = |event: Event| { //! match event { //! Event::PaymentPathFailed { .. } => println!("payment failed after retries"), //! Event::PaymentSent { .. } => println!("payment successful"), @@ -141,16 +142,14 @@ use bitcoin_hashes::Hash; use bitcoin_hashes::sha256::Hash as Sha256; use crate::prelude::*; -use lightning::io; use lightning::ln::{PaymentHash, PaymentPreimage, PaymentSecret}; use lightning::ln::channelmanager::{ChannelDetails, PaymentId, PaymentSendFailure}; use lightning::ln::msgs::LightningError; use lightning::routing::gossip::NodeId; -use lightning::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters}; +use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, Router}; use lightning::util::errors::APIError; use lightning::util::events::{Event, EventHandler}; use lightning::util::logger::Logger; -use lightning::util::ser::Writeable; use crate::time_utils::Time; use crate::sync::Mutex; @@ -158,6 +157,7 @@ use secp256k1::PublicKey; use core::fmt; use core::fmt::{Debug, Display, Formatter}; +use core::future::Future; use core::ops::Deref; use core::time::Duration; #[cfg(feature = "std")] @@ -177,9 +177,21 @@ use crate::time_utils; #[cfg(feature = "no-std")] type ConfiguredTime = time_utils::Eternity; +/// Sealed trait with a blanket implementation to allow both sync and async implementations of event +/// handling to exist within the InvoicePayer. +mod sealed { + pub trait BaseEventHandler {} + impl BaseEventHandler for T {} +} + /// (C-not exported) generally all users should use the [`InvoicePayer`] type alias. -pub struct InvoicePayerUsingTime -where +pub struct InvoicePayerUsingTime< + P: Deref, + R: ScoringRouter, + L: Deref, + E: sealed::BaseEventHandler, + T: Time +> where P::Target: Payer, L::Target: Logger, { @@ -280,13 +292,20 @@ pub trait Payer { fn abandon_payment(&self, payment_id: PaymentId); } -/// A trait defining behavior for routing an [`Invoice`] payment. -pub trait Router { - /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. - fn find_route( - &self, payer: &PublicKey, route_params: &RouteParameters, payment_hash: &PaymentHash, - first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs - ) -> Result; +/// A trait defining behavior for a [`Router`] implementation that also supports scoring channels +/// based on payment and probe success/failure. +/// +/// [`Router`]: lightning::routing::router::Router +pub trait ScoringRouter: Router { + /// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes + /// `PaymentHash` and `PaymentId` to be able to correlate the request with a specific payment. + fn find_route_with_id( + &self, payer: &PublicKey, route_params: &RouteParameters, + first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs, + _payment_hash: PaymentHash, _payment_id: PaymentId + ) -> Result { + self.find_route(payer, route_params, first_hops, inflight_htlcs) + } /// Lets the router know that payment through a specific path has failed. fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64); /// Lets the router know that payment through a specific path was successful. @@ -336,7 +355,8 @@ pub enum PaymentError { Sending(PaymentSendFailure), } -impl InvoicePayerUsingTime +impl + InvoicePayerUsingTime where P::Target: Payer, L::Target: Logger, @@ -529,8 +549,7 @@ where let first_hops = self.payer.first_hops(); let inflight_htlcs = self.create_inflight_map(); let route = self.router.find_route( - &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::>()), - inflight_htlcs + &payer, ¶ms, Some(&first_hops.iter().collect::>()), inflight_htlcs ).map_err(|e| PaymentError::Routing(e))?; match send_payment(&route) { @@ -634,8 +653,7 @@ where let inflight_htlcs = self.create_inflight_map(); let route = self.router.find_route( - &payer, ¶ms, &payment_hash, Some(&first_hops.iter().collect::>()), - inflight_htlcs + &payer, ¶ms, Some(&first_hops.iter().collect::>()), inflight_htlcs ); if route.is_err() { @@ -688,9 +706,8 @@ where self.payment_cache.lock().unwrap().remove(payment_hash); } - /// Given a [`PaymentHash`], this function looks up inflight path attempts in the payment_cache. - /// Then, it uses the path information inside the cache to construct a HashMap mapping a channel's - /// short channel id and direction to the amount being sent through it. + /// Use path information in the payment_cache to construct a HashMap mapping a channel's short + /// channel id and direction to the amount being sent through it. /// /// This function should be called whenever we need information about currently used up liquidity /// across payments. @@ -726,7 +743,7 @@ where } } - InFlightHtlcs(total_inflight_map) + InFlightHtlcs::new(total_inflight_map) } } @@ -741,12 +758,15 @@ fn has_expired(route_params: &RouteParameters) -> bool { } else { false } } -impl EventHandler for InvoicePayerUsingTime +impl + InvoicePayerUsingTime where P::Target: Payer, L::Target: Logger, { - fn handle_event(&self, event: &Event) { + /// Returns a bool indicating whether the processed event should be forwarded to a user-provided + /// event handler. + fn handle_event_internal(&self, event: &Event) -> bool { match event { Event::PaymentPathFailed { payment_hash, path, .. } | Event::PaymentPathSuccessful { path, payment_hash: Some(payment_hash), .. } @@ -776,7 +796,7 @@ where self.payer.abandon_payment(payment_id.unwrap()); } else if self.retry_payment(payment_id.unwrap(), *payment_hash, retry.as_ref().unwrap()).is_ok() { // We retried at least somewhat, don't provide the PaymentPathFailed event to the user. - return; + return false; } else { self.payer.abandon_payment(payment_id.unwrap()); } @@ -811,32 +831,37 @@ where } // Delegate to the decorated event handler unless the payment is retried. - self.event_handler.handle_event(event) + true } } -/// A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC -/// is traveling in. The direction boolean is determined by checking if the HTLC source's public -/// key is less than its destination. See [`InFlightHtlcs::used_liquidity_msat`] for more -/// details. -pub struct InFlightHtlcs(HashMap<(u64, bool), u64>); - -impl InFlightHtlcs { - /// Returns liquidity in msat given the public key of the HTLC source, target, and short channel - /// id. - pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option { - self.0.get(&(channel_scid, source < target)).map(|v| *v) +impl + EventHandler for InvoicePayerUsingTime +where + P::Target: Payer, + L::Target: Logger, +{ + fn handle_event(&self, event: Event) { + let should_forward = self.handle_event_internal(&event); + if should_forward { + self.event_handler.handle_event(event) + } } } -impl Writeable for InFlightHtlcs { - fn write(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) } -} - -impl lightning::util::ser::Readable for InFlightHtlcs { - fn read(reader: &mut R) -> Result { - let infight_map: HashMap<(u64, bool), u64> = lightning::util::ser::Readable::read(reader)?; - Ok(Self(infight_map)) +impl F> + InvoicePayerUsingTime +where + P::Target: Payer, + L::Target: Logger, +{ + /// Intercepts events required by the [`InvoicePayer`] and forwards them to the underlying event + /// handler, if necessary, to handle them asynchronously. + pub async fn handle_event_async(&self, event: Event) { + let should_forward = self.handle_event_internal(&event); + if should_forward { + (self.event_handler)(event).await; + } } } @@ -852,7 +877,7 @@ mod tests { use lightning::ln::functional_test_utils::*; use lightning::ln::msgs::{ChannelMessageHandler, ErrorAction, LightningError}; use lightning::routing::gossip::{EffectiveCapacity, NodeId}; - use lightning::routing::router::{PaymentParameters, Route, RouteHop}; + use lightning::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, Router}; use lightning::routing::scoring::{ChannelUsage, LockableScore, Score}; use lightning::util::test_utils::TestLogger; use lightning::util::errors::APIError; @@ -935,7 +960,7 @@ mod tests { #[test] fn pays_invoice_on_first_attempt() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -951,7 +976,7 @@ mod tests { let payment_id = Some(invoice_payer.pay_invoice(&invoice).unwrap()); assert_eq!(*payer.attempts.borrow(), 1); - invoice_payer.handle_event(&Event::PaymentSent { + invoice_payer.handle_event(Event::PaymentSent { payment_id, payment_preimage, payment_hash, fee_paid_msat: None }); assert_eq!(*event_handled.borrow(), true); @@ -961,7 +986,7 @@ mod tests { #[test] fn pays_invoice_on_retry() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -989,11 +1014,11 @@ mod tests { short_channel_id: None, retry: Some(TestRouter::retry_for_invoice(&invoice)), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); assert_eq!(*event_handled.borrow(), false); assert_eq!(*payer.attempts.borrow(), 2); - invoice_payer.handle_event(&Event::PaymentSent { + invoice_payer.handle_event(Event::PaymentSent { payment_id, payment_preimage, payment_hash, fee_paid_msat: None }); assert_eq!(*event_handled.borrow(), true); @@ -1002,7 +1027,7 @@ mod tests { #[test] fn pays_invoice_on_partial_failure() { - let event_handler = |_: &_| { panic!() }; + let event_handler = |_: Event| { panic!() }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1026,7 +1051,7 @@ mod tests { #[test] fn retries_payment_path_for_unknown_payment() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1052,15 +1077,15 @@ mod tests { short_channel_id: None, retry: Some(TestRouter::retry_for_invoice(&invoice)), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event.clone()); assert_eq!(*event_handled.borrow(), false); assert_eq!(*payer.attempts.borrow(), 1); - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event.clone()); assert_eq!(*event_handled.borrow(), false); assert_eq!(*payer.attempts.borrow(), 2); - invoice_payer.handle_event(&Event::PaymentSent { + invoice_payer.handle_event(Event::PaymentSent { payment_id, payment_preimage, payment_hash, fee_paid_msat: None }); assert_eq!(*event_handled.borrow(), true); @@ -1070,7 +1095,7 @@ mod tests { #[test] fn fails_paying_invoice_after_max_retry_counts() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1098,7 +1123,7 @@ mod tests { short_channel_id: None, retry: Some(TestRouter::retry_for_invoice(&invoice)), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); assert_eq!(*event_handled.borrow(), false); assert_eq!(*payer.attempts.borrow(), 2); @@ -1114,11 +1139,11 @@ mod tests { final_value_msat: final_value_msat / 2, ..TestRouter::retry_for_invoice(&invoice) }), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event.clone()); assert_eq!(*event_handled.borrow(), false); assert_eq!(*payer.attempts.borrow(), 3); - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event.clone()); assert_eq!(*event_handled.borrow(), true); assert_eq!(*payer.attempts.borrow(), 3); } @@ -1127,7 +1152,7 @@ mod tests { #[test] fn fails_paying_invoice_after_max_retry_timeout() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1157,13 +1182,13 @@ mod tests { short_channel_id: None, retry: Some(TestRouter::retry_for_invoice(&invoice)), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event.clone()); assert_eq!(*event_handled.borrow(), false); assert_eq!(*payer.attempts.borrow(), 2); SinceEpoch::advance(Duration::from_secs(121)); - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event.clone()); assert_eq!(*event_handled.borrow(), true); assert_eq!(*payer.attempts.borrow(), 2); } @@ -1171,7 +1196,7 @@ mod tests { #[test] fn fails_paying_invoice_with_missing_retry_params() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1196,7 +1221,7 @@ mod tests { short_channel_id: None, retry: None, }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); assert_eq!(*event_handled.borrow(), true); assert_eq!(*payer.attempts.borrow(), 1); } @@ -1206,7 +1231,7 @@ mod tests { #[test] fn fails_paying_invoice_after_expiration() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payer = TestPayer::new(); let router = TestRouter::new(TestScorer::new()); @@ -1226,7 +1251,7 @@ mod tests { #[test] fn fails_retrying_invoice_after_expiration() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1255,7 +1280,7 @@ mod tests { short_channel_id: None, retry: Some(retry_data), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); assert_eq!(*event_handled.borrow(), true); assert_eq!(*payer.attempts.borrow(), 1); } @@ -1263,7 +1288,7 @@ mod tests { #[test] fn fails_paying_invoice_after_retry_error() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1291,7 +1316,7 @@ mod tests { short_channel_id: None, retry: Some(TestRouter::retry_for_invoice(&invoice)), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); assert_eq!(*event_handled.borrow(), true); assert_eq!(*payer.attempts.borrow(), 2); } @@ -1299,7 +1324,7 @@ mod tests { #[test] fn fails_paying_invoice_after_rejected_by_payee() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1324,7 +1349,7 @@ mod tests { short_channel_id: None, retry: Some(TestRouter::retry_for_invoice(&invoice)), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); assert_eq!(*event_handled.borrow(), true); assert_eq!(*payer.attempts.borrow(), 1); } @@ -1332,7 +1357,7 @@ mod tests { #[test] fn fails_repaying_invoice_with_pending_payment() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1372,7 +1397,7 @@ mod tests { short_channel_id: None, retry: Some(TestRouter::retry_for_invoice(&invoice)), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); assert_eq!(*event_handled.borrow(), true); } @@ -1382,7 +1407,7 @@ mod tests { let router = FailingRouter {}; let logger = TestLogger::new(); let invoice_payer = - InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0)); + InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0)); let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1405,7 +1430,7 @@ mod tests { let router = TestRouter::new(TestScorer::new()); let logger = TestLogger::new(); let invoice_payer = - InvoicePayer::new(&payer, router, &logger, |_: &_| {}, Retry::Attempts(0)); + InvoicePayer::new(&payer, router, &logger, |_: Event| {}, Retry::Attempts(0)); match invoice_payer.pay_invoice(&invoice) { Err(PaymentError::Sending(_)) => {}, @@ -1417,7 +1442,7 @@ mod tests { #[test] fn pays_zero_value_invoice_using_amount() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = zero_value_invoice(payment_preimage); @@ -1434,7 +1459,7 @@ mod tests { Some(invoice_payer.pay_zero_value_invoice(&invoice, final_value_msat).unwrap()); assert_eq!(*payer.attempts.borrow(), 1); - invoice_payer.handle_event(&Event::PaymentSent { + invoice_payer.handle_event(Event::PaymentSent { payment_id, payment_preimage, payment_hash, fee_paid_msat: None }); assert_eq!(*event_handled.borrow(), true); @@ -1444,7 +1469,7 @@ mod tests { #[test] fn fails_paying_zero_value_invoice_with_amount() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payer = TestPayer::new(); let router = TestRouter::new(TestScorer::new()); @@ -1466,7 +1491,7 @@ mod tests { #[test] fn pays_pubkey_with_amount() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let pubkey = pubkey(); let payment_preimage = PaymentPreimage([1; 32]); @@ -1502,11 +1527,11 @@ mod tests { short_channel_id: None, retry: Some(retry), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); assert_eq!(*event_handled.borrow(), false); assert_eq!(*payer.attempts.borrow(), 2); - invoice_payer.handle_event(&Event::PaymentSent { + invoice_payer.handle_event(Event::PaymentSent { payment_id, payment_preimage, payment_hash, fee_paid_msat: None }); assert_eq!(*event_handled.borrow(), true); @@ -1516,7 +1541,7 @@ mod tests { #[test] fn scores_failed_channel() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1548,13 +1573,13 @@ mod tests { short_channel_id, retry: Some(TestRouter::retry_for_invoice(&invoice)), }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); } #[test] fn scores_successful_channels() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1576,17 +1601,17 @@ mod tests { let event = Event::PaymentPathSuccessful { payment_id, payment_hash, path: route.paths[0].clone() }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); let event = Event::PaymentPathSuccessful { payment_id, payment_hash, path: route.paths[1].clone() }; - invoice_payer.handle_event(&event); + invoice_payer.handle_event(event); } #[test] fn generates_correct_inflight_map_data() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice = invoice(payment_preimage); @@ -1613,7 +1638,7 @@ mod tests { assert_eq!(inflight_map.0.get(&(3, false)).unwrap().clone(), 74); assert_eq!(inflight_map.0.get(&(4, false)).unwrap().clone(), 64); - invoice_payer.handle_event(&Event::PaymentPathSuccessful { + invoice_payer.handle_event(Event::PaymentPathSuccessful { payment_id, payment_hash, path: route.paths[0].clone() }); @@ -1632,7 +1657,7 @@ mod tests { fn considers_inflight_htlcs_between_invoice_payments_when_path_succeeds() { // First, let's just send a payment through, but only make sure one of the path completes let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let payment_invoice = invoice(payment_preimage); @@ -1666,7 +1691,7 @@ mod tests { // Succeed 1st path, leave 2nd path inflight let payment_id = invoice_payer.pay_invoice(&payment_invoice).unwrap(); - invoice_payer.handle_event(&Event::PaymentPathSuccessful { + invoice_payer.handle_event(Event::PaymentPathSuccessful { payment_id, payment_hash, path: route.paths[0].clone() }); @@ -1683,7 +1708,7 @@ mod tests { fn considers_inflight_htlcs_between_retries() { // First, let's just send a payment through, but only make sure one of the path completes let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let payment_invoice = invoice(payment_preimage); @@ -1724,7 +1749,7 @@ mod tests { // Fail 1st path, leave 2nd path inflight let payment_id = Some(invoice_payer.pay_invoice(&payment_invoice).unwrap()); - invoice_payer.handle_event(&Event::PaymentPathFailed { + invoice_payer.handle_event(Event::PaymentPathFailed { payment_id, payment_hash, network_update: None, @@ -1736,7 +1761,7 @@ mod tests { }); // Fails again the 1st path of our retry - invoice_payer.handle_event(&Event::PaymentPathFailed { + invoice_payer.handle_event(Event::PaymentPathFailed { payment_id, payment_hash, network_update: None, @@ -1754,7 +1779,7 @@ mod tests { #[test] fn accounts_for_some_inflight_htlcs_sent_during_partial_failure() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice_to_pay = invoice(payment_preimage); @@ -1785,7 +1810,7 @@ mod tests { #[test] fn accounts_for_all_inflight_htlcs_sent_during_partial_failure() { let event_handled = core::cell::RefCell::new(false); - let event_handler = |_: &_| { *event_handled.borrow_mut() = true; }; + let event_handler = |_: Event| { *event_handled.borrow_mut() = true; }; let payment_preimage = PaymentPreimage([1; 32]); let invoice_to_pay = invoice(payment_preimage); @@ -1895,7 +1920,7 @@ mod tests { impl Router for TestRouter { fn find_route( - &self, payer: &PublicKey, route_params: &RouteParameters, _payment_hash: &PaymentHash, + &self, payer: &PublicKey, route_params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs ) -> Result { // Simulate calling the Scorer just as you would in find_route @@ -1926,7 +1951,9 @@ mod tests { payment_params: Some(route_params.payment_params.clone()), ..Self::route_for_value(route_params.final_value_msat) }) } + } + impl ScoringRouter for TestRouter { fn notify_payment_path_failed(&self, path: &[&RouteHop], short_channel_id: u64) { self.scorer.lock().payment_path_failed(path, short_channel_id); } @@ -1948,12 +1975,14 @@ mod tests { impl Router for FailingRouter { fn find_route( - &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash, - _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs + &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>, + _inflight_htlcs: InFlightHtlcs, ) -> Result { Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }) } + } + impl ScoringRouter for FailingRouter { fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {} fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {} @@ -2210,12 +2239,13 @@ mod tests { impl Router for ManualRouter { fn find_route( - &self, _payer: &PublicKey, _params: &RouteParameters, _payment_hash: &PaymentHash, - _first_hops: Option<&[&ChannelDetails]>, _inflight_htlcs: InFlightHtlcs + &self, _payer: &PublicKey, _params: &RouteParameters, _first_hops: Option<&[&ChannelDetails]>, + _inflight_htlcs: InFlightHtlcs ) -> Result { self.0.borrow_mut().pop_front().unwrap() } - + } + impl ScoringRouter for ManualRouter { fn notify_payment_path_failed(&self, _path: &[&RouteHop], _short_channel_id: u64) {} fn notify_payment_path_successful(&self, _path: &[&RouteHop]) {} @@ -2277,7 +2307,7 @@ mod tests { route.paths[1][0].fee_msat = 50_000_000; router.expect_find_route(Ok(route.clone())); - let event_handler = |_: &_| { panic!(); }; + let event_handler = |_: Event| { panic!(); }; let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1)); assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch( @@ -2322,7 +2352,7 @@ mod tests { route.paths[1][0].fee_msat = 50_000_001; router.expect_find_route(Ok(route.clone())); - let event_handler = |_: &_| { panic!(); }; + let event_handler = |_: Event| { panic!(); }; let invoice_payer = InvoicePayer::new(nodes[0].node, router, nodes[0].logger, event_handler, Retry::Attempts(1)); assert!(invoice_payer.pay_invoice(&create_invoice_from_channelmanager_and_duration_since_epoch( @@ -2399,8 +2429,8 @@ mod tests { route.paths.remove(1); router.expect_find_route(Ok(route.clone())); - let expected_events: RefCell> = RefCell::new(VecDeque::new()); - let event_handler = |event: &Event| { + let expected_events: RefCell> = RefCell::new(VecDeque::new()); + let event_handler = |event: Event| { let event_checker = expected_events.borrow_mut().pop_front().unwrap(); event_checker(event); }; @@ -2475,7 +2505,7 @@ mod tests { // `PaymentPathFailed` being passed up to the user (us, in this case). Previously, we'd // treated this as "HTLC complete" and dropped the retry counter, causing us to retry again // if the final HTLC failed. - expected_events.borrow_mut().push_back(&|ev: &Event| { + expected_events.borrow_mut().push_back(&|ev: Event| { if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev { assert!(!payment_failed_permanently); assert!(all_paths_failed); @@ -2493,13 +2523,13 @@ mod tests { nodes[0].node.handle_update_fail_htlc(&nodes[1].node.get_our_node_id(), &bs_fail_update.update_fail_htlcs[0]); commitment_signed_dance!(nodes[0], nodes[1], &bs_fail_update.commitment_signed, false, true); - expected_events.borrow_mut().push_back(&|ev: &Event| { + expected_events.borrow_mut().push_back(&|ev: Event| { if let Event::PaymentPathFailed { payment_failed_permanently, all_paths_failed, .. } = ev { assert!(!payment_failed_permanently); assert!(all_paths_failed); } else { panic!("Unexpected event"); } }); - expected_events.borrow_mut().push_back(&|ev: &Event| { + expected_events.borrow_mut().push_back(&|ev: Event| { if let Event::PaymentFailed { .. } = ev { } else { panic!("Unexpected event"); } });