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, PaymentId};
19 use crate::ln::onion_utils::HTLCFailReason;
20 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, RoutePath, Router};
21 use crate::util::errors::APIError;
22 use crate::util::events;
23 use crate::util::logger::Logger;
24 use crate::util::time::Time;
25 #[cfg(all(not(feature = "no-std"), test))]
26 use crate::util::time::tests::SinceEpoch;
27 use crate::util::ser::ReadableArgs;
30 use core::fmt::{self, Display, Formatter};
33 use crate::prelude::*;
34 use crate::sync::Mutex;
36 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
37 /// and later, also stores information for retrying the payment.
38 pub(crate) enum PendingOutboundPayment {
40 session_privs: HashSet<[u8; 32]>,
43 retry_strategy: Option<Retry>,
44 attempts: PaymentAttempts,
45 payment_params: Option<PaymentParameters>,
46 session_privs: HashSet<[u8; 32]>,
47 payment_hash: PaymentHash,
48 payment_secret: Option<PaymentSecret>,
49 keysend_preimage: Option<PaymentPreimage>,
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 we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
67 /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
69 session_privs: HashSet<[u8; 32]>,
70 payment_hash: PaymentHash,
74 impl PendingOutboundPayment {
75 fn increment_attempts(&mut self) {
76 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
80 fn is_auto_retryable_now(&self) -> bool {
82 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
83 strategy.is_retryable_now(&attempts)
88 fn is_retryable_now(&self) -> bool {
90 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
91 // We're handling retries manually, we can always retry.
94 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
95 strategy.is_retryable_now(&attempts)
100 fn payment_parameters(&mut self) -> Option<&mut PaymentParameters> {
102 PendingOutboundPayment::Retryable { payment_params: Some(ref mut params), .. } => {
108 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
109 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
110 params.previously_failed_channels.push(scid);
113 pub(super) fn is_fulfilled(&self) -> bool {
115 PendingOutboundPayment::Fulfilled { .. } => true,
119 pub(super) fn abandoned(&self) -> bool {
121 PendingOutboundPayment::Abandoned { .. } => true,
125 fn get_pending_fee_msat(&self) -> Option<u64> {
127 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
132 fn payment_hash(&self) -> Option<PaymentHash> {
134 PendingOutboundPayment::Legacy { .. } => None,
135 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
136 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
137 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
141 fn mark_fulfilled(&mut self) {
142 let mut session_privs = HashSet::new();
143 core::mem::swap(&mut session_privs, match self {
144 PendingOutboundPayment::Legacy { session_privs } |
145 PendingOutboundPayment::Retryable { session_privs, .. } |
146 PendingOutboundPayment::Fulfilled { session_privs, .. } |
147 PendingOutboundPayment::Abandoned { session_privs, .. }
150 let payment_hash = self.payment_hash();
151 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
154 fn mark_abandoned(&mut self) -> Result<(), ()> {
155 let mut session_privs = HashSet::new();
156 let our_payment_hash;
157 core::mem::swap(&mut session_privs, match self {
158 PendingOutboundPayment::Legacy { .. } |
159 PendingOutboundPayment::Fulfilled { .. } =>
161 PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } |
162 PendingOutboundPayment::Abandoned { session_privs, payment_hash, .. } => {
163 our_payment_hash = *payment_hash;
167 *self = PendingOutboundPayment::Abandoned { session_privs, payment_hash: our_payment_hash };
171 /// panics if path is None and !self.is_fulfilled
172 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
173 let remove_res = match self {
174 PendingOutboundPayment::Legacy { session_privs } |
175 PendingOutboundPayment::Retryable { session_privs, .. } |
176 PendingOutboundPayment::Fulfilled { session_privs, .. } |
177 PendingOutboundPayment::Abandoned { session_privs, .. } => {
178 session_privs.remove(session_priv)
182 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
183 let path = path.expect("Fulfilling a payment should always come with a path");
184 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
185 *pending_amt_msat -= path_last_hop.fee_msat;
186 if let Some(fee_msat) = pending_fee_msat.as_mut() {
187 *fee_msat -= path.get_path_fees();
194 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
195 let insert_res = match self {
196 PendingOutboundPayment::Legacy { session_privs } |
197 PendingOutboundPayment::Retryable { session_privs, .. } => {
198 session_privs.insert(session_priv)
200 PendingOutboundPayment::Fulfilled { .. } => false,
201 PendingOutboundPayment::Abandoned { .. } => false,
204 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
205 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
206 *pending_amt_msat += path_last_hop.fee_msat;
207 if let Some(fee_msat) = pending_fee_msat.as_mut() {
208 *fee_msat += path.get_path_fees();
215 pub(super) fn remaining_parts(&self) -> usize {
217 PendingOutboundPayment::Legacy { session_privs } |
218 PendingOutboundPayment::Retryable { session_privs, .. } |
219 PendingOutboundPayment::Fulfilled { session_privs, .. } |
220 PendingOutboundPayment::Abandoned { session_privs, .. } => {
227 /// Strategies available to retry payment path failures.
228 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
230 /// Max number of attempts to retry payment.
232 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
233 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
234 /// were retried along a route from a single call to [`Router::find_route`].
236 #[cfg(not(feature = "no-std"))]
237 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
238 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
240 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
241 Timeout(core::time::Duration),
245 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
246 match (self, attempts) {
247 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
248 max_retry_count > count
250 #[cfg(all(not(feature = "no-std"), not(test)))]
251 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
252 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
253 #[cfg(all(not(feature = "no-std"), test))]
254 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
255 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
260 #[cfg(feature = "std")]
261 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
262 if let Some(expiry_time) = route_params.payment_params.expiry_time {
263 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
264 return elapsed > core::time::Duration::from_secs(expiry_time)
270 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
272 /// Storing minimal payment attempts information required for determining if a outbound payment can
274 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
275 /// This count will be incremented only after the result of the attempt is known. When it's 0,
276 /// it means the result of the first attempt is not known yet.
277 pub(crate) count: usize,
278 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
279 #[cfg(not(feature = "no-std"))]
280 first_attempted_at: T,
281 #[cfg(feature = "no-std")]
282 phantom: core::marker::PhantomData<T>,
286 #[cfg(not(any(feature = "no-std", test)))]
287 type ConfiguredTime = std::time::Instant;
288 #[cfg(feature = "no-std")]
289 type ConfiguredTime = crate::util::time::Eternity;
290 #[cfg(all(not(feature = "no-std"), test))]
291 type ConfiguredTime = SinceEpoch;
293 impl<T: Time> PaymentAttemptsUsingTime<T> {
294 pub(crate) fn new() -> Self {
295 PaymentAttemptsUsingTime {
297 #[cfg(not(feature = "no-std"))]
298 first_attempted_at: T::now(),
299 #[cfg(feature = "no-std")]
300 phantom: core::marker::PhantomData,
305 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
306 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
307 #[cfg(feature = "no-std")]
308 return write!(f, "attempts: {}", self.count);
309 #[cfg(not(feature = "no-std"))]
312 "attempts: {}, duration: {}s",
314 T::now().duration_since(self.first_attempted_at).as_secs()
319 /// Indicates an immediate error on [`ChannelManager::send_payment_with_retry`]. Further errors
320 /// may be surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
322 /// [`ChannelManager::send_payment_with_retry`]: crate::ln::channelmanager::ChannelManager::send_payment_with_retry
323 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
324 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
325 #[derive(Clone, Debug)]
326 pub enum RetryableSendFailure {
327 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
328 /// that this error is *not* caused by [`Retry::Timeout`].
330 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
332 /// We were unable to find a route to the destination.
334 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
335 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
337 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
338 /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
339 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
343 /// If a payment fails to send with [`ChannelManager::send_payment`], it can be in one of several
344 /// states. This enum is returned as the Err() type describing which state the payment is in, see
345 /// the description of individual enum states for more.
347 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
348 #[derive(Clone, Debug)]
349 pub enum PaymentSendFailure {
350 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
351 /// send the payment at all.
353 /// You can freely resend the payment in full (with the parameter error fixed).
355 /// Because the payment failed outright, no payment tracking is done and no
356 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
358 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
359 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
360 ParameterError(APIError),
361 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
362 /// from attempting to send the payment at all.
364 /// You can freely resend the payment in full (with the parameter error fixed).
366 /// Because the payment failed outright, no payment tracking is done and no
367 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
369 /// The results here are ordered the same as the paths in the route object which was passed to
372 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
373 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
374 PathParameterError(Vec<Result<(), APIError>>),
375 /// All paths which were attempted failed to send, with no channel state change taking place.
376 /// You can freely resend the payment in full (though you probably want to do so over different
377 /// paths than the ones selected).
379 /// Because the payment failed outright, no payment tracking is done and no
380 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
382 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
383 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
384 AllFailedResendSafe(Vec<APIError>),
385 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
386 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
388 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
389 /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
390 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
392 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
393 /// some paths have irrevocably committed to the HTLC.
395 /// The results here are ordered the same as the paths in the route object that was passed to
398 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
399 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
401 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
403 /// The errors themselves, in the same order as the paths from the route.
404 results: Vec<Result<(), APIError>>,
405 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
406 /// contain a [`RouteParameters`] object for the failing paths.
407 failed_paths_retry: Option<RouteParameters>,
408 /// The payment id for the payment, which is now at least partially pending.
409 payment_id: PaymentId,
413 pub(super) struct OutboundPayments {
414 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
415 pub(super) retry_lock: Mutex<()>,
418 impl OutboundPayments {
419 pub(super) fn new() -> Self {
421 pending_outbound_payments: Mutex::new(HashMap::new()),
422 retry_lock: Mutex::new(()),
426 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
427 &self, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>, payment_id: PaymentId,
428 retry_strategy: Retry, route_params: RouteParameters, router: &R,
429 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
430 node_signer: &NS, best_block_height: u32, logger: &L,
431 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP,
432 ) -> Result<(), RetryableSendFailure>
435 ES::Target: EntropySource,
436 NS::Target: NodeSigner,
438 IH: Fn() -> InFlightHtlcs,
439 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
440 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
442 self.send_payment_internal(payment_id, payment_hash, payment_secret, None, retry_strategy,
443 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
444 best_block_height, logger, pending_events, &send_payment_along_path)
447 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
448 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
449 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
450 send_payment_along_path: F
451 ) -> Result<(), PaymentSendFailure>
453 ES::Target: EntropySource,
454 NS::Target: NodeSigner,
455 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
456 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
458 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, None, route, None, None, entropy_source, best_block_height)?;
459 self.pay_route_internal(route, payment_hash, payment_secret, None, payment_id, None,
460 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
461 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
464 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
465 &self, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
466 retry_strategy: Retry, route_params: RouteParameters, router: &R,
467 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
468 node_signer: &NS, best_block_height: u32, logger: &L,
469 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP
470 ) -> Result<PaymentHash, RetryableSendFailure>
473 ES::Target: EntropySource,
474 NS::Target: NodeSigner,
476 IH: Fn() -> InFlightHtlcs,
477 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
478 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
480 let preimage = payment_preimage
481 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
482 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
483 self.send_payment_internal(payment_id, payment_hash, &None, Some(preimage), retry_strategy,
484 route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer,
485 best_block_height, logger, pending_events, send_payment_along_path)
486 .map(|()| payment_hash)
489 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
490 &self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
491 entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F
492 ) -> Result<PaymentHash, PaymentSendFailure>
494 ES::Target: EntropySource,
495 NS::Target: NodeSigner,
496 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
497 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
499 let preimage = payment_preimage
500 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
501 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
502 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
504 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) {
505 Ok(()) => Ok(payment_hash),
507 self.remove_outbound_if_all_failed(payment_id, &e);
513 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
514 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
515 best_block_height: u32, pending_events: &Mutex<Vec<events::Event>>, logger: &L,
516 send_payment_along_path: SP,
520 ES::Target: EntropySource,
521 NS::Target: NodeSigner,
522 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
523 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
524 IH: Fn() -> InFlightHtlcs,
525 FH: Fn() -> Vec<ChannelDetails>,
528 let _single_thread = self.retry_lock.lock().unwrap();
530 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
531 let mut retry_id_route_params = None;
532 for (pmt_id, pmt) in outbounds.iter_mut() {
533 if pmt.is_auto_retryable_now() {
534 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), .. } = pmt {
535 if pending_amt_msat < total_msat {
536 retry_id_route_params = Some((*pmt_id, RouteParameters {
537 final_value_msat: *total_msat - *pending_amt_msat,
538 payment_params: params.clone(),
545 core::mem::drop(outbounds);
546 if let Some((payment_id, route_params)) = retry_id_route_params {
547 self.retry_payment_internal(payment_id, route_params, router, first_hops(), &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, &send_payment_along_path)
551 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
552 outbounds.retain(|pmt_id, pmt| {
553 let mut retain = true;
554 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
555 if pmt.mark_abandoned().is_ok() {
556 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
558 payment_hash: pmt.payment_hash().expect("PendingOutboundPayments::Retryable always has a payment hash set"),
567 pub(super) fn needs_abandon(&self) -> bool {
568 let outbounds = self.pending_outbound_payments.lock().unwrap();
569 outbounds.iter().any(|(_, pmt)|
570 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled())
573 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
574 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
576 /// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
577 /// [`Event::PaymentFailed`]: crate::util::events::Event::PaymentFailed
578 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
579 &self, payment_id: PaymentId, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
580 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
581 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
582 node_signer: &NS, best_block_height: u32, logger: &L,
583 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP,
584 ) -> Result<(), RetryableSendFailure>
587 ES::Target: EntropySource,
588 NS::Target: NodeSigner,
590 IH: Fn() -> InFlightHtlcs,
591 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
592 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
594 #[cfg(feature = "std")] {
595 if has_expired(&route_params) {
596 return Err(RetryableSendFailure::PaymentExpired)
600 let route = router.find_route(
601 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
602 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs()
603 ).map_err(|_| RetryableSendFailure::RouteNotFound)?;
605 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret,
606 payment_id, keysend_preimage, &route, Some(retry_strategy),
607 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
608 .map_err(|_| RetryableSendFailure::DuplicatePayment)?;
610 let res = self.pay_route_internal(&route, payment_hash, payment_secret, None, payment_id, None,
611 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
612 log_info!(logger, "Result sending payment with id {}: {:?}", log_bytes!(payment_id.0), res);
613 if let Err(e) = res {
614 self.handle_pay_route_err(e, payment_id, payment_hash, route, route_params, router, first_hops, &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, &send_payment_along_path);
619 fn retry_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
620 &self, payment_id: PaymentId, route_params: RouteParameters, router: &R,
621 first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS,
622 best_block_height: u32, logger: &L, pending_events: &Mutex<Vec<events::Event>>,
623 send_payment_along_path: &SP,
627 ES::Target: EntropySource,
628 NS::Target: NodeSigner,
630 IH: Fn() -> InFlightHtlcs,
631 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
632 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
634 #[cfg(feature = "std")] {
635 if has_expired(&route_params) {
636 log_error!(logger, "Payment params expired on retry, abandoning payment {}", log_bytes!(payment_id.0));
637 self.abandon_payment(payment_id, pending_events);
642 let route = match router.find_route(
643 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
644 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs()
648 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", log_bytes!(payment_id.0), e);
649 self.abandon_payment(payment_id, pending_events);
653 for path in route.paths.iter() {
655 log_error!(logger, "length-0 path in route");
656 self.abandon_payment(payment_id, pending_events);
661 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
662 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
663 for _ in 0..route.paths.len() {
664 onion_session_privs.push(entropy_source.get_secure_random_bytes());
667 macro_rules! abandon_with_entry {
668 ($payment_id: expr, $payment_hash: expr, $payment: expr, $pending_events: expr) => {
669 if $payment.get_mut().mark_abandoned().is_ok() && $payment.get().remaining_parts() == 0 {
670 $pending_events.lock().unwrap().push(events::Event::PaymentFailed {
671 payment_id: $payment_id,
672 payment_hash: $payment_hash,
678 let (total_msat, payment_hash, payment_secret, keysend_preimage) = {
679 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
680 match outbounds.entry(payment_id) {
681 hash_map::Entry::Occupied(mut payment) => {
682 let res = match payment.get() {
683 PendingOutboundPayment::Retryable {
684 total_msat, payment_hash, keysend_preimage, payment_secret, pending_amt_msat, ..
686 let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
687 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
688 log_error!(logger, "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);
689 let payment_hash = *payment_hash;
690 abandon_with_entry!(payment_id, payment_hash, payment, pending_events);
693 (*total_msat, *payment_hash, *payment_secret, *keysend_preimage)
695 PendingOutboundPayment::Legacy { .. } => {
696 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
699 PendingOutboundPayment::Fulfilled { .. } => {
700 log_error!(logger, "Payment already completed");
703 PendingOutboundPayment::Abandoned { .. } => {
704 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
708 if !payment.get().is_retryable_now() {
709 log_error!(logger, "Retries exhausted for payment id {}", log_bytes!(payment_id.0));
710 abandon_with_entry!(payment_id, res.1, payment, pending_events);
713 payment.get_mut().increment_attempts();
714 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
715 assert!(payment.get_mut().insert(*session_priv_bytes, path));
719 hash_map::Entry::Vacant(_) => {
720 log_error!(logger, "Payment with ID {} not found", log_bytes!(payment_id.0));
725 let res = self.pay_route_internal(&route, payment_hash, &payment_secret, keysend_preimage,
726 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
727 &send_payment_along_path);
728 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), res);
729 if let Err(e) = res {
730 self.handle_pay_route_err(e, payment_id, payment_hash, route, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
734 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
735 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
736 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
737 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
738 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: &SP,
742 ES::Target: EntropySource,
743 NS::Target: NodeSigner,
745 IH: Fn() -> InFlightHtlcs,
746 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
747 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
750 PaymentSendFailure::AllFailedResendSafe(errs) => {
751 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, errs.into_iter().map(|e| Err(e)), pending_events);
752 self.retry_payment_internal(payment_id, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
754 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
755 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), pending_events);
756 // Some paths were sent, even if we failed to send the full MPP value our recipient may
757 // misbehave and claim the funds, at which point we have to consider the payment sent, so
758 // return `Ok()` here, ignoring any retry errors.
759 self.retry_payment_internal(payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
761 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
762 // This may happen if we send a payment and some paths fail, but only due to a temporary
763 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
764 // initial HTLC-Add messages yet.
766 PaymentSendFailure::PathParameterError(results) => {
767 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), pending_events);
768 self.abandon_payment(payment_id, pending_events);
770 PaymentSendFailure::ParameterError(e) => {
771 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
772 self.abandon_payment(payment_id, pending_events);
774 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
778 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>>(
779 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
780 paths: Vec<Vec<RouteHop>>, path_results: I, pending_events: &Mutex<Vec<events::Event>>
782 let mut events = pending_events.lock().unwrap();
783 debug_assert_eq!(paths.len(), path_results.len());
784 for (path, path_res) in paths.into_iter().zip(path_results) {
785 if let Err(e) = path_res {
786 if let APIError::MonitorUpdateInProgress = e { continue }
787 let mut failed_scid = None;
788 if let APIError::ChannelUnavailable { .. } = e {
789 let scid = path[0].short_channel_id;
790 failed_scid = Some(scid);
791 route_params.payment_params.previously_failed_channels.push(scid);
793 events.push(events::Event::PaymentPathFailed {
794 payment_id: Some(payment_id),
796 payment_failed_permanently: false,
797 failure: events::PathFailure::InitialSend { err: e },
799 short_channel_id: failed_scid,
810 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
811 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
812 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
813 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
815 ES::Target: EntropySource,
816 NS::Target: NodeSigner,
817 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
818 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
820 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
822 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
825 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
826 err: "No need probing a path with less than two hops".to_string()
830 let route = Route { paths: vec![hops], payment_params: None };
831 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, None, &route, None, None, entropy_source, best_block_height)?;
833 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) {
834 Ok(()) => Ok((payment_hash, payment_id)),
836 self.remove_outbound_if_all_failed(payment_id, &e);
843 pub(super) fn test_add_new_pending_payment<ES: Deref>(
844 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
845 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
846 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
847 self.add_new_pending_payment(payment_hash, payment_secret, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
850 pub(super) fn add_new_pending_payment<ES: Deref>(
851 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
852 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
853 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
854 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
855 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
856 for _ in 0..route.paths.len() {
857 onion_session_privs.push(entropy_source.get_secure_random_bytes());
860 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
861 match pending_outbounds.entry(payment_id) {
862 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
863 hash_map::Entry::Vacant(entry) => {
864 let payment = entry.insert(PendingOutboundPayment::Retryable {
866 attempts: PaymentAttempts::new(),
868 session_privs: HashSet::new(),
870 pending_fee_msat: Some(0),
874 starting_block_height: best_block_height,
875 total_msat: route.get_total_amount(),
878 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
879 assert!(payment.insert(*session_priv_bytes, path));
882 Ok(onion_session_privs)
887 fn pay_route_internal<NS: Deref, F>(
888 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
889 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
890 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
891 send_payment_along_path: &F
892 ) -> Result<(), PaymentSendFailure>
894 NS::Target: NodeSigner,
895 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
896 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
898 if route.paths.len() < 1 {
899 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
901 if payment_secret.is_none() && route.paths.len() > 1 {
902 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
904 let mut total_value = 0;
905 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
906 let mut path_errs = Vec::with_capacity(route.paths.len());
907 'path_check: for path in route.paths.iter() {
908 if path.len() < 1 || path.len() > 20 {
909 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
910 continue 'path_check;
912 for (idx, hop) in path.iter().enumerate() {
913 if idx != path.len() - 1 && hop.pubkey == our_node_id {
914 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
915 continue 'path_check;
918 total_value += path.last().unwrap().fee_msat;
919 path_errs.push(Ok(()));
921 if path_errs.iter().any(|e| e.is_err()) {
922 return Err(PaymentSendFailure::PathParameterError(path_errs));
924 if let Some(amt_msat) = recv_value_msat {
925 debug_assert!(amt_msat >= total_value);
926 total_value = amt_msat;
929 let cur_height = best_block_height + 1;
930 let mut results = Vec::new();
931 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
932 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
933 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);
936 Err(APIError::MonitorUpdateInProgress) => {
937 // While a MonitorUpdateInProgress is an Err(_), the payment is still
938 // considered "in flight" and we shouldn't remove it from the
939 // PendingOutboundPayment set.
942 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
943 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
944 let removed = payment.remove(&session_priv, Some(path));
945 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
947 debug_assert!(false, "This can't happen as the payment was added by callers");
948 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
952 results.push(path_res);
954 let mut has_ok = false;
955 let mut has_err = false;
956 let mut pending_amt_unsent = 0;
957 let mut max_unsent_cltv_delta = 0;
958 for (res, path) in results.iter().zip(route.paths.iter()) {
959 if res.is_ok() { has_ok = true; }
960 if res.is_err() { has_err = true; }
961 if let &Err(APIError::MonitorUpdateInProgress) = res {
962 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
966 } else if res.is_err() {
967 pending_amt_unsent += path.last().unwrap().fee_msat;
968 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
971 if has_err && has_ok {
972 Err(PaymentSendFailure::PartialFailure {
975 failed_paths_retry: if pending_amt_unsent != 0 {
976 if let Some(payment_params) = &route.payment_params {
977 Some(RouteParameters {
978 payment_params: payment_params.clone(),
979 final_value_msat: pending_amt_unsent,
985 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
992 pub(super) fn test_send_payment_internal<NS: Deref, F>(
993 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
994 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
995 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
996 send_payment_along_path: F
997 ) -> Result<(), PaymentSendFailure>
999 NS::Target: NodeSigner,
1000 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
1001 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
1003 self.pay_route_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id,
1004 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1005 &send_payment_along_path)
1006 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1009 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1010 // map as the payment is free to be resent.
1011 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1012 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1013 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1014 debug_assert!(removed, "We should always have a pending payment to remove here");
1018 pub(super) fn claim_htlc<L: Deref>(
1019 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1020 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
1021 ) where L::Target: Logger {
1022 let mut session_priv_bytes = [0; 32];
1023 session_priv_bytes.copy_from_slice(&session_priv[..]);
1024 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1025 let mut pending_events = pending_events.lock().unwrap();
1026 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1027 if !payment.get().is_fulfilled() {
1028 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1029 let fee_paid_msat = payment.get().get_pending_fee_msat();
1030 pending_events.push(
1031 events::Event::PaymentSent {
1032 payment_id: Some(payment_id),
1038 payment.get_mut().mark_fulfilled();
1042 // We currently immediately remove HTLCs which were fulfilled on-chain.
1043 // This could potentially lead to removing a pending payment too early,
1044 // with a reorg of one block causing us to re-add the fulfilled payment on
1046 // TODO: We should have a second monitor event that informs us of payments
1047 // irrevocably fulfilled.
1048 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1049 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1050 pending_events.push(
1051 events::Event::PaymentPathSuccessful {
1060 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
1064 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
1065 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1066 let mut pending_events = pending_events.lock().unwrap();
1067 for source in sources {
1068 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1069 let mut session_priv_bytes = [0; 32];
1070 session_priv_bytes.copy_from_slice(&session_priv[..]);
1071 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1072 assert!(payment.get().is_fulfilled());
1073 if payment.get_mut().remove(&session_priv_bytes, None) {
1074 pending_events.push(
1075 events::Event::PaymentPathSuccessful {
1077 payment_hash: payment.get().payment_hash(),
1087 pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
1088 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1089 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1090 // this could race the user making a duplicate send_payment call and our idempotency
1091 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1092 // removal. This should be more than sufficient to ensure the idempotency of any
1093 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1095 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1096 let pending_events = pending_events.lock().unwrap();
1097 pending_outbound_payments.retain(|payment_id, payment| {
1098 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1099 let mut no_remaining_entries = session_privs.is_empty();
1100 if no_remaining_entries {
1101 for ev in pending_events.iter() {
1103 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1104 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1105 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1106 if payment_id == ev_payment_id {
1107 no_remaining_entries = false;
1115 if no_remaining_entries {
1116 *timer_ticks_without_htlcs += 1;
1117 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1119 *timer_ticks_without_htlcs = 0;
1126 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1127 pub(super) fn fail_htlc<L: Deref>(
1128 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1129 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
1130 payment_params: &Option<PaymentParameters>, probing_cookie_secret: [u8; 32],
1131 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
1132 ) -> bool where L::Target: Logger {
1134 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1136 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1138 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1139 let mut session_priv_bytes = [0; 32];
1140 session_priv_bytes.copy_from_slice(&session_priv[..]);
1141 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1143 // If any payments already need retry, there's no need to generate a redundant
1144 // `PendingHTLCsForwardable`.
1145 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1146 let mut awaiting_retry = false;
1147 if pmt.is_auto_retryable_now() {
1148 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1149 if pending_amt_msat < total_msat {
1150 awaiting_retry = true;
1157 let mut full_failure_ev = None;
1158 let mut pending_retry_ev = false;
1159 let mut retry = None;
1160 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1161 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1162 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1165 if payment.get().is_fulfilled() {
1166 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1169 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1170 if let Some(scid) = short_channel_id {
1171 payment.get_mut().insert_previously_failed_scid(scid);
1174 // We want to move towards only using the `PaymentParameters` in the outbound payments
1175 // map. However, for backwards-compatibility, we still need to support passing the
1176 // `PaymentParameters` data that was shoved in the HTLC (and given to us via
1177 // `payment_params`) back to the user.
1178 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
1179 if let Some(params) = payment.get_mut().payment_parameters() {
1180 retry = Some(RouteParameters {
1181 payment_params: params.clone(),
1182 final_value_msat: path_last_hop.fee_msat,
1184 } else if let Some(params) = payment_params {
1185 retry = Some(RouteParameters {
1186 payment_params: params.clone(),
1187 final_value_msat: path_last_hop.fee_msat,
1191 if payment_is_probe || !is_retryable_now || !payment_retryable || retry.is_none() {
1192 let _ = payment.get_mut().mark_abandoned(); // we'll only Err if it's a legacy payment
1193 is_retryable_now = false;
1195 if payment.get().remaining_parts() == 0 {
1196 if payment.get().abandoned() {
1197 if !payment_is_probe {
1198 full_failure_ev = Some(events::Event::PaymentFailed {
1199 payment_id: *payment_id,
1200 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1208 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1211 core::mem::drop(outbounds);
1212 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1214 let path_failure = {
1215 if payment_is_probe {
1216 if !payment_retryable {
1217 events::Event::ProbeSuccessful {
1218 payment_id: *payment_id,
1219 payment_hash: payment_hash.clone(),
1223 events::Event::ProbeFailed {
1224 payment_id: *payment_id,
1225 payment_hash: payment_hash.clone(),
1231 // TODO: If we decided to blame ourselves (or one of our channels) in
1232 // process_onion_failure we should close that channel as it implies our
1233 // next-hop is needlessly blaming us!
1234 if let Some(scid) = short_channel_id {
1235 retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
1237 // If we miss abandoning the payment above, we *must* generate an event here or else the
1238 // payment will sit in our outbounds forever.
1239 if attempts_remaining && !already_awaiting_retry {
1240 debug_assert!(full_failure_ev.is_none());
1241 pending_retry_ev = true;
1243 events::Event::PaymentPathFailed {
1244 payment_id: Some(*payment_id),
1245 payment_hash: payment_hash.clone(),
1246 payment_failed_permanently: !payment_retryable,
1247 failure: events::PathFailure::OnPath { network_update },
1252 error_code: onion_error_code,
1254 error_data: onion_error_data
1258 let mut pending_events = pending_events.lock().unwrap();
1259 pending_events.push(path_failure);
1260 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1264 pub(super) fn abandon_payment(
1265 &self, payment_id: PaymentId, pending_events: &Mutex<Vec<events::Event>>
1267 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1268 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1269 if let Ok(()) = payment.get_mut().mark_abandoned() {
1270 if payment.get().remaining_parts() == 0 {
1271 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1273 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1282 pub fn has_pending_payments(&self) -> bool {
1283 !self.pending_outbound_payments.lock().unwrap().is_empty()
1287 pub fn clear_pending_payments(&self) {
1288 self.pending_outbound_payments.lock().unwrap().clear()
1292 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1294 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1295 probing_cookie_secret: [u8; 32]) -> bool
1297 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1298 target_payment_hash == *payment_hash
1301 /// Returns the 'probing cookie' for the given [`PaymentId`].
1302 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1303 let mut preimage = [0u8; 64];
1304 preimage[..32].copy_from_slice(&probing_cookie_secret);
1305 preimage[32..].copy_from_slice(&payment_id.0);
1306 PaymentHash(Sha256::hash(&preimage).into_inner())
1309 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1311 (0, session_privs, required),
1314 (0, session_privs, required),
1315 (1, payment_hash, option),
1316 (3, timer_ticks_without_htlcs, (default_value, 0)),
1319 (0, session_privs, required),
1320 (1, pending_fee_msat, option),
1321 (2, payment_hash, required),
1322 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1323 // never see it - `payment_params` was added here after the field was added/required.
1324 (3, payment_params, (option: ReadableArgs, 0)),
1325 (4, payment_secret, option),
1326 (5, keysend_preimage, option),
1327 (6, total_msat, required),
1328 (8, pending_amt_msat, required),
1329 (10, starting_block_height, required),
1330 (not_written, retry_strategy, (static_value, None)),
1331 (not_written, attempts, (static_value, PaymentAttempts::new())),
1334 (0, session_privs, required),
1335 (2, payment_hash, required),
1341 use bitcoin::network::constants::Network;
1342 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1344 use crate::ln::PaymentHash;
1345 use crate::ln::channelmanager::PaymentId;
1346 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1347 use crate::ln::msgs::{ErrorAction, LightningError};
1348 use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
1349 use crate::routing::gossip::NetworkGraph;
1350 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters};
1351 use crate::sync::{Arc, Mutex};
1352 use crate::util::errors::APIError;
1353 use crate::util::events::{Event, PathFailure};
1354 use crate::util::test_utils;
1357 #[cfg(feature = "std")]
1358 fn fails_paying_after_expiration() {
1359 do_fails_paying_after_expiration(false);
1360 do_fails_paying_after_expiration(true);
1362 #[cfg(feature = "std")]
1363 fn do_fails_paying_after_expiration(on_retry: bool) {
1364 let outbound_payments = OutboundPayments::new();
1365 let logger = test_utils::TestLogger::new();
1366 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1367 let scorer = Mutex::new(test_utils::TestScorer::new());
1368 let router = test_utils::TestRouter::new(network_graph, &scorer);
1369 let secp_ctx = Secp256k1::new();
1370 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1372 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1373 let payment_params = PaymentParameters::from_node_id(
1374 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1376 ).with_expiry_time(past_expiry_time);
1377 let expired_route_params = RouteParameters {
1379 final_value_msat: 0,
1381 let pending_events = Mutex::new(Vec::new());
1383 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), None, PaymentId([0; 32]), None,
1384 &Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)),
1385 Some(expired_route_params.payment_params.clone()), &&keys_manager, 0).unwrap();
1386 outbound_payments.retry_payment_internal(
1387 PaymentId([0; 32]), expired_route_params, &&router, vec![], &|| InFlightHtlcs::new(),
1388 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1389 &|_, _, _, _, _, _, _, _, _| Ok(()));
1390 let events = pending_events.lock().unwrap();
1391 assert_eq!(events.len(), 1);
1392 if let Event::PaymentFailed { .. } = events[0] { } else { panic!("Unexpected event"); }
1394 let err = outbound_payments.send_payment(
1395 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), expired_route_params,
1396 &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1397 &pending_events, |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1398 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1403 fn find_route_error() {
1404 do_find_route_error(false);
1405 do_find_route_error(true);
1407 fn do_find_route_error(on_retry: bool) {
1408 let outbound_payments = OutboundPayments::new();
1409 let logger = test_utils::TestLogger::new();
1410 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1411 let scorer = Mutex::new(test_utils::TestScorer::new());
1412 let router = test_utils::TestRouter::new(network_graph, &scorer);
1413 let secp_ctx = Secp256k1::new();
1414 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1416 let payment_params = PaymentParameters::from_node_id(
1417 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1418 let route_params = RouteParameters {
1420 final_value_msat: 0,
1422 router.expect_find_route(route_params.clone(),
1423 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1425 let pending_events = Mutex::new(Vec::new());
1427 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), None, PaymentId([0; 32]), None,
1428 &Route { paths: vec![], payment_params: None }, Some(Retry::Attempts(1)),
1429 Some(route_params.payment_params.clone()), &&keys_manager, 0).unwrap();
1430 outbound_payments.retry_payment_internal(
1431 PaymentId([0; 32]), route_params, &&router, vec![], &|| InFlightHtlcs::new(),
1432 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1433 &|_, _, _, _, _, _, _, _, _| Ok(()));
1434 let events = pending_events.lock().unwrap();
1435 assert_eq!(events.len(), 1);
1436 if let Event::PaymentFailed { .. } = events[0] { } else { panic!("Unexpected event"); }
1438 let err = outbound_payments.send_payment(
1439 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params,
1440 &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1441 &pending_events, |_, _, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1442 if let RetryableSendFailure::RouteNotFound = err {
1443 } else { panic!("Unexpected error"); }
1448 fn initial_send_payment_path_failed_evs() {
1449 let outbound_payments = OutboundPayments::new();
1450 let logger = test_utils::TestLogger::new();
1451 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1452 let scorer = Mutex::new(test_utils::TestScorer::new());
1453 let router = test_utils::TestRouter::new(network_graph, &scorer);
1454 let secp_ctx = Secp256k1::new();
1455 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1457 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1458 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1459 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1460 let route_params = RouteParameters {
1461 payment_params: payment_params.clone(),
1462 final_value_msat: 0,
1464 let failed_scid = 42;
1466 paths: vec![vec![RouteHop {
1467 pubkey: receiver_pk,
1468 node_features: NodeFeatures::empty(),
1469 short_channel_id: failed_scid,
1470 channel_features: ChannelFeatures::empty(),
1472 cltv_expiry_delta: 0,
1474 payment_params: Some(payment_params),
1476 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1477 let mut route_params_w_failed_scid = route_params.clone();
1478 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1479 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1480 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1481 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1483 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1484 // PaymentPathFailed event.
1485 let pending_events = Mutex::new(Vec::new());
1486 outbound_payments.send_payment(
1487 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params.clone(),
1488 &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1490 |_, _, _, _, _, _, _, _, _| Err(APIError::ChannelUnavailable { err: "test".to_owned() }))
1492 let mut events = pending_events.lock().unwrap();
1493 assert_eq!(events.len(), 2);
1494 if let Event::PaymentPathFailed {
1496 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0]
1498 assert_eq!(short_channel_id, Some(failed_scid));
1499 } else { panic!("Unexpected event"); }
1500 if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }
1502 core::mem::drop(events);
1504 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1505 outbound_payments.send_payment(
1506 PaymentHash([0; 32]), &None, PaymentId([0; 32]), Retry::Attempts(0), route_params.clone(),
1507 &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1508 &pending_events, |_, _, _, _, _, _, _, _, _| Err(APIError::MonitorUpdateInProgress))
1511 let events = pending_events.lock().unwrap();
1512 assert_eq!(events.len(), 0);
1515 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1516 outbound_payments.send_payment(
1517 PaymentHash([0; 32]), &None, PaymentId([1; 32]), Retry::Attempts(0), route_params.clone(),
1518 &&router, vec![], || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1520 |_, _, _, _, _, _, _, _, _| Err(APIError::APIMisuseError { err: "test".to_owned() }))
1522 let events = pending_events.lock().unwrap();
1523 assert_eq!(events.len(), 2);
1524 if let Event::PaymentPathFailed {
1526 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0]
1528 assert_eq!(short_channel_id, None);
1529 } else { panic!("Unexpected event"); }
1530 if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }