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::events::{self, PaymentFailureReason};
18 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
19 use crate::ln::channelmanager::{ChannelDetails, HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, PaymentId};
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::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,
71 /// Will be `None` if the payment was serialized before 0.0.115.
72 reason: Option<PaymentFailureReason>,
76 impl PendingOutboundPayment {
77 fn increment_attempts(&mut self) {
78 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
82 fn is_auto_retryable_now(&self) -> bool {
84 PendingOutboundPayment::Retryable {
85 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
87 strategy.is_retryable_now(&attempts)
92 fn is_retryable_now(&self) -> bool {
94 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
95 // We're handling retries manually, we can always retry.
98 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
99 strategy.is_retryable_now(&attempts)
104 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
105 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
106 params.previously_failed_channels.push(scid);
109 pub(super) fn is_fulfilled(&self) -> bool {
111 PendingOutboundPayment::Fulfilled { .. } => true,
115 pub(super) fn abandoned(&self) -> bool {
117 PendingOutboundPayment::Abandoned { .. } => true,
121 fn get_pending_fee_msat(&self) -> Option<u64> {
123 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
128 fn payment_hash(&self) -> Option<PaymentHash> {
130 PendingOutboundPayment::Legacy { .. } => None,
131 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
132 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
133 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
137 fn mark_fulfilled(&mut self) {
138 let mut session_privs = HashSet::new();
139 core::mem::swap(&mut session_privs, match self {
140 PendingOutboundPayment::Legacy { session_privs } |
141 PendingOutboundPayment::Retryable { session_privs, .. } |
142 PendingOutboundPayment::Fulfilled { session_privs, .. } |
143 PendingOutboundPayment::Abandoned { session_privs, .. }
146 let payment_hash = self.payment_hash();
147 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
150 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
151 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
152 let mut our_session_privs = HashSet::new();
153 core::mem::swap(&mut our_session_privs, session_privs);
154 *self = PendingOutboundPayment::Abandoned {
155 session_privs: our_session_privs,
156 payment_hash: *payment_hash,
162 /// panics if path is None and !self.is_fulfilled
163 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
164 let remove_res = match self {
165 PendingOutboundPayment::Legacy { session_privs } |
166 PendingOutboundPayment::Retryable { session_privs, .. } |
167 PendingOutboundPayment::Fulfilled { session_privs, .. } |
168 PendingOutboundPayment::Abandoned { session_privs, .. } => {
169 session_privs.remove(session_priv)
173 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
174 let path = path.expect("Fulfilling a payment should always come with a path");
175 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
176 *pending_amt_msat -= path_last_hop.fee_msat;
177 if let Some(fee_msat) = pending_fee_msat.as_mut() {
178 *fee_msat -= path.get_path_fees();
185 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
186 let insert_res = match self {
187 PendingOutboundPayment::Legacy { session_privs } |
188 PendingOutboundPayment::Retryable { session_privs, .. } => {
189 session_privs.insert(session_priv)
191 PendingOutboundPayment::Fulfilled { .. } => false,
192 PendingOutboundPayment::Abandoned { .. } => false,
195 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
196 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
197 *pending_amt_msat += path_last_hop.fee_msat;
198 if let Some(fee_msat) = pending_fee_msat.as_mut() {
199 *fee_msat += path.get_path_fees();
206 pub(super) fn remaining_parts(&self) -> usize {
208 PendingOutboundPayment::Legacy { session_privs } |
209 PendingOutboundPayment::Retryable { session_privs, .. } |
210 PendingOutboundPayment::Fulfilled { session_privs, .. } |
211 PendingOutboundPayment::Abandoned { session_privs, .. } => {
218 /// Strategies available to retry payment path failures.
219 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
221 /// Max number of attempts to retry payment.
223 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
224 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
225 /// were retried along a route from a single call to [`Router::find_route_with_id`].
227 #[cfg(not(feature = "no-std"))]
228 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
229 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
231 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
232 Timeout(core::time::Duration),
236 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
237 match (self, attempts) {
238 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
239 max_retry_count > count
241 #[cfg(all(not(feature = "no-std"), not(test)))]
242 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
243 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
244 #[cfg(all(not(feature = "no-std"), test))]
245 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
246 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
251 #[cfg(feature = "std")]
252 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
253 if let Some(expiry_time) = route_params.payment_params.expiry_time {
254 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
255 return elapsed > core::time::Duration::from_secs(expiry_time)
261 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
263 /// Storing minimal payment attempts information required for determining if a outbound payment can
265 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
266 /// This count will be incremented only after the result of the attempt is known. When it's 0,
267 /// it means the result of the first attempt is not known yet.
268 pub(crate) count: usize,
269 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
270 #[cfg(not(feature = "no-std"))]
271 first_attempted_at: T,
272 #[cfg(feature = "no-std")]
273 phantom: core::marker::PhantomData<T>,
277 #[cfg(not(any(feature = "no-std", test)))]
278 type ConfiguredTime = std::time::Instant;
279 #[cfg(feature = "no-std")]
280 type ConfiguredTime = crate::util::time::Eternity;
281 #[cfg(all(not(feature = "no-std"), test))]
282 type ConfiguredTime = SinceEpoch;
284 impl<T: Time> PaymentAttemptsUsingTime<T> {
285 pub(crate) fn new() -> Self {
286 PaymentAttemptsUsingTime {
288 #[cfg(not(feature = "no-std"))]
289 first_attempted_at: T::now(),
290 #[cfg(feature = "no-std")]
291 phantom: core::marker::PhantomData,
296 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
297 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
298 #[cfg(feature = "no-std")]
299 return write!(f, "attempts: {}", self.count);
300 #[cfg(not(feature = "no-std"))]
303 "attempts: {}, duration: {}s",
305 T::now().duration_since(self.first_attempted_at).as_secs()
310 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
311 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
313 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
314 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
315 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
316 #[derive(Clone, Debug)]
317 pub enum RetryableSendFailure {
318 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
319 /// that this error is *not* caused by [`Retry::Timeout`].
321 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
323 /// We were unable to find a route to the destination.
325 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
326 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
328 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
329 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
330 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
334 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
335 /// of several states. This enum is returned as the Err() type describing which state the payment
336 /// is in, see the description of individual enum states for more.
338 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
339 #[derive(Clone, Debug)]
340 pub enum PaymentSendFailure {
341 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
342 /// send the payment at all.
344 /// You can freely resend the payment in full (with the parameter error fixed).
346 /// Because the payment failed outright, no payment tracking is done and no
347 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
349 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
350 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
351 ParameterError(APIError),
352 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
353 /// from attempting to send the payment at all.
355 /// You can freely resend the payment in full (with the parameter error fixed).
357 /// Because the payment failed outright, no payment tracking is done and no
358 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
360 /// The results here are ordered the same as the paths in the route object which was passed to
363 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
364 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
365 PathParameterError(Vec<Result<(), APIError>>),
366 /// All paths which were attempted failed to send, with no channel state change taking place.
367 /// You can freely resend the payment in full (though you probably want to do so over different
368 /// paths than the ones selected).
370 /// Because the payment failed outright, no payment tracking is done and no
371 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
373 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
374 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
375 AllFailedResendSafe(Vec<APIError>),
376 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
377 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
379 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
380 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
381 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
383 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
384 /// some paths have irrevocably committed to the HTLC.
386 /// The results here are ordered the same as the paths in the route object that was passed to
389 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
390 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
392 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
394 /// The errors themselves, in the same order as the paths from the route.
395 results: Vec<Result<(), APIError>>,
396 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
397 /// contain a [`RouteParameters`] object for the failing paths.
398 failed_paths_retry: Option<RouteParameters>,
399 /// The payment id for the payment, which is now at least partially pending.
400 payment_id: PaymentId,
404 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
406 /// This should generally be constructed with data communicated to us from the recipient (via a
407 /// BOLT11 or BOLT12 invoice).
409 pub struct RecipientOnionFields {
410 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
411 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
412 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
415 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
416 /// multi-path payments require a recipient-provided secret.
418 /// Note that for spontaneous payments most lightning nodes do not currently support MPP
419 /// receives, thus you should generally never be providing a secret here for spontaneous
421 pub payment_secret: Option<PaymentSecret>,
424 impl RecipientOnionFields {
425 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
426 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
427 /// but do not require or provide any further data.
428 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
429 Self { payment_secret: Some(payment_secret) }
432 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
433 /// payable HTLCs except for spontaneous payments, i.e. this should generally only be used for
434 /// calls to [`ChannelManager::send_spontaneous_payment`].
436 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
437 pub fn spontaneous_empty() -> Self {
438 Self { payment_secret: None }
442 pub(super) struct OutboundPayments {
443 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
444 pub(super) retry_lock: Mutex<()>,
447 impl OutboundPayments {
448 pub(super) fn new() -> Self {
450 pending_outbound_payments: Mutex::new(HashMap::new()),
451 retry_lock: Mutex::new(()),
455 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
456 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
457 retry_strategy: Retry, route_params: RouteParameters, router: &R,
458 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
459 node_signer: &NS, best_block_height: u32, logger: &L,
460 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP,
461 ) -> Result<(), RetryableSendFailure>
464 ES::Target: EntropySource,
465 NS::Target: NodeSigner,
467 IH: Fn() -> InFlightHtlcs,
468 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
469 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
471 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
472 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
473 best_block_height, logger, pending_events, &send_payment_along_path)
476 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
477 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
478 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
479 send_payment_along_path: F
480 ) -> Result<(), PaymentSendFailure>
482 ES::Target: EntropySource,
483 NS::Target: NodeSigner,
484 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
485 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
487 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(), payment_id, None, route, None, None, entropy_source, best_block_height)?;
488 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
489 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
490 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
493 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
494 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
495 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
496 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
497 node_signer: &NS, best_block_height: u32, logger: &L,
498 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP
499 ) -> Result<PaymentHash, RetryableSendFailure>
502 ES::Target: EntropySource,
503 NS::Target: NodeSigner,
505 IH: Fn() -> InFlightHtlcs,
506 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
507 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
509 let preimage = payment_preimage
510 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
511 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
512 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
513 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
514 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
515 .map(|()| payment_hash)
518 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
519 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
520 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
521 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
522 ) -> Result<PaymentHash, PaymentSendFailure>
524 ES::Target: EntropySource,
525 NS::Target: NodeSigner,
526 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
527 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
529 let preimage = payment_preimage
530 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
531 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
532 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
533 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
535 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
536 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
538 Ok(()) => Ok(payment_hash),
540 self.remove_outbound_if_all_failed(payment_id, &e);
546 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
547 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
548 best_block_height: u32, pending_events: &Mutex<Vec<events::Event>>, logger: &L,
549 send_payment_along_path: SP,
553 ES::Target: EntropySource,
554 NS::Target: NodeSigner,
555 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
556 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
557 IH: Fn() -> InFlightHtlcs,
558 FH: Fn() -> Vec<ChannelDetails>,
561 let _single_thread = self.retry_lock.lock().unwrap();
563 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
564 let mut retry_id_route_params = None;
565 for (pmt_id, pmt) in outbounds.iter_mut() {
566 if pmt.is_auto_retryable_now() {
567 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, .. } = pmt {
568 if pending_amt_msat < total_msat {
569 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
570 final_value_msat: *total_msat - *pending_amt_msat,
571 payment_params: params.clone(),
575 } else { debug_assert!(false); }
578 core::mem::drop(outbounds);
579 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
580 self.retry_payment_internal(payment_hash, payment_id, route_params, router, first_hops(), &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, &send_payment_along_path)
584 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
585 outbounds.retain(|pmt_id, pmt| {
586 let mut retain = true;
587 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
588 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
589 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
590 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
592 payment_hash: *payment_hash,
602 pub(super) fn needs_abandon(&self) -> bool {
603 let outbounds = self.pending_outbound_payments.lock().unwrap();
604 outbounds.iter().any(|(_, pmt)|
605 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled())
608 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
609 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
611 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
612 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
613 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
614 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
615 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
616 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
617 node_signer: &NS, best_block_height: u32, logger: &L,
618 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP,
619 ) -> Result<(), RetryableSendFailure>
622 ES::Target: EntropySource,
623 NS::Target: NodeSigner,
625 IH: Fn() -> InFlightHtlcs,
626 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
627 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
629 #[cfg(feature = "std")] {
630 if has_expired(&route_params) {
631 return Err(RetryableSendFailure::PaymentExpired)
635 let route = router.find_route_with_id(
636 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
637 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
638 payment_hash, payment_id,
639 ).map_err(|_| RetryableSendFailure::RouteNotFound)?;
641 let onion_session_privs = self.add_new_pending_payment(payment_hash,
642 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
643 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
644 .map_err(|_| RetryableSendFailure::DuplicatePayment)?;
646 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, None, payment_id, None,
647 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
648 log_info!(logger, "Result sending payment with id {}: {:?}", log_bytes!(payment_id.0), res);
649 if let Err(e) = res {
650 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);
655 fn retry_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
656 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
657 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
658 node_signer: &NS, best_block_height: u32, logger: &L,
659 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: &SP,
663 ES::Target: EntropySource,
664 NS::Target: NodeSigner,
666 IH: Fn() -> InFlightHtlcs,
667 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
668 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
670 #[cfg(feature = "std")] {
671 if has_expired(&route_params) {
672 log_error!(logger, "Payment params expired on retry, abandoning payment {}", log_bytes!(payment_id.0));
673 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
678 let route = match router.find_route_with_id(
679 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
680 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
681 payment_hash, payment_id,
685 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", log_bytes!(payment_id.0), e);
686 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
690 for path in route.paths.iter() {
692 log_error!(logger, "length-0 path in route");
693 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
698 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
699 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
700 for _ in 0..route.paths.len() {
701 onion_session_privs.push(entropy_source.get_secure_random_bytes());
704 macro_rules! abandon_with_entry {
705 ($payment: expr, $reason: expr) => {
706 $payment.get_mut().mark_abandoned($reason);
707 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
708 if $payment.get().remaining_parts() == 0 {
709 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
719 let (total_msat, recipient_onion, keysend_preimage) = {
720 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
721 match outbounds.entry(payment_id) {
722 hash_map::Entry::Occupied(mut payment) => {
723 let res = match payment.get() {
724 PendingOutboundPayment::Retryable {
725 total_msat, keysend_preimage, payment_secret, pending_amt_msat, ..
727 let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
728 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
729 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);
730 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
733 (*total_msat, RecipientOnionFields {
734 payment_secret: *payment_secret,
735 }, *keysend_preimage)
737 PendingOutboundPayment::Legacy { .. } => {
738 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
741 PendingOutboundPayment::Fulfilled { .. } => {
742 log_error!(logger, "Payment already completed");
745 PendingOutboundPayment::Abandoned { .. } => {
746 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
750 if !payment.get().is_retryable_now() {
751 log_error!(logger, "Retries exhausted for payment id {}", log_bytes!(payment_id.0));
752 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
755 payment.get_mut().increment_attempts();
756 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
757 assert!(payment.get_mut().insert(*session_priv_bytes, path));
761 hash_map::Entry::Vacant(_) => {
762 log_error!(logger, "Payment with ID {} not found", log_bytes!(payment_id.0));
767 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
768 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
769 &send_payment_along_path);
770 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), res);
771 if let Err(e) = res {
772 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);
776 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
777 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
778 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
779 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
780 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: &SP,
784 ES::Target: EntropySource,
785 NS::Target: NodeSigner,
787 IH: Fn() -> InFlightHtlcs,
788 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
789 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
792 PaymentSendFailure::AllFailedResendSafe(errs) => {
793 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, errs.into_iter().map(|e| Err(e)), logger, pending_events);
794 self.retry_payment_internal(payment_hash, payment_id, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
796 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
797 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
798 // Some paths were sent, even if we failed to send the full MPP value our recipient may
799 // misbehave and claim the funds, at which point we have to consider the payment sent, so
800 // return `Ok()` here, ignoring any retry errors.
801 self.retry_payment_internal(payment_hash, payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
803 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
804 // This may happen if we send a payment and some paths fail, but only due to a temporary
805 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
806 // initial HTLC-Add messages yet.
808 PaymentSendFailure::PathParameterError(results) => {
809 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
810 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
811 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
813 PaymentSendFailure::ParameterError(e) => {
814 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
815 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
817 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
821 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
822 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
823 paths: Vec<Vec<RouteHop>>, path_results: I, logger: &L, pending_events: &Mutex<Vec<events::Event>>
824 ) where L::Target: Logger {
825 let mut events = pending_events.lock().unwrap();
826 debug_assert_eq!(paths.len(), path_results.len());
827 for (path, path_res) in paths.into_iter().zip(path_results) {
828 if let Err(e) = path_res {
829 if let APIError::MonitorUpdateInProgress = e { continue }
830 log_error!(logger, "Failed to send along path due to error: {:?}", e);
831 let mut failed_scid = None;
832 if let APIError::ChannelUnavailable { .. } = e {
833 let scid = path[0].short_channel_id;
834 failed_scid = Some(scid);
835 route_params.payment_params.previously_failed_channels.push(scid);
837 events.push(events::Event::PaymentPathFailed {
838 payment_id: Some(payment_id),
840 payment_failed_permanently: false,
841 failure: events::PathFailure::InitialSend { err: e },
843 short_channel_id: failed_scid,
853 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
854 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
855 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
856 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
858 ES::Target: EntropySource,
859 NS::Target: NodeSigner,
860 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
861 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
863 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
865 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
868 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
869 err: "No need probing a path with less than two hops".to_string()
873 let route = Route { paths: vec![hops], payment_params: None };
874 let onion_session_privs = self.add_new_pending_payment(payment_hash,
875 RecipientOnionFields::spontaneous_empty(), payment_id, None, &route, None, None,
876 entropy_source, best_block_height)?;
878 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
879 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
881 Ok(()) => Ok((payment_hash, payment_id)),
883 self.remove_outbound_if_all_failed(payment_id, &e);
890 pub(super) fn test_add_new_pending_payment<ES: Deref>(
891 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
892 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
893 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
894 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
897 pub(super) fn add_new_pending_payment<ES: Deref>(
898 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
899 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
900 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
901 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
902 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
903 for _ in 0..route.paths.len() {
904 onion_session_privs.push(entropy_source.get_secure_random_bytes());
907 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
908 match pending_outbounds.entry(payment_id) {
909 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
910 hash_map::Entry::Vacant(entry) => {
911 let payment = entry.insert(PendingOutboundPayment::Retryable {
913 attempts: PaymentAttempts::new(),
915 session_privs: HashSet::new(),
917 pending_fee_msat: Some(0),
919 payment_secret: recipient_onion.payment_secret,
921 starting_block_height: best_block_height,
922 total_msat: route.get_total_amount(),
925 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
926 assert!(payment.insert(*session_priv_bytes, path));
929 Ok(onion_session_privs)
934 fn pay_route_internal<NS: Deref, F>(
935 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
936 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
937 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
938 send_payment_along_path: &F
939 ) -> Result<(), PaymentSendFailure>
941 NS::Target: NodeSigner,
942 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
943 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
945 if route.paths.len() < 1 {
946 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
948 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1 {
949 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
951 let mut total_value = 0;
952 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
953 let mut path_errs = Vec::with_capacity(route.paths.len());
954 'path_check: for path in route.paths.iter() {
955 if path.len() < 1 || path.len() > 20 {
956 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
957 continue 'path_check;
959 for (idx, hop) in path.iter().enumerate() {
960 if idx != path.len() - 1 && hop.pubkey == our_node_id {
961 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
962 continue 'path_check;
965 total_value += path.last().unwrap().fee_msat;
966 path_errs.push(Ok(()));
968 if path_errs.iter().any(|e| e.is_err()) {
969 return Err(PaymentSendFailure::PathParameterError(path_errs));
971 if let Some(amt_msat) = recv_value_msat {
972 total_value = amt_msat;
975 let cur_height = best_block_height + 1;
976 let mut results = Vec::new();
977 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
978 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
979 let mut path_res = send_payment_along_path(&path, &payment_hash, recipient_onion.clone(),
980 total_value, cur_height, payment_id, &keysend_preimage, session_priv);
983 Err(APIError::MonitorUpdateInProgress) => {
984 // While a MonitorUpdateInProgress is an Err(_), the payment is still
985 // considered "in flight" and we shouldn't remove it from the
986 // PendingOutboundPayment set.
989 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
990 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
991 let removed = payment.remove(&session_priv, Some(path));
992 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
994 debug_assert!(false, "This can't happen as the payment was added by callers");
995 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
999 results.push(path_res);
1001 let mut has_ok = false;
1002 let mut has_err = false;
1003 let mut pending_amt_unsent = 0;
1004 let mut max_unsent_cltv_delta = 0;
1005 for (res, path) in results.iter().zip(route.paths.iter()) {
1006 if res.is_ok() { has_ok = true; }
1007 if res.is_err() { has_err = true; }
1008 if let &Err(APIError::MonitorUpdateInProgress) = res {
1009 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1013 } else if res.is_err() {
1014 pending_amt_unsent += path.last().unwrap().fee_msat;
1015 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
1018 if has_err && has_ok {
1019 Err(PaymentSendFailure::PartialFailure {
1022 failed_paths_retry: if pending_amt_unsent != 0 {
1023 if let Some(payment_params) = &route.payment_params {
1024 Some(RouteParameters {
1025 payment_params: payment_params.clone(),
1026 final_value_msat: pending_amt_unsent,
1032 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1039 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1040 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1041 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1042 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1043 send_payment_along_path: F
1044 ) -> Result<(), PaymentSendFailure>
1046 NS::Target: NodeSigner,
1047 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
1048 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
1050 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1051 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1052 &send_payment_along_path)
1053 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1056 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1057 // map as the payment is free to be resent.
1058 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1059 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1060 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1061 debug_assert!(removed, "We should always have a pending payment to remove here");
1065 pub(super) fn claim_htlc<L: Deref>(
1066 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1067 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
1068 ) where L::Target: Logger {
1069 let mut session_priv_bytes = [0; 32];
1070 session_priv_bytes.copy_from_slice(&session_priv[..]);
1071 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1072 let mut pending_events = pending_events.lock().unwrap();
1073 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1074 if !payment.get().is_fulfilled() {
1075 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1076 let fee_paid_msat = payment.get().get_pending_fee_msat();
1077 pending_events.push(
1078 events::Event::PaymentSent {
1079 payment_id: Some(payment_id),
1085 payment.get_mut().mark_fulfilled();
1089 // We currently immediately remove HTLCs which were fulfilled on-chain.
1090 // This could potentially lead to removing a pending payment too early,
1091 // with a reorg of one block causing us to re-add the fulfilled payment on
1093 // TODO: We should have a second monitor event that informs us of payments
1094 // irrevocably fulfilled.
1095 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1096 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1097 pending_events.push(
1098 events::Event::PaymentPathSuccessful {
1107 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
1111 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
1112 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1113 let mut pending_events = pending_events.lock().unwrap();
1114 for source in sources {
1115 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1116 let mut session_priv_bytes = [0; 32];
1117 session_priv_bytes.copy_from_slice(&session_priv[..]);
1118 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1119 assert!(payment.get().is_fulfilled());
1120 if payment.get_mut().remove(&session_priv_bytes, None) {
1121 pending_events.push(
1122 events::Event::PaymentPathSuccessful {
1124 payment_hash: payment.get().payment_hash(),
1134 pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
1135 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1136 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1137 // this could race the user making a duplicate send_payment call and our idempotency
1138 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1139 // removal. This should be more than sufficient to ensure the idempotency of any
1140 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1142 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1143 let pending_events = pending_events.lock().unwrap();
1144 pending_outbound_payments.retain(|payment_id, payment| {
1145 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1146 let mut no_remaining_entries = session_privs.is_empty();
1147 if no_remaining_entries {
1148 for ev in pending_events.iter() {
1150 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1151 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1152 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1153 if payment_id == ev_payment_id {
1154 no_remaining_entries = false;
1162 if no_remaining_entries {
1163 *timer_ticks_without_htlcs += 1;
1164 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1166 *timer_ticks_without_htlcs = 0;
1173 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1174 pub(super) fn fail_htlc<L: Deref>(
1175 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1176 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
1177 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1178 pending_events: &Mutex<Vec<events::Event>>, logger: &L
1179 ) -> bool where L::Target: Logger {
1181 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1183 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1185 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1186 let mut session_priv_bytes = [0; 32];
1187 session_priv_bytes.copy_from_slice(&session_priv[..]);
1188 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1190 // If any payments already need retry, there's no need to generate a redundant
1191 // `PendingHTLCsForwardable`.
1192 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1193 let mut awaiting_retry = false;
1194 if pmt.is_auto_retryable_now() {
1195 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1196 if pending_amt_msat < total_msat {
1197 awaiting_retry = true;
1204 let mut full_failure_ev = None;
1205 let mut pending_retry_ev = false;
1206 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1207 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1208 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1211 if payment.get().is_fulfilled() {
1212 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1215 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1216 if let Some(scid) = short_channel_id {
1217 // TODO: If we decided to blame ourselves (or one of our channels) in
1218 // process_onion_failure we should close that channel as it implies our
1219 // next-hop is needlessly blaming us!
1220 payment.get_mut().insert_previously_failed_scid(scid);
1223 if payment_is_probe || !is_retryable_now || !payment_retryable {
1224 let reason = if !payment_retryable {
1225 PaymentFailureReason::RecipientRejected
1227 PaymentFailureReason::RetriesExhausted
1229 payment.get_mut().mark_abandoned(reason);
1230 is_retryable_now = false;
1232 if payment.get().remaining_parts() == 0 {
1233 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1234 if !payment_is_probe {
1235 full_failure_ev = Some(events::Event::PaymentFailed {
1236 payment_id: *payment_id,
1237 payment_hash: *payment_hash,
1246 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1249 core::mem::drop(outbounds);
1250 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1252 let path_failure = {
1253 if payment_is_probe {
1254 if !payment_retryable {
1255 events::Event::ProbeSuccessful {
1256 payment_id: *payment_id,
1257 payment_hash: payment_hash.clone(),
1261 events::Event::ProbeFailed {
1262 payment_id: *payment_id,
1263 payment_hash: payment_hash.clone(),
1269 // If we miss abandoning the payment above, we *must* generate an event here or else the
1270 // payment will sit in our outbounds forever.
1271 if attempts_remaining && !already_awaiting_retry {
1272 debug_assert!(full_failure_ev.is_none());
1273 pending_retry_ev = true;
1275 events::Event::PaymentPathFailed {
1276 payment_id: Some(*payment_id),
1277 payment_hash: payment_hash.clone(),
1278 payment_failed_permanently: !payment_retryable,
1279 failure: events::PathFailure::OnPath { network_update },
1283 error_code: onion_error_code,
1285 error_data: onion_error_data
1289 let mut pending_events = pending_events.lock().unwrap();
1290 pending_events.push(path_failure);
1291 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1295 pub(super) fn abandon_payment(
1296 &self, payment_id: PaymentId, reason: PaymentFailureReason, pending_events: &Mutex<Vec<events::Event>>
1298 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1299 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1300 payment.get_mut().mark_abandoned(reason);
1301 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1302 if payment.get().remaining_parts() == 0 {
1303 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1305 payment_hash: *payment_hash,
1315 pub fn has_pending_payments(&self) -> bool {
1316 !self.pending_outbound_payments.lock().unwrap().is_empty()
1320 pub fn clear_pending_payments(&self) {
1321 self.pending_outbound_payments.lock().unwrap().clear()
1325 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1327 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1328 probing_cookie_secret: [u8; 32]) -> bool
1330 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1331 target_payment_hash == *payment_hash
1334 /// Returns the 'probing cookie' for the given [`PaymentId`].
1335 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1336 let mut preimage = [0u8; 64];
1337 preimage[..32].copy_from_slice(&probing_cookie_secret);
1338 preimage[32..].copy_from_slice(&payment_id.0);
1339 PaymentHash(Sha256::hash(&preimage).into_inner())
1342 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1344 (0, session_privs, required),
1347 (0, session_privs, required),
1348 (1, payment_hash, option),
1349 (3, timer_ticks_without_htlcs, (default_value, 0)),
1352 (0, session_privs, required),
1353 (1, pending_fee_msat, option),
1354 (2, payment_hash, required),
1355 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1356 // never see it - `payment_params` was added here after the field was added/required.
1357 (3, payment_params, (option: ReadableArgs, 0)),
1358 (4, payment_secret, option),
1359 (5, keysend_preimage, option),
1360 (6, total_msat, required),
1361 (8, pending_amt_msat, required),
1362 (10, starting_block_height, required),
1363 (not_written, retry_strategy, (static_value, None)),
1364 (not_written, attempts, (static_value, PaymentAttempts::new())),
1367 (0, session_privs, required),
1368 (1, reason, option),
1369 (2, payment_hash, required),
1375 use bitcoin::network::constants::Network;
1376 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1378 use crate::events::{Event, PathFailure, PaymentFailureReason};
1379 use crate::ln::PaymentHash;
1380 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1381 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1382 use crate::ln::msgs::{ErrorAction, LightningError};
1383 use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
1384 use crate::routing::gossip::NetworkGraph;
1385 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters};
1386 use crate::sync::{Arc, Mutex};
1387 use crate::util::errors::APIError;
1388 use crate::util::test_utils;
1391 #[cfg(feature = "std")]
1392 fn fails_paying_after_expiration() {
1393 do_fails_paying_after_expiration(false);
1394 do_fails_paying_after_expiration(true);
1396 #[cfg(feature = "std")]
1397 fn do_fails_paying_after_expiration(on_retry: bool) {
1398 let outbound_payments = OutboundPayments::new();
1399 let logger = test_utils::TestLogger::new();
1400 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1401 let scorer = Mutex::new(test_utils::TestScorer::new());
1402 let router = test_utils::TestRouter::new(network_graph, &scorer);
1403 let secp_ctx = Secp256k1::new();
1404 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1406 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1407 let payment_params = PaymentParameters::from_node_id(
1408 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1410 ).with_expiry_time(past_expiry_time);
1411 let expired_route_params = RouteParameters {
1413 final_value_msat: 0,
1415 let pending_events = Mutex::new(Vec::new());
1417 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1418 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1419 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1420 &&keys_manager, 0).unwrap();
1421 outbound_payments.retry_payment_internal(
1422 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1423 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1424 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1425 let events = pending_events.lock().unwrap();
1426 assert_eq!(events.len(), 1);
1427 if let Event::PaymentFailed { ref reason, .. } = events[0] {
1428 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1429 } else { panic!("Unexpected event"); }
1431 let err = outbound_payments.send_payment(
1432 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1433 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1434 &&keys_manager, &&keys_manager, 0, &&logger,
1435 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1436 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1441 fn find_route_error() {
1442 do_find_route_error(false);
1443 do_find_route_error(true);
1445 fn do_find_route_error(on_retry: bool) {
1446 let outbound_payments = OutboundPayments::new();
1447 let logger = test_utils::TestLogger::new();
1448 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1449 let scorer = Mutex::new(test_utils::TestScorer::new());
1450 let router = test_utils::TestRouter::new(network_graph, &scorer);
1451 let secp_ctx = Secp256k1::new();
1452 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1454 let payment_params = PaymentParameters::from_node_id(
1455 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1456 let route_params = RouteParameters {
1458 final_value_msat: 0,
1460 router.expect_find_route(route_params.clone(),
1461 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1463 let pending_events = Mutex::new(Vec::new());
1465 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1466 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1467 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1468 &&keys_manager, 0).unwrap();
1469 outbound_payments.retry_payment_internal(
1470 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1471 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1472 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1473 let events = pending_events.lock().unwrap();
1474 assert_eq!(events.len(), 1);
1475 if let Event::PaymentFailed { .. } = events[0] { } else { panic!("Unexpected event"); }
1477 let err = outbound_payments.send_payment(
1478 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1479 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1480 &&keys_manager, &&keys_manager, 0, &&logger,
1481 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1482 if let RetryableSendFailure::RouteNotFound = err {
1483 } else { panic!("Unexpected error"); }
1488 fn initial_send_payment_path_failed_evs() {
1489 let outbound_payments = OutboundPayments::new();
1490 let logger = test_utils::TestLogger::new();
1491 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1492 let scorer = Mutex::new(test_utils::TestScorer::new());
1493 let router = test_utils::TestRouter::new(network_graph, &scorer);
1494 let secp_ctx = Secp256k1::new();
1495 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1497 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1498 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1499 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1500 let route_params = RouteParameters {
1501 payment_params: payment_params.clone(),
1502 final_value_msat: 0,
1504 let failed_scid = 42;
1506 paths: vec![vec![RouteHop {
1507 pubkey: receiver_pk,
1508 node_features: NodeFeatures::empty(),
1509 short_channel_id: failed_scid,
1510 channel_features: ChannelFeatures::empty(),
1512 cltv_expiry_delta: 0,
1514 payment_params: Some(payment_params),
1516 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1517 let mut route_params_w_failed_scid = route_params.clone();
1518 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1519 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1520 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1521 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1523 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1524 // PaymentPathFailed event.
1525 let pending_events = Mutex::new(Vec::new());
1526 outbound_payments.send_payment(
1527 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1528 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1529 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1530 |_, _, _, _, _, _, _, _| Err(APIError::ChannelUnavailable { err: "test".to_owned() }))
1532 let mut events = pending_events.lock().unwrap();
1533 assert_eq!(events.len(), 2);
1534 if let Event::PaymentPathFailed {
1536 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0]
1538 assert_eq!(short_channel_id, Some(failed_scid));
1539 } else { panic!("Unexpected event"); }
1540 if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }
1542 core::mem::drop(events);
1544 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1545 outbound_payments.send_payment(
1546 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1547 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1548 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1549 |_, _, _, _, _, _, _, _| Err(APIError::MonitorUpdateInProgress)).unwrap();
1550 assert_eq!(pending_events.lock().unwrap().len(), 0);
1552 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1553 outbound_payments.send_payment(
1554 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1555 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1556 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1557 |_, _, _, _, _, _, _, _| Err(APIError::APIMisuseError { err: "test".to_owned() }))
1559 let events = pending_events.lock().unwrap();
1560 assert_eq!(events.len(), 2);
1561 if let Event::PaymentPathFailed {
1563 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0]
1565 assert_eq!(short_channel_id, None);
1566 } else { panic!("Unexpected event"); }
1567 if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }