1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Utilities to send payments and manage outbound payment information.
12 use bitcoin::hashes::Hash;
13 use bitcoin::hashes::sha256::Hash as Sha256;
14 use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
16 use crate::chain::keysinterface::{EntropySource, NodeSigner, Recipient};
17 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
18 use crate::ln::channelmanager::{ChannelDetails, HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, MIN_HTLC_RELAY_HOLDING_CELL_MILLIS, PaymentId};
19 use crate::ln::msgs::DecodeError;
20 use crate::ln::onion_utils::HTLCFailReason;
21 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, RoutePath, Router};
22 use crate::util::errors::APIError;
23 use crate::util::events;
24 use crate::util::logger::Logger;
25 use crate::util::time::Time;
26 #[cfg(all(not(feature = "no-std"), test))]
27 use crate::util::time::tests::SinceEpoch;
30 use core::fmt::{self, Display, Formatter};
32 use core::time::Duration;
34 use crate::prelude::*;
35 use crate::sync::Mutex;
37 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
38 /// and later, also stores information for retrying the payment.
39 pub(crate) enum PendingOutboundPayment {
41 session_privs: HashSet<[u8; 32]>,
44 retry_strategy: Option<Retry>,
45 attempts: PaymentAttempts,
46 route_params: Option<RouteParameters>,
47 session_privs: HashSet<[u8; 32]>,
48 payment_hash: PaymentHash,
49 payment_secret: Option<PaymentSecret>,
50 pending_amt_msat: u64,
51 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
52 pending_fee_msat: Option<u64>,
53 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
55 /// Our best known block height at the time this payment was initiated.
56 starting_block_height: u32,
58 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
59 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
60 /// and add a pending payment that was already fulfilled.
62 session_privs: HashSet<[u8; 32]>,
63 payment_hash: Option<PaymentHash>,
64 timer_ticks_without_htlcs: u8,
66 /// When a payer gives up trying to retry a payment, they inform us, letting us generate a
67 /// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
68 /// conditions in MPP-aware payment retriers (1), where the possibility of multiple
69 /// `PaymentPathFailed` events with `all_paths_failed` can be pending at once, confusing a
70 /// downstream event handler as to when a payment has actually failed.
72 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
74 session_privs: HashSet<[u8; 32]>,
75 payment_hash: PaymentHash,
79 impl PendingOutboundPayment {
80 fn increment_attempts(&mut self) {
81 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
85 fn is_auto_retryable_now(&self) -> bool {
87 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
88 strategy.is_retryable_now(&attempts)
93 fn is_retryable_now(&self) -> bool {
95 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
96 // We're handling retries manually, we can always retry.
99 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
100 strategy.is_retryable_now(&attempts)
105 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
106 if let PendingOutboundPayment::Retryable { route_params: Some(params), .. } = self {
107 params.payment_params.previously_failed_channels.push(scid);
110 pub(super) fn is_fulfilled(&self) -> bool {
112 PendingOutboundPayment::Fulfilled { .. } => true,
116 pub(super) fn abandoned(&self) -> bool {
118 PendingOutboundPayment::Abandoned { .. } => true,
122 fn get_pending_fee_msat(&self) -> Option<u64> {
124 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
129 fn payment_hash(&self) -> Option<PaymentHash> {
131 PendingOutboundPayment::Legacy { .. } => None,
132 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
133 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
134 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
138 fn mark_fulfilled(&mut self) {
139 let mut session_privs = HashSet::new();
140 core::mem::swap(&mut session_privs, match self {
141 PendingOutboundPayment::Legacy { session_privs } |
142 PendingOutboundPayment::Retryable { session_privs, .. } |
143 PendingOutboundPayment::Fulfilled { session_privs, .. } |
144 PendingOutboundPayment::Abandoned { session_privs, .. }
147 let payment_hash = self.payment_hash();
148 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
151 fn mark_abandoned(&mut self) -> Result<(), ()> {
152 let mut session_privs = HashSet::new();
153 let our_payment_hash;
154 core::mem::swap(&mut session_privs, match self {
155 PendingOutboundPayment::Legacy { .. } |
156 PendingOutboundPayment::Fulfilled { .. } =>
158 PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } |
159 PendingOutboundPayment::Abandoned { session_privs, payment_hash, .. } => {
160 our_payment_hash = *payment_hash;
164 *self = PendingOutboundPayment::Abandoned { session_privs, payment_hash: our_payment_hash };
168 /// panics if path is None and !self.is_fulfilled
169 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
170 let remove_res = match self {
171 PendingOutboundPayment::Legacy { session_privs } |
172 PendingOutboundPayment::Retryable { session_privs, .. } |
173 PendingOutboundPayment::Fulfilled { session_privs, .. } |
174 PendingOutboundPayment::Abandoned { session_privs, .. } => {
175 session_privs.remove(session_priv)
179 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
180 let path = path.expect("Fulfilling a payment should always come with a path");
181 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
182 *pending_amt_msat -= path_last_hop.fee_msat;
183 if let Some(fee_msat) = pending_fee_msat.as_mut() {
184 *fee_msat -= path.get_path_fees();
191 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
192 let insert_res = match self {
193 PendingOutboundPayment::Legacy { session_privs } |
194 PendingOutboundPayment::Retryable { session_privs, .. } => {
195 session_privs.insert(session_priv)
197 PendingOutboundPayment::Fulfilled { .. } => false,
198 PendingOutboundPayment::Abandoned { .. } => false,
201 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
202 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
203 *pending_amt_msat += path_last_hop.fee_msat;
204 if let Some(fee_msat) = pending_fee_msat.as_mut() {
205 *fee_msat += path.get_path_fees();
212 pub(super) fn remaining_parts(&self) -> usize {
214 PendingOutboundPayment::Legacy { session_privs } |
215 PendingOutboundPayment::Retryable { session_privs, .. } |
216 PendingOutboundPayment::Fulfilled { session_privs, .. } |
217 PendingOutboundPayment::Abandoned { session_privs, .. } => {
224 /// Strategies available to retry payment path failures.
225 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
227 /// Max number of attempts to retry payment.
229 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
230 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
231 /// were retried along a route from a single call to [`Router::find_route`].
233 #[cfg(not(feature = "no-std"))]
234 /// Time elapsed before abandoning retries for a payment.
235 Timeout(core::time::Duration),
239 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
240 match (self, attempts) {
241 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
242 max_retry_count > count
244 #[cfg(all(not(feature = "no-std"), not(test)))]
245 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
246 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
247 #[cfg(all(not(feature = "no-std"), test))]
248 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
249 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
254 #[cfg(feature = "std")]
255 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
256 if let Some(expiry_time) = route_params.payment_params.expiry_time {
257 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
258 return elapsed > core::time::Duration::from_secs(expiry_time)
264 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
266 /// Storing minimal payment attempts information required for determining if a outbound payment can
268 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
269 /// This count will be incremented only after the result of the attempt is known. When it's 0,
270 /// it means the result of the first attempt is not known yet.
271 pub(crate) count: usize,
272 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
273 first_attempted_at: T
276 #[cfg(not(any(feature = "no-std", test)))]
277 type ConfiguredTime = std::time::Instant;
278 #[cfg(feature = "no-std")]
279 type ConfiguredTime = crate::util::time::Eternity;
280 #[cfg(all(not(feature = "no-std"), test))]
281 type ConfiguredTime = SinceEpoch;
283 impl<T: Time> PaymentAttemptsUsingTime<T> {
284 pub(crate) fn new() -> Self {
285 PaymentAttemptsUsingTime {
287 first_attempted_at: T::now()
292 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
293 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
294 #[cfg(feature = "no-std")]
295 return write!(f, "attempts: {}", self.count);
296 #[cfg(not(feature = "no-std"))]
299 "attempts: {}, duration: {}s",
301 T::now().duration_since(self.first_attempted_at).as_secs()
306 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
307 /// Err() type describing which state the payment is in, see the description of individual enum
309 #[derive(Clone, Debug)]
310 pub enum PaymentSendFailure {
311 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
312 /// send the payment at all.
314 /// You can freely resend the payment in full (with the parameter error fixed).
316 /// Because the payment failed outright, no payment tracking is done, you do not need to call
317 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
318 /// for this payment.
320 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
321 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
322 ParameterError(APIError),
323 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
324 /// from attempting to send the payment at all.
326 /// You can freely resend the payment in full (with the parameter error fixed).
328 /// The results here are ordered the same as the paths in the route object which was passed to
331 /// Because the payment failed outright, no payment tracking is done, you do not need to call
332 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
333 /// for this payment.
335 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
336 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
337 PathParameterError(Vec<Result<(), APIError>>),
338 /// All paths which were attempted failed to send, with no channel state change taking place.
339 /// You can freely resend the payment in full (though you probably want to do so over different
340 /// paths than the ones selected).
342 /// Because the payment failed outright, no payment tracking is done, you do not need to call
343 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
344 /// for this payment.
346 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
347 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
348 AllFailedResendSafe(Vec<APIError>),
349 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
350 /// yet completed (i.e. generated an [`Event::PaymentSent`]) or been abandoned (via
351 /// [`ChannelManager::abandon_payment`]).
353 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
354 /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
355 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
357 /// Some paths which were attempted failed to send, though possibly not all. At least some
358 /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
359 /// in over-/re-payment.
361 /// The results here are ordered the same as the paths in the route object which was passed to
362 /// send_payment, and any `Err`s which are not [`APIError::MonitorUpdateInProgress`] can be
363 /// safely retried via [`ChannelManager::retry_payment`].
365 /// Any entries which contain `Err(APIError::MonitorUpdateInprogress)` or `Ok(())` MUST NOT be
366 /// retried as they will result in over-/re-payment. These HTLCs all either successfully sent
367 /// (in the case of `Ok(())`) or will send once a [`MonitorEvent::Completed`] is provided for
368 /// the next-hop channel with the latest update_id.
370 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
371 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
373 /// The errors themselves, in the same order as the route hops.
374 results: Vec<Result<(), APIError>>,
375 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
376 /// contain a [`RouteParameters`] object which can be used to calculate a new route that
377 /// will pay all remaining unpaid balance.
378 failed_paths_retry: Option<RouteParameters>,
379 /// The payment id for the payment, which is now at least partially pending.
380 payment_id: PaymentId,
384 pub(super) struct OutboundPayments {
385 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
388 impl OutboundPayments {
389 pub(super) fn new() -> Self {
391 pending_outbound_payments: Mutex::new(HashMap::new())
395 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, F, L: Deref>(
396 &self, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId,
397 retry_strategy: Retry, route_params: RouteParameters, router: &R,
398 first_hops: Vec<ChannelDetails>, inflight_htlcs: InFlightHtlcs, entropy_source: &ES,
399 node_signer: &NS, best_block_height: u32, logger: &L, send_payment_along_path: F,
400 ) -> Result<(), PaymentSendFailure>
403 ES::Target: EntropySource,
404 NS::Target: NodeSigner,
406 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
407 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
409 self.pay_internal(payment_id, Some((payment_hash, payment_secret, retry_strategy)),
410 route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer,
411 best_block_height, logger, &send_payment_along_path)
412 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
415 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
416 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
417 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
418 send_payment_along_path: F
419 ) -> Result<(), PaymentSendFailure>
421 ES::Target: EntropySource,
422 NS::Target: NodeSigner,
423 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
424 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
426 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, route, None, None, entropy_source, best_block_height)?;
427 self.pay_route_internal(route, payment_hash, payment_secret, None, payment_id, None,
428 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
429 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
432 pub(super) fn send_spontaneous_payment<ES: Deref, NS: Deref, F>(
433 &self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
434 entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F
435 ) -> Result<PaymentHash, PaymentSendFailure>
437 ES::Target: EntropySource,
438 NS::Target: NodeSigner,
439 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
440 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
442 let preimage = match payment_preimage {
444 None => PaymentPreimage(entropy_source.get_secure_random_bytes()),
446 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
447 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, None, None, entropy_source, best_block_height)?;
449 match self.pay_route_internal(route, payment_hash, &None, Some(preimage), payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path) {
450 Ok(()) => Ok(payment_hash),
452 self.remove_outbound_if_all_failed(payment_id, &e);
458 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
459 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
460 best_block_height: u32, logger: &L, send_payment_along_path: SP,
464 ES::Target: EntropySource,
465 NS::Target: NodeSigner,
466 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
467 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
468 IH: Fn() -> InFlightHtlcs,
469 FH: Fn() -> Vec<ChannelDetails>,
473 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
474 let mut retry_id_route_params = None;
475 for (pmt_id, pmt) in outbounds.iter_mut() {
476 if pmt.is_auto_retryable_now() {
477 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, route_params: Some(params), .. } = pmt {
478 if pending_amt_msat < total_msat {
479 retry_id_route_params = Some((*pmt_id, params.clone()));
485 if let Some((payment_id, route_params)) = retry_id_route_params {
486 core::mem::drop(outbounds);
487 if let Err(e) = self.pay_internal(payment_id, None, route_params, router, first_hops(), inflight_htlcs(), entropy_source, node_signer, best_block_height, logger, &send_payment_along_path) {
488 log_info!(logger, "Errored retrying payment: {:?}", e);
494 fn pay_internal<R: Deref, NS: Deref, ES: Deref, F, L: Deref>(
495 &self, payment_id: PaymentId,
496 initial_send_info: Option<(PaymentHash, &Option<PaymentSecret>, Retry)>,
497 route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
498 inflight_htlcs: InFlightHtlcs, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
499 logger: &L, send_payment_along_path: &F,
500 ) -> Result<(), PaymentSendFailure>
503 ES::Target: EntropySource,
504 NS::Target: NodeSigner,
506 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
507 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
509 #[cfg(feature = "std")] {
510 if has_expired(&route_params) {
511 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
512 err: format!("Invoice expired for payment id {}", log_bytes!(payment_id.0)),
517 let route = router.find_route(
518 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
519 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
520 ).map_err(|e| PaymentSendFailure::ParameterError(APIError::APIMisuseError {
521 err: format!("Failed to find a route for payment {}: {:?}", log_bytes!(payment_id.0), e), // TODO: add APIError::RouteNotFound
524 let res = if let Some((payment_hash, payment_secret, retry_strategy)) = initial_send_info {
525 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, &route, Some(retry_strategy), Some(route_params.clone()), entropy_source, best_block_height)?;
526 self.pay_route_internal(&route, payment_hash, payment_secret, None, payment_id, None, onion_session_privs, node_signer, best_block_height, send_payment_along_path)
528 self.retry_payment_with_route(&route, payment_id, entropy_source, node_signer, best_block_height, send_payment_along_path)
531 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
532 let retry_res = self.pay_internal(payment_id, None, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, send_payment_along_path);
533 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
534 if let Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError { err })) = &retry_res {
535 if err.starts_with("Retries exhausted ") { return res; }
539 Err(PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), .. }) => {
540 // Some paths were sent, even if we failed to send the full MPP value our recipient may
541 // misbehave and claim the funds, at which point we have to consider the payment sent, so
542 // return `Ok()` here, ignoring any retry errors.
543 let retry_res = self.pay_internal(payment_id, None, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, send_payment_along_path);
544 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), retry_res);
547 Err(PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. }) => {
548 // This may happen if we send a payment and some paths fail, but only due to a temporary
549 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
550 // initial HTLC-Add messages yet.
557 pub(super) fn retry_payment_with_route<ES: Deref, NS: Deref, F>(
558 &self, route: &Route, payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
559 send_payment_along_path: F
560 ) -> Result<(), PaymentSendFailure>
562 ES::Target: EntropySource,
563 NS::Target: NodeSigner,
564 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
565 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
567 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
568 for path in route.paths.iter() {
570 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
571 err: "length-0 path in route".to_string()
576 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
577 for _ in 0..route.paths.len() {
578 onion_session_privs.push(entropy_source.get_secure_random_bytes());
581 let (total_msat, payment_hash, payment_secret) = {
582 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
583 match outbounds.get_mut(&payment_id) {
585 let res = match payment {
586 PendingOutboundPayment::Retryable {
587 total_msat, payment_hash, payment_secret, pending_amt_msat, ..
589 let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
590 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
591 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
592 err: format!("retry_amt_msat of {} will put pending_amt_msat (currently: {}) more than 10% over total_payment_amt_msat of {}", retry_amt_msat, pending_amt_msat, total_msat).to_string()
595 (*total_msat, *payment_hash, *payment_secret)
597 PendingOutboundPayment::Legacy { .. } => {
598 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
599 err: "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102".to_string()
602 PendingOutboundPayment::Fulfilled { .. } => {
603 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
604 err: "Payment already completed".to_owned()
607 PendingOutboundPayment::Abandoned { .. } => {
608 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
609 err: "Payment already abandoned (with some HTLCs still pending)".to_owned()
613 if !payment.is_retryable_now() {
614 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
615 err: format!("Retries exhausted for payment id {}", log_bytes!(payment_id.0)),
618 payment.increment_attempts();
619 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
620 assert!(payment.insert(*session_priv_bytes, path));
625 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
626 err: format!("Payment with ID {} not found", log_bytes!(payment_id.0)),
630 self.pay_route_internal(route, payment_hash, &payment_secret, None, payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
633 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
634 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
635 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
636 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
638 ES::Target: EntropySource,
639 NS::Target: NodeSigner,
640 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
641 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
643 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
645 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
648 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
649 err: "No need probing a path with less than two hops".to_string()
653 let route = Route { paths: vec![hops], payment_params: None };
654 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, None, None, entropy_source, best_block_height)?;
656 match self.pay_route_internal(&route, payment_hash, &None, None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path) {
657 Ok(()) => Ok((payment_hash, payment_id)),
659 self.remove_outbound_if_all_failed(payment_id, &e);
666 pub(super) fn test_add_new_pending_payment<ES: Deref>(
667 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
668 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
669 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
670 self.add_new_pending_payment(payment_hash, payment_secret, payment_id, route, retry_strategy, None, entropy_source, best_block_height)
673 pub(super) fn add_new_pending_payment<ES: Deref>(
674 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
675 route: &Route, retry_strategy: Option<Retry>, route_params: Option<RouteParameters>,
676 entropy_source: &ES, best_block_height: u32
677 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
678 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
679 for _ in 0..route.paths.len() {
680 onion_session_privs.push(entropy_source.get_secure_random_bytes());
683 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
684 match pending_outbounds.entry(payment_id) {
685 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
686 hash_map::Entry::Vacant(entry) => {
687 let payment = entry.insert(PendingOutboundPayment::Retryable {
689 attempts: PaymentAttempts::new(),
691 session_privs: HashSet::new(),
693 pending_fee_msat: Some(0),
696 starting_block_height: best_block_height,
697 total_msat: route.get_total_amount(),
700 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
701 assert!(payment.insert(*session_priv_bytes, path));
704 Ok(onion_session_privs)
709 fn pay_route_internal<NS: Deref, F>(
710 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
711 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
712 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
713 send_payment_along_path: &F
714 ) -> Result<(), PaymentSendFailure>
716 NS::Target: NodeSigner,
717 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
718 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
720 if route.paths.len() < 1 {
721 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over"}));
723 if payment_secret.is_none() && route.paths.len() > 1 {
724 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_string()}));
726 let mut total_value = 0;
727 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
728 let mut path_errs = Vec::with_capacity(route.paths.len());
729 'path_check: for path in route.paths.iter() {
730 if path.len() < 1 || path.len() > 20 {
731 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size"}));
732 continue 'path_check;
734 for (idx, hop) in path.iter().enumerate() {
735 if idx != path.len() - 1 && hop.pubkey == our_node_id {
736 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us"}));
737 continue 'path_check;
740 total_value += path.last().unwrap().fee_msat;
741 path_errs.push(Ok(()));
743 if path_errs.iter().any(|e| e.is_err()) {
744 return Err(PaymentSendFailure::PathParameterError(path_errs));
746 if let Some(amt_msat) = recv_value_msat {
747 debug_assert!(amt_msat >= total_value);
748 total_value = amt_msat;
751 let cur_height = best_block_height + 1;
752 let mut results = Vec::new();
753 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
754 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
755 let mut path_res = send_payment_along_path(&path, &route.payment_params, &payment_hash, payment_secret, total_value, cur_height, payment_id, &keysend_preimage, session_priv);
758 Err(APIError::MonitorUpdateInProgress) => {
759 // While a MonitorUpdateInProgress is an Err(_), the payment is still
760 // considered "in flight" and we shouldn't remove it from the
761 // PendingOutboundPayment set.
764 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
765 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
766 let removed = payment.remove(&session_priv, Some(path));
767 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
769 debug_assert!(false, "This can't happen as the payment was added by callers");
770 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
774 results.push(path_res);
776 let mut has_ok = false;
777 let mut has_err = false;
778 let mut pending_amt_unsent = 0;
779 let mut max_unsent_cltv_delta = 0;
780 for (res, path) in results.iter().zip(route.paths.iter()) {
781 if res.is_ok() { has_ok = true; }
782 if res.is_err() { has_err = true; }
783 if let &Err(APIError::MonitorUpdateInProgress) = res {
784 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
788 } else if res.is_err() {
789 pending_amt_unsent += path.last().unwrap().fee_msat;
790 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
793 if has_err && has_ok {
794 Err(PaymentSendFailure::PartialFailure {
797 failed_paths_retry: if pending_amt_unsent != 0 {
798 if let Some(payment_params) = &route.payment_params {
799 Some(RouteParameters {
800 payment_params: payment_params.clone(),
801 final_value_msat: pending_amt_unsent,
802 final_cltv_expiry_delta:
803 if let Some(delta) = payment_params.final_cltv_expiry_delta { delta }
804 else { max_unsent_cltv_delta },
810 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
817 pub(super) fn test_send_payment_internal<NS: Deref, F>(
818 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
819 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
820 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
821 send_payment_along_path: F
822 ) -> Result<(), PaymentSendFailure>
824 NS::Target: NodeSigner,
825 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
826 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
828 self.pay_route_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id,
829 recv_value_msat, onion_session_privs, node_signer, best_block_height,
830 &send_payment_along_path)
831 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
834 // If we failed to send any paths, we should remove the new PaymentId from the
835 // `pending_outbound_payments` map, as the user isn't expected to `abandon_payment`.
836 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
837 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
838 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
839 debug_assert!(removed, "We should always have a pending payment to remove here");
843 pub(super) fn claim_htlc<L: Deref>(
844 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
845 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
846 ) where L::Target: Logger {
847 let mut session_priv_bytes = [0; 32];
848 session_priv_bytes.copy_from_slice(&session_priv[..]);
849 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
850 let mut pending_events = pending_events.lock().unwrap();
851 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
852 if !payment.get().is_fulfilled() {
853 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
854 let fee_paid_msat = payment.get().get_pending_fee_msat();
856 events::Event::PaymentSent {
857 payment_id: Some(payment_id),
863 payment.get_mut().mark_fulfilled();
867 // We currently immediately remove HTLCs which were fulfilled on-chain.
868 // This could potentially lead to removing a pending payment too early,
869 // with a reorg of one block causing us to re-add the fulfilled payment on
871 // TODO: We should have a second monitor event that informs us of payments
872 // irrevocably fulfilled.
873 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
874 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
876 events::Event::PaymentPathSuccessful {
885 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
889 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
890 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
891 let mut pending_events = pending_events.lock().unwrap();
892 for source in sources {
893 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
894 let mut session_priv_bytes = [0; 32];
895 session_priv_bytes.copy_from_slice(&session_priv[..]);
896 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
897 assert!(payment.get().is_fulfilled());
898 if payment.get_mut().remove(&session_priv_bytes, None) {
900 events::Event::PaymentPathSuccessful {
902 payment_hash: payment.get().payment_hash(),
912 pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
913 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
914 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
915 // this could race the user making a duplicate send_payment call and our idempotency
916 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
917 // removal. This should be more than sufficient to ensure the idempotency of any
918 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
920 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
921 let pending_events = pending_events.lock().unwrap();
922 pending_outbound_payments.retain(|payment_id, payment| {
923 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
924 let mut no_remaining_entries = session_privs.is_empty();
925 if no_remaining_entries {
926 for ev in pending_events.iter() {
928 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
929 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
930 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
931 if payment_id == ev_payment_id {
932 no_remaining_entries = false;
940 if no_remaining_entries {
941 *timer_ticks_without_htlcs += 1;
942 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
944 *timer_ticks_without_htlcs = 0;
951 pub(super) fn fail_htlc<L: Deref>(
952 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
953 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
954 payment_params: &Option<PaymentParameters>, probing_cookie_secret: [u8; 32],
955 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
956 ) where L::Target: Logger {
958 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
960 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
962 let mut session_priv_bytes = [0; 32];
963 session_priv_bytes.copy_from_slice(&session_priv[..]);
964 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
965 let mut all_paths_failed = false;
966 let mut full_failure_ev = None;
967 let mut pending_retry_ev = None;
968 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
969 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
970 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
973 if payment.get().is_fulfilled() {
974 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
977 let is_retryable_now = payment.get().is_auto_retryable_now();
978 if let Some(scid) = short_channel_id {
979 payment.get_mut().insert_previously_failed_scid(scid);
981 if payment.get().remaining_parts() == 0 {
982 all_paths_failed = true;
983 if payment.get().abandoned() {
984 full_failure_ev = Some(events::Event::PaymentFailed {
985 payment_id: *payment_id,
986 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
993 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
996 core::mem::drop(outbounds);
997 let mut retry = if let Some(payment_params_data) = payment_params {
998 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
999 Some(RouteParameters {
1000 payment_params: payment_params_data.clone(),
1001 final_value_msat: path_last_hop.fee_msat,
1002 final_cltv_expiry_delta:
1003 if let Some(delta) = payment_params_data.final_cltv_expiry_delta { delta }
1004 else { path_last_hop.cltv_expiry_delta },
1007 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1009 let path_failure = {
1010 if payment_is_probe(payment_hash, &payment_id, probing_cookie_secret) {
1011 if !payment_retryable {
1012 events::Event::ProbeSuccessful {
1013 payment_id: *payment_id,
1014 payment_hash: payment_hash.clone(),
1018 events::Event::ProbeFailed {
1019 payment_id: *payment_id,
1020 payment_hash: payment_hash.clone(),
1026 // TODO: If we decided to blame ourselves (or one of our channels) in
1027 // process_onion_failure we should close that channel as it implies our
1028 // next-hop is needlessly blaming us!
1029 if let Some(scid) = short_channel_id {
1030 retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
1032 if payment_retryable && attempts_remaining && retry.is_some() {
1033 debug_assert!(full_failure_ev.is_none());
1034 pending_retry_ev = Some(events::Event::PendingHTLCsForwardable {
1035 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
1038 events::Event::PaymentPathFailed {
1039 payment_id: Some(*payment_id),
1040 payment_hash: payment_hash.clone(),
1041 payment_failed_permanently: !payment_retryable,
1048 error_code: onion_error_code,
1050 error_data: onion_error_data
1054 let mut pending_events = pending_events.lock().unwrap();
1055 pending_events.push(path_failure);
1056 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1057 if let Some(ev) = pending_retry_ev { pending_events.push(ev); }
1060 pub(super) fn abandon_payment(&self, payment_id: PaymentId) -> Option<events::Event> {
1061 let mut failed_ev = None;
1062 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1063 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1064 if let Ok(()) = payment.get_mut().mark_abandoned() {
1065 if payment.get().remaining_parts() == 0 {
1066 failed_ev = Some(events::Event::PaymentFailed {
1068 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1078 pub fn has_pending_payments(&self) -> bool {
1079 !self.pending_outbound_payments.lock().unwrap().is_empty()
1083 pub fn clear_pending_payments(&self) {
1084 self.pending_outbound_payments.lock().unwrap().clear()
1088 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1090 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1091 probing_cookie_secret: [u8; 32]) -> bool
1093 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1094 target_payment_hash == *payment_hash
1097 /// Returns the 'probing cookie' for the given [`PaymentId`].
1098 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1099 let mut preimage = [0u8; 64];
1100 preimage[..32].copy_from_slice(&probing_cookie_secret);
1101 preimage[32..].copy_from_slice(&payment_id.0);
1102 PaymentHash(Sha256::hash(&preimage).into_inner())
1105 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1107 (0, session_privs, required),
1110 (0, session_privs, required),
1111 (1, payment_hash, option),
1112 (3, timer_ticks_without_htlcs, (default_value, 0)),
1115 (0, session_privs, required),
1116 (1, pending_fee_msat, option),
1117 (2, payment_hash, required),
1118 (not_written, retry_strategy, (static_value, None)),
1119 (4, payment_secret, option),
1120 (not_written, attempts, (static_value, PaymentAttempts::new())),
1121 (6, total_msat, required),
1122 (not_written, route_params, (static_value, None)),
1123 (8, pending_amt_msat, required),
1124 (10, starting_block_height, required),
1127 (0, session_privs, required),
1128 (2, payment_hash, required),
1134 use bitcoin::blockdata::constants::genesis_block;
1135 use bitcoin::network::constants::Network;
1136 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1138 use crate::ln::PaymentHash;
1139 use crate::ln::channelmanager::{PaymentId, PaymentSendFailure};
1140 use crate::ln::msgs::{ErrorAction, LightningError};
1141 use crate::ln::outbound_payment::{OutboundPayments, Retry};
1142 use crate::routing::gossip::NetworkGraph;
1143 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteParameters};
1144 use crate::sync::Arc;
1145 use crate::util::errors::APIError;
1146 use crate::util::test_utils;
1149 #[cfg(feature = "std")]
1150 fn fails_paying_after_expiration() {
1151 do_fails_paying_after_expiration(false);
1152 do_fails_paying_after_expiration(true);
1154 #[cfg(feature = "std")]
1155 fn do_fails_paying_after_expiration(on_retry: bool) {
1156 let outbound_payments = OutboundPayments::new();
1157 let logger = test_utils::TestLogger::new();
1158 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1159 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1160 let router = test_utils::TestRouter::new(network_graph);
1161 let secp_ctx = Secp256k1::new();
1162 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1164 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1165 let payment_params = PaymentParameters::from_node_id(
1166 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1168 ).with_expiry_time(past_expiry_time);
1169 let expired_route_params = RouteParameters {
1171 final_value_msat: 0,
1172 final_cltv_expiry_delta: 0,
1174 let err = if on_retry {
1175 outbound_payments.pay_internal(
1176 PaymentId([0; 32]), None, expired_route_params, &&router, vec![], InFlightHtlcs::new(),
1177 &&keys_manager, &&keys_manager, 0, &&logger, &|_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1179 outbound_payments.send_payment(
1180 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), expired_route_params,
1181 &&router, vec![], InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1182 |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1184 if let PaymentSendFailure::ParameterError(APIError::APIMisuseError { err }) = err {
1185 assert!(err.contains("Invoice expired"));
1186 } else { panic!("Unexpected error"); }
1190 fn find_route_error() {
1191 do_find_route_error(false);
1192 do_find_route_error(true);
1194 fn do_find_route_error(on_retry: bool) {
1195 let outbound_payments = OutboundPayments::new();
1196 let logger = test_utils::TestLogger::new();
1197 let genesis_hash = genesis_block(Network::Testnet).header.block_hash();
1198 let network_graph = Arc::new(NetworkGraph::new(genesis_hash, &logger));
1199 let router = test_utils::TestRouter::new(network_graph);
1200 let secp_ctx = Secp256k1::new();
1201 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1203 let payment_params = PaymentParameters::from_node_id(
1204 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1205 let route_params = RouteParameters {
1207 final_value_msat: 0,
1208 final_cltv_expiry_delta: 0,
1210 router.expect_find_route(route_params.clone(),
1211 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1213 let err = if on_retry {
1214 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), None, PaymentId([0; 32]),
1215 &Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)), Some(route_params.clone()),
1216 &&keys_manager, 0).unwrap();
1217 outbound_payments.pay_internal(
1218 PaymentId([0; 32]), None, route_params, &&router, vec![], InFlightHtlcs::new(),
1219 &&keys_manager, &&keys_manager, 0, &&logger, &|_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1221 outbound_payments.send_payment(
1222 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params,
1223 &&router, vec![], InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1224 |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err()
1226 if let PaymentSendFailure::ParameterError(APIError::APIMisuseError { err }) = err {
1227 assert!(err.contains("Failed to find a route"));
1228 } else { panic!("Unexpected error"); }