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;
29 use core::fmt::{self, Display, Formatter};
32 use crate::prelude::*;
33 use crate::sync::Mutex;
35 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
36 /// and later, also stores information for retrying the payment.
37 pub(crate) enum PendingOutboundPayment {
39 session_privs: HashSet<[u8; 32]>,
42 retry_strategy: Option<Retry>,
43 attempts: PaymentAttempts,
44 payment_params: Option<PaymentParameters>,
45 session_privs: HashSet<[u8; 32]>,
46 payment_hash: PaymentHash,
47 payment_secret: Option<PaymentSecret>,
48 payment_metadata: Option<Vec<u8>>,
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).
408 #[derive(Clone, Debug, PartialEq, Eq)]
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>,
422 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
423 /// arbitrary length. This gives recipients substantially more flexibility to receive
426 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
427 /// scheme to authenticate received payments against expected payments and invoices, this field
428 /// is not used in LDK for received payments, and can be used to store arbitrary data in
429 /// invoices which will be received with the payment.
431 /// Note that this field was added to the lightning specification more recently than
432 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
433 /// may not be supported as universally.
434 pub payment_metadata: Option<Vec<u8>>,
437 impl_writeable_tlv_based!(RecipientOnionFields, {
438 (0, payment_secret, option),
439 (2, payment_metadata, option),
442 impl RecipientOnionFields {
443 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
444 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
445 /// but do not require or provide any further data.
446 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
447 Self { payment_secret: Some(payment_secret), payment_metadata: None }
450 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
451 /// payable HTLCs except for spontaneous payments, i.e. this should generally only be used for
452 /// calls to [`ChannelManager::send_spontaneous_payment`].
454 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
455 pub fn spontaneous_empty() -> Self {
456 Self { payment_secret: None, payment_metadata: None }
459 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
460 /// have to make sure that some fields match exactly across the parts. For those that aren't
461 /// required to match, if they don't match we should remove them so as to not expose data
462 /// that's dependent on the HTLC receive order to users.
464 /// Here we implement this, first checking compatibility then mutating two objects and then
465 /// dropping any remaining non-matching fields from both.
466 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
467 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
468 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
469 // For custom TLVs we should just drop non-matching ones, but not reject the payment.
474 pub(super) struct OutboundPayments {
475 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
476 pub(super) retry_lock: Mutex<()>,
479 impl OutboundPayments {
480 pub(super) fn new() -> Self {
482 pending_outbound_payments: Mutex::new(HashMap::new()),
483 retry_lock: Mutex::new(()),
487 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
488 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
489 retry_strategy: Retry, route_params: RouteParameters, router: &R,
490 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
491 node_signer: &NS, best_block_height: u32, logger: &L,
492 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP,
493 ) -> Result<(), RetryableSendFailure>
496 ES::Target: EntropySource,
497 NS::Target: NodeSigner,
499 IH: Fn() -> InFlightHtlcs,
500 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
501 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
503 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
504 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
505 best_block_height, logger, pending_events, &send_payment_along_path)
508 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
509 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
510 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
511 send_payment_along_path: F
512 ) -> Result<(), PaymentSendFailure>
514 ES::Target: EntropySource,
515 NS::Target: NodeSigner,
516 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
517 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
519 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)?;
520 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
521 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
522 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
525 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
526 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
527 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
528 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
529 node_signer: &NS, best_block_height: u32, logger: &L,
530 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP
531 ) -> Result<PaymentHash, RetryableSendFailure>
534 ES::Target: EntropySource,
535 NS::Target: NodeSigner,
537 IH: Fn() -> InFlightHtlcs,
538 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
539 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
541 let preimage = payment_preimage
542 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
543 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
544 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
545 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
546 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
547 .map(|()| payment_hash)
550 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
551 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
552 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
553 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
554 ) -> Result<PaymentHash, PaymentSendFailure>
556 ES::Target: EntropySource,
557 NS::Target: NodeSigner,
558 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
559 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
561 let preimage = payment_preimage
562 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
563 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
564 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
565 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
567 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
568 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
570 Ok(()) => Ok(payment_hash),
572 self.remove_outbound_if_all_failed(payment_id, &e);
578 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
579 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
580 best_block_height: u32, pending_events: &Mutex<Vec<events::Event>>, logger: &L,
581 send_payment_along_path: SP,
585 ES::Target: EntropySource,
586 NS::Target: NodeSigner,
587 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
588 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
589 IH: Fn() -> InFlightHtlcs,
590 FH: Fn() -> Vec<ChannelDetails>,
593 let _single_thread = self.retry_lock.lock().unwrap();
595 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
596 let mut retry_id_route_params = None;
597 for (pmt_id, pmt) in outbounds.iter_mut() {
598 if pmt.is_auto_retryable_now() {
599 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, .. } = pmt {
600 if pending_amt_msat < total_msat {
601 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
602 final_value_msat: *total_msat - *pending_amt_msat,
603 payment_params: params.clone(),
607 } else { debug_assert!(false); }
610 core::mem::drop(outbounds);
611 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
612 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)
616 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
617 outbounds.retain(|pmt_id, pmt| {
618 let mut retain = true;
619 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 {
620 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
621 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
622 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
624 payment_hash: *payment_hash,
634 pub(super) fn needs_abandon(&self) -> bool {
635 let outbounds = self.pending_outbound_payments.lock().unwrap();
636 outbounds.iter().any(|(_, pmt)|
637 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled())
640 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
641 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
643 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
644 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
645 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
646 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
647 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
648 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
649 node_signer: &NS, best_block_height: u32, logger: &L,
650 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: SP,
651 ) -> Result<(), RetryableSendFailure>
654 ES::Target: EntropySource,
655 NS::Target: NodeSigner,
657 IH: Fn() -> InFlightHtlcs,
658 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
659 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
661 #[cfg(feature = "std")] {
662 if has_expired(&route_params) {
663 return Err(RetryableSendFailure::PaymentExpired)
667 let route = router.find_route_with_id(
668 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
669 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
670 payment_hash, payment_id,
671 ).map_err(|_| RetryableSendFailure::RouteNotFound)?;
673 let onion_session_privs = self.add_new_pending_payment(payment_hash,
674 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
675 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
676 .map_err(|_| RetryableSendFailure::DuplicatePayment)?;
678 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, None, payment_id, None,
679 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
680 log_info!(logger, "Result sending payment with id {}: {:?}", log_bytes!(payment_id.0), res);
681 if let Err(e) = res {
682 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);
687 fn retry_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
688 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
689 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
690 node_signer: &NS, best_block_height: u32, logger: &L,
691 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: &SP,
695 ES::Target: EntropySource,
696 NS::Target: NodeSigner,
698 IH: Fn() -> InFlightHtlcs,
699 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
700 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
702 #[cfg(feature = "std")] {
703 if has_expired(&route_params) {
704 log_error!(logger, "Payment params expired on retry, abandoning payment {}", log_bytes!(payment_id.0));
705 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
710 let route = match router.find_route_with_id(
711 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
712 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs(),
713 payment_hash, payment_id,
717 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", log_bytes!(payment_id.0), e);
718 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
722 for path in route.paths.iter() {
724 log_error!(logger, "length-0 path in route");
725 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
730 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
731 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
732 for _ in 0..route.paths.len() {
733 onion_session_privs.push(entropy_source.get_secure_random_bytes());
736 macro_rules! abandon_with_entry {
737 ($payment: expr, $reason: expr) => {
738 $payment.get_mut().mark_abandoned($reason);
739 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
740 if $payment.get().remaining_parts() == 0 {
741 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
751 let (total_msat, recipient_onion, keysend_preimage) = {
752 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
753 match outbounds.entry(payment_id) {
754 hash_map::Entry::Occupied(mut payment) => {
755 let res = match payment.get() {
756 PendingOutboundPayment::Retryable {
757 total_msat, keysend_preimage, payment_secret, payment_metadata, pending_amt_msat, ..
759 let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
760 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
761 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);
762 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
765 (*total_msat, RecipientOnionFields {
766 payment_secret: *payment_secret,
767 payment_metadata: payment_metadata.clone(),
768 }, *keysend_preimage)
770 PendingOutboundPayment::Legacy { .. } => {
771 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
774 PendingOutboundPayment::Fulfilled { .. } => {
775 log_error!(logger, "Payment already completed");
778 PendingOutboundPayment::Abandoned { .. } => {
779 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
783 if !payment.get().is_retryable_now() {
784 log_error!(logger, "Retries exhausted for payment id {}", log_bytes!(payment_id.0));
785 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
788 payment.get_mut().increment_attempts();
789 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
790 assert!(payment.get_mut().insert(*session_priv_bytes, path));
794 hash_map::Entry::Vacant(_) => {
795 log_error!(logger, "Payment with ID {} not found", log_bytes!(payment_id.0));
800 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
801 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
802 &send_payment_along_path);
803 log_info!(logger, "Result retrying payment id {}: {:?}", log_bytes!(payment_id.0), res);
804 if let Err(e) = res {
805 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);
809 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
810 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
811 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
812 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
813 pending_events: &Mutex<Vec<events::Event>>, send_payment_along_path: &SP,
817 ES::Target: EntropySource,
818 NS::Target: NodeSigner,
820 IH: Fn() -> InFlightHtlcs,
821 SP: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
822 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
825 PaymentSendFailure::AllFailedResendSafe(errs) => {
826 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);
827 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);
829 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
830 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
831 // Some paths were sent, even if we failed to send the full MPP value our recipient may
832 // misbehave and claim the funds, at which point we have to consider the payment sent, so
833 // return `Ok()` here, ignoring any retry errors.
834 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);
836 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
837 // This may happen if we send a payment and some paths fail, but only due to a temporary
838 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
839 // initial HTLC-Add messages yet.
841 PaymentSendFailure::PathParameterError(results) => {
842 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
843 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
844 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
846 PaymentSendFailure::ParameterError(e) => {
847 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
848 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
850 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
854 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
855 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
856 paths: Vec<Vec<RouteHop>>, path_results: I, logger: &L, pending_events: &Mutex<Vec<events::Event>>
857 ) where L::Target: Logger {
858 let mut events = pending_events.lock().unwrap();
859 debug_assert_eq!(paths.len(), path_results.len());
860 for (path, path_res) in paths.into_iter().zip(path_results) {
861 if let Err(e) = path_res {
862 if let APIError::MonitorUpdateInProgress = e { continue }
863 log_error!(logger, "Failed to send along path due to error: {:?}", e);
864 let mut failed_scid = None;
865 if let APIError::ChannelUnavailable { .. } = e {
866 let scid = path[0].short_channel_id;
867 failed_scid = Some(scid);
868 route_params.payment_params.previously_failed_channels.push(scid);
870 events.push(events::Event::PaymentPathFailed {
871 payment_id: Some(payment_id),
873 payment_failed_permanently: false,
874 failure: events::PathFailure::InitialSend { err: e },
876 short_channel_id: failed_scid,
886 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
887 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
888 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
889 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
891 ES::Target: EntropySource,
892 NS::Target: NodeSigner,
893 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
894 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
896 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
898 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
901 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
902 err: "No need probing a path with less than two hops".to_string()
906 let route = Route { paths: vec![hops], payment_params: None };
907 let onion_session_privs = self.add_new_pending_payment(payment_hash,
908 RecipientOnionFields::spontaneous_empty(), payment_id, None, &route, None, None,
909 entropy_source, best_block_height)?;
911 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
912 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
914 Ok(()) => Ok((payment_hash, payment_id)),
916 self.remove_outbound_if_all_failed(payment_id, &e);
923 pub(super) fn test_set_payment_metadata(
924 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
926 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
927 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
928 *payment_metadata = new_payment_metadata;
930 _ => panic!("Need a retryable payment to update metadata on"),
935 pub(super) fn test_add_new_pending_payment<ES: Deref>(
936 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
937 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
938 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
939 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
942 pub(super) fn add_new_pending_payment<ES: Deref>(
943 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
944 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
945 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
946 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
947 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
948 for _ in 0..route.paths.len() {
949 onion_session_privs.push(entropy_source.get_secure_random_bytes());
952 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
953 match pending_outbounds.entry(payment_id) {
954 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
955 hash_map::Entry::Vacant(entry) => {
956 let payment = entry.insert(PendingOutboundPayment::Retryable {
958 attempts: PaymentAttempts::new(),
960 session_privs: HashSet::new(),
962 pending_fee_msat: Some(0),
964 payment_secret: recipient_onion.payment_secret,
965 payment_metadata: recipient_onion.payment_metadata,
967 starting_block_height: best_block_height,
968 total_msat: route.get_total_amount(),
971 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
972 assert!(payment.insert(*session_priv_bytes, path));
975 Ok(onion_session_privs)
980 fn pay_route_internal<NS: Deref, F>(
981 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
982 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
983 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
984 send_payment_along_path: &F
985 ) -> Result<(), PaymentSendFailure>
987 NS::Target: NodeSigner,
988 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
989 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
991 if route.paths.len() < 1 {
992 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
994 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1 {
995 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
997 let mut total_value = 0;
998 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
999 let mut path_errs = Vec::with_capacity(route.paths.len());
1000 'path_check: for path in route.paths.iter() {
1001 if path.len() < 1 || path.len() > 20 {
1002 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1003 continue 'path_check;
1005 for (idx, hop) in path.iter().enumerate() {
1006 if idx != path.len() - 1 && hop.pubkey == our_node_id {
1007 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1008 continue 'path_check;
1011 total_value += path.last().unwrap().fee_msat;
1012 path_errs.push(Ok(()));
1014 if path_errs.iter().any(|e| e.is_err()) {
1015 return Err(PaymentSendFailure::PathParameterError(path_errs));
1017 if let Some(amt_msat) = recv_value_msat {
1018 total_value = amt_msat;
1021 let cur_height = best_block_height + 1;
1022 let mut results = Vec::new();
1023 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1024 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1025 let mut path_res = send_payment_along_path(&path, &payment_hash, recipient_onion.clone(),
1026 total_value, cur_height, payment_id, &keysend_preimage, session_priv);
1029 Err(APIError::MonitorUpdateInProgress) => {
1030 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1031 // considered "in flight" and we shouldn't remove it from the
1032 // PendingOutboundPayment set.
1035 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1036 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1037 let removed = payment.remove(&session_priv, Some(path));
1038 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1040 debug_assert!(false, "This can't happen as the payment was added by callers");
1041 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1045 results.push(path_res);
1047 let mut has_ok = false;
1048 let mut has_err = false;
1049 let mut pending_amt_unsent = 0;
1050 for (res, path) in results.iter().zip(route.paths.iter()) {
1051 if res.is_ok() { has_ok = true; }
1052 if res.is_err() { has_err = true; }
1053 if let &Err(APIError::MonitorUpdateInProgress) = res {
1054 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1058 } else if res.is_err() {
1059 pending_amt_unsent += path.last().unwrap().fee_msat;
1062 if has_err && has_ok {
1063 Err(PaymentSendFailure::PartialFailure {
1066 failed_paths_retry: if pending_amt_unsent != 0 {
1067 if let Some(payment_params) = &route.payment_params {
1068 Some(RouteParameters {
1069 payment_params: payment_params.clone(),
1070 final_value_msat: pending_amt_unsent,
1076 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1083 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1084 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1085 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1086 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1087 send_payment_along_path: F
1088 ) -> Result<(), PaymentSendFailure>
1090 NS::Target: NodeSigner,
1091 F: Fn(&Vec<RouteHop>, &PaymentHash, RecipientOnionFields, u64, u32, PaymentId,
1092 &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
1094 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1095 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1096 &send_payment_along_path)
1097 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1100 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1101 // map as the payment is free to be resent.
1102 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1103 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1104 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1105 debug_assert!(removed, "We should always have a pending payment to remove here");
1109 pub(super) fn claim_htlc<L: Deref>(
1110 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1111 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
1112 ) where L::Target: Logger {
1113 let mut session_priv_bytes = [0; 32];
1114 session_priv_bytes.copy_from_slice(&session_priv[..]);
1115 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1116 let mut pending_events = pending_events.lock().unwrap();
1117 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1118 if !payment.get().is_fulfilled() {
1119 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1120 let fee_paid_msat = payment.get().get_pending_fee_msat();
1121 pending_events.push(
1122 events::Event::PaymentSent {
1123 payment_id: Some(payment_id),
1129 payment.get_mut().mark_fulfilled();
1133 // We currently immediately remove HTLCs which were fulfilled on-chain.
1134 // This could potentially lead to removing a pending payment too early,
1135 // with a reorg of one block causing us to re-add the fulfilled payment on
1137 // TODO: We should have a second monitor event that informs us of payments
1138 // irrevocably fulfilled.
1139 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1140 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1141 pending_events.push(
1142 events::Event::PaymentPathSuccessful {
1151 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
1155 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
1156 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1157 let mut pending_events = pending_events.lock().unwrap();
1158 for source in sources {
1159 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1160 let mut session_priv_bytes = [0; 32];
1161 session_priv_bytes.copy_from_slice(&session_priv[..]);
1162 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1163 assert!(payment.get().is_fulfilled());
1164 if payment.get_mut().remove(&session_priv_bytes, None) {
1165 pending_events.push(
1166 events::Event::PaymentPathSuccessful {
1168 payment_hash: payment.get().payment_hash(),
1178 pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
1179 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1180 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1181 // this could race the user making a duplicate send_payment call and our idempotency
1182 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1183 // removal. This should be more than sufficient to ensure the idempotency of any
1184 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1186 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1187 let pending_events = pending_events.lock().unwrap();
1188 pending_outbound_payments.retain(|payment_id, payment| {
1189 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1190 let mut no_remaining_entries = session_privs.is_empty();
1191 if no_remaining_entries {
1192 for ev in pending_events.iter() {
1194 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1195 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1196 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1197 if payment_id == ev_payment_id {
1198 no_remaining_entries = false;
1206 if no_remaining_entries {
1207 *timer_ticks_without_htlcs += 1;
1208 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1210 *timer_ticks_without_htlcs = 0;
1217 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1218 pub(super) fn fail_htlc<L: Deref>(
1219 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1220 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
1221 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1222 pending_events: &Mutex<Vec<events::Event>>, logger: &L
1223 ) -> bool where L::Target: Logger {
1225 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1227 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1229 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1230 let mut session_priv_bytes = [0; 32];
1231 session_priv_bytes.copy_from_slice(&session_priv[..]);
1232 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1234 // If any payments already need retry, there's no need to generate a redundant
1235 // `PendingHTLCsForwardable`.
1236 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1237 let mut awaiting_retry = false;
1238 if pmt.is_auto_retryable_now() {
1239 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1240 if pending_amt_msat < total_msat {
1241 awaiting_retry = true;
1248 let mut full_failure_ev = None;
1249 let mut pending_retry_ev = false;
1250 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1251 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1252 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1255 if payment.get().is_fulfilled() {
1256 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
1259 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1260 if let Some(scid) = short_channel_id {
1261 // TODO: If we decided to blame ourselves (or one of our channels) in
1262 // process_onion_failure we should close that channel as it implies our
1263 // next-hop is needlessly blaming us!
1264 payment.get_mut().insert_previously_failed_scid(scid);
1267 if payment_is_probe || !is_retryable_now || !payment_retryable {
1268 let reason = if !payment_retryable {
1269 PaymentFailureReason::RecipientRejected
1271 PaymentFailureReason::RetriesExhausted
1273 payment.get_mut().mark_abandoned(reason);
1274 is_retryable_now = false;
1276 if payment.get().remaining_parts() == 0 {
1277 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1278 if !payment_is_probe {
1279 full_failure_ev = Some(events::Event::PaymentFailed {
1280 payment_id: *payment_id,
1281 payment_hash: *payment_hash,
1290 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1293 core::mem::drop(outbounds);
1294 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
1296 let path_failure = {
1297 if payment_is_probe {
1298 if !payment_retryable {
1299 events::Event::ProbeSuccessful {
1300 payment_id: *payment_id,
1301 payment_hash: payment_hash.clone(),
1305 events::Event::ProbeFailed {
1306 payment_id: *payment_id,
1307 payment_hash: payment_hash.clone(),
1313 // If we miss abandoning the payment above, we *must* generate an event here or else the
1314 // payment will sit in our outbounds forever.
1315 if attempts_remaining && !already_awaiting_retry {
1316 debug_assert!(full_failure_ev.is_none());
1317 pending_retry_ev = true;
1319 events::Event::PaymentPathFailed {
1320 payment_id: Some(*payment_id),
1321 payment_hash: payment_hash.clone(),
1322 payment_failed_permanently: !payment_retryable,
1323 failure: events::PathFailure::OnPath { network_update },
1327 error_code: onion_error_code,
1329 error_data: onion_error_data
1333 let mut pending_events = pending_events.lock().unwrap();
1334 pending_events.push(path_failure);
1335 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1339 pub(super) fn abandon_payment(
1340 &self, payment_id: PaymentId, reason: PaymentFailureReason, pending_events: &Mutex<Vec<events::Event>>
1342 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1343 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1344 payment.get_mut().mark_abandoned(reason);
1345 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1346 if payment.get().remaining_parts() == 0 {
1347 pending_events.lock().unwrap().push(events::Event::PaymentFailed {
1349 payment_hash: *payment_hash,
1359 pub fn has_pending_payments(&self) -> bool {
1360 !self.pending_outbound_payments.lock().unwrap().is_empty()
1364 pub fn clear_pending_payments(&self) {
1365 self.pending_outbound_payments.lock().unwrap().clear()
1369 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1371 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1372 probing_cookie_secret: [u8; 32]) -> bool
1374 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1375 target_payment_hash == *payment_hash
1378 /// Returns the 'probing cookie' for the given [`PaymentId`].
1379 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1380 let mut preimage = [0u8; 64];
1381 preimage[..32].copy_from_slice(&probing_cookie_secret);
1382 preimage[32..].copy_from_slice(&payment_id.0);
1383 PaymentHash(Sha256::hash(&preimage).into_inner())
1386 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1388 (0, session_privs, required),
1391 (0, session_privs, required),
1392 (1, payment_hash, option),
1393 (3, timer_ticks_without_htlcs, (default_value, 0)),
1396 (0, session_privs, required),
1397 (1, pending_fee_msat, option),
1398 (2, payment_hash, required),
1399 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1400 // never see it - `payment_params` was added here after the field was added/required.
1401 (3, payment_params, (option: ReadableArgs, 0)),
1402 (4, payment_secret, option),
1403 (5, keysend_preimage, option),
1404 (6, total_msat, required),
1405 (7, payment_metadata, option),
1406 (8, pending_amt_msat, required),
1407 (10, starting_block_height, required),
1408 (not_written, retry_strategy, (static_value, None)),
1409 (not_written, attempts, (static_value, PaymentAttempts::new())),
1412 (0, session_privs, required),
1413 (1, reason, option),
1414 (2, payment_hash, required),
1420 use bitcoin::network::constants::Network;
1421 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1423 use crate::events::{Event, PathFailure, PaymentFailureReason};
1424 use crate::ln::PaymentHash;
1425 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1426 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1427 use crate::ln::msgs::{ErrorAction, LightningError};
1428 use crate::ln::outbound_payment::{OutboundPayments, Retry, RetryableSendFailure};
1429 use crate::routing::gossip::NetworkGraph;
1430 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters};
1431 use crate::sync::{Arc, Mutex};
1432 use crate::util::errors::APIError;
1433 use crate::util::test_utils;
1436 #[cfg(feature = "std")]
1437 fn fails_paying_after_expiration() {
1438 do_fails_paying_after_expiration(false);
1439 do_fails_paying_after_expiration(true);
1441 #[cfg(feature = "std")]
1442 fn do_fails_paying_after_expiration(on_retry: bool) {
1443 let outbound_payments = OutboundPayments::new();
1444 let logger = test_utils::TestLogger::new();
1445 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1446 let scorer = Mutex::new(test_utils::TestScorer::new());
1447 let router = test_utils::TestRouter::new(network_graph, &scorer);
1448 let secp_ctx = Secp256k1::new();
1449 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1451 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1452 let payment_params = PaymentParameters::from_node_id(
1453 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1455 ).with_expiry_time(past_expiry_time);
1456 let expired_route_params = RouteParameters {
1458 final_value_msat: 0,
1460 let pending_events = Mutex::new(Vec::new());
1462 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1463 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1464 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1465 &&keys_manager, 0).unwrap();
1466 outbound_payments.retry_payment_internal(
1467 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1468 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1469 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1470 let events = pending_events.lock().unwrap();
1471 assert_eq!(events.len(), 1);
1472 if let Event::PaymentFailed { ref reason, .. } = events[0] {
1473 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1474 } else { panic!("Unexpected event"); }
1476 let err = outbound_payments.send_payment(
1477 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1478 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1479 &&keys_manager, &&keys_manager, 0, &&logger,
1480 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1481 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1486 fn find_route_error() {
1487 do_find_route_error(false);
1488 do_find_route_error(true);
1490 fn do_find_route_error(on_retry: bool) {
1491 let outbound_payments = OutboundPayments::new();
1492 let logger = test_utils::TestLogger::new();
1493 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1494 let scorer = Mutex::new(test_utils::TestScorer::new());
1495 let router = test_utils::TestRouter::new(network_graph, &scorer);
1496 let secp_ctx = Secp256k1::new();
1497 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1499 let payment_params = PaymentParameters::from_node_id(
1500 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1501 let route_params = RouteParameters {
1503 final_value_msat: 0,
1505 router.expect_find_route(route_params.clone(),
1506 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1508 let pending_events = Mutex::new(Vec::new());
1510 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1511 PaymentId([0; 32]), None, &Route { paths: vec![], payment_params: None },
1512 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1513 &&keys_manager, 0).unwrap();
1514 outbound_payments.retry_payment_internal(
1515 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1516 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger,
1517 &pending_events, &|_, _, _, _, _, _, _, _| Ok(()));
1518 let events = pending_events.lock().unwrap();
1519 assert_eq!(events.len(), 1);
1520 if let Event::PaymentFailed { .. } = events[0] { } else { panic!("Unexpected event"); }
1522 let err = outbound_payments.send_payment(
1523 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1524 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1525 &&keys_manager, &&keys_manager, 0, &&logger,
1526 &pending_events, |_, _, _, _, _, _, _, _| Ok(())).unwrap_err();
1527 if let RetryableSendFailure::RouteNotFound = err {
1528 } else { panic!("Unexpected error"); }
1533 fn initial_send_payment_path_failed_evs() {
1534 let outbound_payments = OutboundPayments::new();
1535 let logger = test_utils::TestLogger::new();
1536 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1537 let scorer = Mutex::new(test_utils::TestScorer::new());
1538 let router = test_utils::TestRouter::new(network_graph, &scorer);
1539 let secp_ctx = Secp256k1::new();
1540 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1542 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1543 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1544 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1545 let route_params = RouteParameters {
1546 payment_params: payment_params.clone(),
1547 final_value_msat: 0,
1549 let failed_scid = 42;
1551 paths: vec![vec![RouteHop {
1552 pubkey: receiver_pk,
1553 node_features: NodeFeatures::empty(),
1554 short_channel_id: failed_scid,
1555 channel_features: ChannelFeatures::empty(),
1557 cltv_expiry_delta: 0,
1559 payment_params: Some(payment_params),
1561 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1562 let mut route_params_w_failed_scid = route_params.clone();
1563 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1564 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1565 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1566 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1568 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1569 // PaymentPathFailed event.
1570 let pending_events = Mutex::new(Vec::new());
1571 outbound_payments.send_payment(
1572 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1573 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1574 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1575 |_, _, _, _, _, _, _, _| Err(APIError::ChannelUnavailable { err: "test".to_owned() }))
1577 let mut events = pending_events.lock().unwrap();
1578 assert_eq!(events.len(), 2);
1579 if let Event::PaymentPathFailed {
1581 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0]
1583 assert_eq!(short_channel_id, Some(failed_scid));
1584 } else { panic!("Unexpected event"); }
1585 if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }
1587 core::mem::drop(events);
1589 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1590 outbound_payments.send_payment(
1591 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1592 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1593 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1594 |_, _, _, _, _, _, _, _| Err(APIError::MonitorUpdateInProgress)).unwrap();
1595 assert_eq!(pending_events.lock().unwrap().len(), 0);
1597 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1598 outbound_payments.send_payment(
1599 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1600 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1601 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1602 |_, _, _, _, _, _, _, _| Err(APIError::APIMisuseError { err: "test".to_owned() }))
1604 let events = pending_events.lock().unwrap();
1605 assert_eq!(events.len(), 2);
1606 if let Event::PaymentPathFailed {
1608 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0]
1610 assert_eq!(short_channel_id, None);
1611 } else { panic!("Unexpected event"); }
1612 if let Event::PaymentFailed { .. } = events[1] { } else { panic!("Unexpected event"); }