1 // This file is Copyright its original authors, visible in version control
4 // This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
5 // or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
7 // You may not use this file except in accordance with one or both of these
10 //! Utilities to send payments and manage outbound payment information.
12 use bitcoin::hashes::Hash;
13 use bitcoin::hashes::sha256::Hash as Sha256;
14 use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
16 use crate::chain::keysinterface::{EntropySource, NodeSigner, Recipient};
17 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
18 use crate::ln::channelmanager::{ChannelDetails, HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, MIN_HTLC_RELAY_HOLDING_CELL_MILLIS, PaymentId};
19 use crate::ln::msgs::DecodeError;
20 use crate::ln::onion_utils::HTLCFailReason;
21 use crate::routing::router::{InFlightHtlcs, PaymentParameters, Route, RouteHop, RouteParameters, RoutePath, Router};
22 use crate::util::errors::APIError;
23 use crate::util::events;
24 use crate::util::logger::Logger;
25 use crate::util::time::Time;
26 #[cfg(all(not(feature = "no-std"), test))]
27 use crate::util::time::tests::SinceEpoch;
30 use core::fmt::{self, Display, Formatter};
32 use core::time::Duration;
34 use crate::prelude::*;
35 use crate::sync::Mutex;
37 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
38 /// and later, also stores information for retrying the payment.
39 pub(crate) enum PendingOutboundPayment {
41 session_privs: HashSet<[u8; 32]>,
44 retry_strategy: Retry,
45 attempts: PaymentAttempts,
46 route_params: Option<RouteParameters>,
47 session_privs: HashSet<[u8; 32]>,
48 payment_hash: PaymentHash,
49 payment_secret: Option<PaymentSecret>,
50 pending_amt_msat: u64,
51 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
52 pending_fee_msat: Option<u64>,
53 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
55 /// Our best known block height at the time this payment was initiated.
56 starting_block_height: u32,
58 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
59 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
60 /// and add a pending payment that was already fulfilled.
62 session_privs: HashSet<[u8; 32]>,
63 payment_hash: Option<PaymentHash>,
64 timer_ticks_without_htlcs: u8,
66 /// When a payer gives up trying to retry a payment, they inform us, letting us generate a
67 /// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
68 /// conditions in MPP-aware payment retriers (1), where the possibility of multiple
69 /// `PaymentPathFailed` events with `all_paths_failed` can be pending at once, confusing a
70 /// downstream event handler as to when a payment has actually failed.
72 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
74 session_privs: HashSet<[u8; 32]>,
75 payment_hash: PaymentHash,
79 impl PendingOutboundPayment {
80 fn increment_attempts(&mut self) {
81 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
85 fn is_retryable_now(&self) -> bool {
86 if let PendingOutboundPayment::Retryable { retry_strategy, attempts, .. } = self {
87 return retry_strategy.is_retryable_now(&attempts)
91 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
92 if let PendingOutboundPayment::Retryable { route_params: Some(params), .. } = self {
93 params.payment_params.previously_failed_channels.push(scid);
96 pub(super) fn is_fulfilled(&self) -> bool {
98 PendingOutboundPayment::Fulfilled { .. } => true,
102 pub(super) fn abandoned(&self) -> bool {
104 PendingOutboundPayment::Abandoned { .. } => true,
108 fn get_pending_fee_msat(&self) -> Option<u64> {
110 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
115 fn payment_hash(&self) -> Option<PaymentHash> {
117 PendingOutboundPayment::Legacy { .. } => None,
118 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
119 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
120 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
124 fn mark_fulfilled(&mut self) {
125 let mut session_privs = HashSet::new();
126 core::mem::swap(&mut session_privs, match self {
127 PendingOutboundPayment::Legacy { session_privs } |
128 PendingOutboundPayment::Retryable { session_privs, .. } |
129 PendingOutboundPayment::Fulfilled { session_privs, .. } |
130 PendingOutboundPayment::Abandoned { session_privs, .. }
133 let payment_hash = self.payment_hash();
134 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
137 fn mark_abandoned(&mut self) -> Result<(), ()> {
138 let mut session_privs = HashSet::new();
139 let our_payment_hash;
140 core::mem::swap(&mut session_privs, match self {
141 PendingOutboundPayment::Legacy { .. } |
142 PendingOutboundPayment::Fulfilled { .. } =>
144 PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } |
145 PendingOutboundPayment::Abandoned { session_privs, payment_hash, .. } => {
146 our_payment_hash = *payment_hash;
150 *self = PendingOutboundPayment::Abandoned { session_privs, payment_hash: our_payment_hash };
154 /// panics if path is None and !self.is_fulfilled
155 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
156 let remove_res = match self {
157 PendingOutboundPayment::Legacy { session_privs } |
158 PendingOutboundPayment::Retryable { session_privs, .. } |
159 PendingOutboundPayment::Fulfilled { session_privs, .. } |
160 PendingOutboundPayment::Abandoned { session_privs, .. } => {
161 session_privs.remove(session_priv)
165 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
166 let path = path.expect("Fulfilling a payment should always come with a path");
167 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
168 *pending_amt_msat -= path_last_hop.fee_msat;
169 if let Some(fee_msat) = pending_fee_msat.as_mut() {
170 *fee_msat -= path.get_path_fees();
177 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
178 let insert_res = match self {
179 PendingOutboundPayment::Legacy { session_privs } |
180 PendingOutboundPayment::Retryable { session_privs, .. } => {
181 session_privs.insert(session_priv)
183 PendingOutboundPayment::Fulfilled { .. } => false,
184 PendingOutboundPayment::Abandoned { .. } => false,
187 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
188 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
189 *pending_amt_msat += path_last_hop.fee_msat;
190 if let Some(fee_msat) = pending_fee_msat.as_mut() {
191 *fee_msat += path.get_path_fees();
198 pub(super) fn remaining_parts(&self) -> usize {
200 PendingOutboundPayment::Legacy { session_privs } |
201 PendingOutboundPayment::Retryable { session_privs, .. } |
202 PendingOutboundPayment::Fulfilled { session_privs, .. } |
203 PendingOutboundPayment::Abandoned { session_privs, .. } => {
210 /// Strategies available to retry payment path failures.
211 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
213 /// Max number of attempts to retry payment.
215 /// Note that this is the number of *path* failures, not full payment retries. For multi-path
216 /// payments, if this is less than the total number of paths, we will never even retry all of the
219 #[cfg(not(feature = "no-std"))]
220 /// Time elapsed before abandoning retries for a payment.
221 Timeout(core::time::Duration),
225 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
226 match (self, attempts) {
227 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
228 max_retry_count > count
230 #[cfg(all(not(feature = "no-std"), not(test)))]
231 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
232 *max_duration >= std::time::Instant::now().duration_since(*first_attempted_at),
233 #[cfg(all(not(feature = "no-std"), test))]
234 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
235 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
240 #[cfg(feature = "std")]
241 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
242 if let Some(expiry_time) = route_params.payment_params.expiry_time {
243 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
244 return elapsed > core::time::Duration::from_secs(expiry_time)
250 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
252 /// Storing minimal payment attempts information required for determining if a outbound payment can
254 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
255 /// This count will be incremented only after the result of the attempt is known. When it's 0,
256 /// it means the result of the first attempt is not known yet.
257 pub(crate) count: usize,
258 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
259 first_attempted_at: T
262 #[cfg(not(any(feature = "no-std", test)))]
263 type ConfiguredTime = std::time::Instant;
264 #[cfg(feature = "no-std")]
265 type ConfiguredTime = crate::util::time::Eternity;
266 #[cfg(all(not(feature = "no-std"), test))]
267 type ConfiguredTime = SinceEpoch;
269 impl<T: Time> PaymentAttemptsUsingTime<T> {
270 pub(crate) fn new() -> Self {
271 PaymentAttemptsUsingTime {
273 first_attempted_at: T::now()
278 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
279 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
280 #[cfg(feature = "no-std")]
281 return write!(f, "attempts: {}", self.count);
282 #[cfg(not(feature = "no-std"))]
285 "attempts: {}, duration: {}s",
287 T::now().duration_since(self.first_attempted_at).as_secs()
292 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
293 /// Err() type describing which state the payment is in, see the description of individual enum
295 #[derive(Clone, Debug)]
296 pub enum PaymentSendFailure {
297 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
298 /// send the payment at all.
300 /// You can freely resend the payment in full (with the parameter error fixed).
302 /// Because the payment failed outright, no payment tracking is done, you do not need to call
303 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
304 /// for this payment.
306 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
307 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
308 ParameterError(APIError),
309 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
310 /// from attempting to send the payment at all.
312 /// You can freely resend the payment in full (with the parameter error fixed).
314 /// The results here are ordered the same as the paths in the route object which was passed to
317 /// Because the payment failed outright, no payment tracking is done, you do not need to call
318 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
319 /// for this payment.
321 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
322 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
323 PathParameterError(Vec<Result<(), APIError>>),
324 /// All paths which were attempted failed to send, with no channel state change taking place.
325 /// You can freely resend the payment in full (though you probably want to do so over different
326 /// paths than the ones selected).
328 /// Because the payment failed outright, no payment tracking is done, you do not need to call
329 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
330 /// for this payment.
332 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
333 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
334 AllFailedResendSafe(Vec<APIError>),
335 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
336 /// yet completed (i.e. generated an [`Event::PaymentSent`]) or been abandoned (via
337 /// [`ChannelManager::abandon_payment`]).
339 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
340 /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
341 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
343 /// Some paths which were attempted failed to send, though possibly not all. At least some
344 /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
345 /// in over-/re-payment.
347 /// The results here are ordered the same as the paths in the route object which was passed to
348 /// send_payment, and any `Err`s which are not [`APIError::MonitorUpdateInProgress`] can be
349 /// safely retried via [`ChannelManager::retry_payment`].
351 /// Any entries which contain `Err(APIError::MonitorUpdateInprogress)` or `Ok(())` MUST NOT be
352 /// retried as they will result in over-/re-payment. These HTLCs all either successfully sent
353 /// (in the case of `Ok(())`) or will send once a [`MonitorEvent::Completed`] is provided for
354 /// the next-hop channel with the latest update_id.
356 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
357 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
359 /// The errors themselves, in the same order as the route hops.
360 results: Vec<Result<(), APIError>>,
361 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
362 /// contain a [`RouteParameters`] object which can be used to calculate a new route that
363 /// will pay all remaining unpaid balance.
364 failed_paths_retry: Option<RouteParameters>,
365 /// The payment id for the payment, which is now at least partially pending.
366 payment_id: PaymentId,
370 pub(super) struct OutboundPayments {
371 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
374 impl OutboundPayments {
375 pub(super) fn new() -> Self {
377 pending_outbound_payments: Mutex::new(HashMap::new())
381 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
382 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
383 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
384 send_payment_along_path: F
385 ) -> Result<(), PaymentSendFailure>
387 ES::Target: EntropySource,
388 NS::Target: NodeSigner,
389 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
390 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
392 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, route, Retry::Attempts(0), None, entropy_source, best_block_height)?;
393 self.send_payment_internal(route, payment_hash, payment_secret, None, payment_id, None,
394 onion_session_privs, node_signer, best_block_height, send_payment_along_path)
395 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
398 pub(super) fn send_spontaneous_payment<ES: Deref, NS: Deref, F>(
399 &self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
400 entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F
401 ) -> Result<PaymentHash, PaymentSendFailure>
403 ES::Target: EntropySource,
404 NS::Target: NodeSigner,
405 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
406 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
408 let preimage = match payment_preimage {
410 None => PaymentPreimage(entropy_source.get_secure_random_bytes()),
412 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
413 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, Retry::Attempts(0), None, entropy_source, best_block_height)?;
415 match self.send_payment_internal(route, payment_hash, &None, Some(preimage), payment_id, None, onion_session_privs, node_signer, best_block_height, send_payment_along_path) {
416 Ok(()) => Ok(payment_hash),
418 self.remove_outbound_if_all_failed(payment_id, &e);
424 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
425 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
426 best_block_height: u32, logger: &L, send_payment_along_path: SP,
430 ES::Target: EntropySource,
431 NS::Target: NodeSigner,
432 SP: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
433 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>,
434 IH: Fn() -> InFlightHtlcs,
435 FH: Fn() -> Vec<ChannelDetails>,
439 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
440 let mut retry_id_route_params = None;
441 for (pmt_id, pmt) in outbounds.iter_mut() {
442 if pmt.is_retryable_now() {
443 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, route_params: Some(params), .. } = pmt {
444 if pending_amt_msat < total_msat {
445 retry_id_route_params = Some((*pmt_id, params.clone()));
446 pmt.increment_attempts();
452 if let Some((payment_id, route_params)) = retry_id_route_params {
453 core::mem::drop(outbounds);
454 if let Err(e) = self.pay_internal(payment_id, route_params, router, first_hops(), inflight_htlcs(), entropy_source, node_signer, best_block_height, &send_payment_along_path) {
455 log_trace!(logger, "Errored retrying payment: {:?}", e);
461 fn pay_internal<R: Deref, NS: Deref, ES: Deref, F>(
462 &self, payment_id: PaymentId, route_params: RouteParameters, router: &R,
463 first_hops: Vec<ChannelDetails>, inflight_htlcs: InFlightHtlcs, entropy_source: &ES,
464 node_signer: &NS, best_block_height: u32, send_payment_along_path: &F
465 ) -> Result<(), PaymentSendFailure>
468 ES::Target: EntropySource,
469 NS::Target: NodeSigner,
470 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
471 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
473 #[cfg(feature = "std")] {
474 if has_expired(&route_params) {
475 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
476 err: format!("Invoice expired for payment id {}", log_bytes!(payment_id.0)),
481 let route = router.find_route(
482 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
483 Some(&first_hops.iter().collect::<Vec<_>>()), &inflight_htlcs
484 ).map_err(|e| PaymentSendFailure::ParameterError(APIError::APIMisuseError {
485 err: format!("Failed to find a route for payment {}: {:?}", log_bytes!(payment_id.0), e), // TODO: add APIError::RouteNotFound
488 let res = self.retry_payment_with_route(&route, payment_id, entropy_source, node_signer, best_block_height, send_payment_along_path);
490 Err(PaymentSendFailure::AllFailedResendSafe(_)) => {
491 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
492 if let Some(payment) = outbounds.get_mut(&payment_id) {
493 let retryable = payment.is_retryable_now();
495 payment.increment_attempts();
496 } else { return res }
497 } else { return res }
498 core::mem::drop(outbounds);
499 self.pay_internal(payment_id, route_params, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, send_payment_along_path)
501 Err(PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), results, .. }) => {
502 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
503 if let Some(payment) = outbounds.get_mut(&payment_id) {
504 let retryable = payment.is_retryable_now();
506 payment.increment_attempts();
507 } else { return Err(PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), results, payment_id }) }
508 } else { return Err(PaymentSendFailure::PartialFailure { failed_paths_retry: Some(retry), results, payment_id }) }
509 core::mem::drop(outbounds);
511 // Some paths were sent, even if we failed to send the full MPP value our recipient may
512 // misbehave and claim the funds, at which point we have to consider the payment sent, so
513 // return `Ok()` here, ignoring any retry errors.
514 let _ = self.pay_internal(payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, send_payment_along_path);
517 Err(PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. }) => {
518 // This may happen if we send a payment and some paths fail, but only due to a temporary
519 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
520 // initial HTLC-Add messages yet.
527 pub(super) fn retry_payment_with_route<ES: Deref, NS: Deref, F>(
528 &self, route: &Route, payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
529 send_payment_along_path: F
530 ) -> Result<(), PaymentSendFailure>
532 ES::Target: EntropySource,
533 NS::Target: NodeSigner,
534 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
535 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
537 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
538 for path in route.paths.iter() {
540 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
541 err: "length-0 path in route".to_string()
546 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
547 for _ in 0..route.paths.len() {
548 onion_session_privs.push(entropy_source.get_secure_random_bytes());
551 let (total_msat, payment_hash, payment_secret) = {
552 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
553 match outbounds.get_mut(&payment_id) {
555 let res = match payment {
556 PendingOutboundPayment::Retryable {
557 total_msat, payment_hash, payment_secret, pending_amt_msat, ..
559 let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
560 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
561 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
562 err: format!("retry_amt_msat of {} will put pending_amt_msat (currently: {}) more than 10% over total_payment_amt_msat of {}", retry_amt_msat, pending_amt_msat, total_msat).to_string()
565 (*total_msat, *payment_hash, *payment_secret)
567 PendingOutboundPayment::Legacy { .. } => {
568 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
569 err: "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102".to_string()
572 PendingOutboundPayment::Fulfilled { .. } => {
573 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
574 err: "Payment already completed".to_owned()
577 PendingOutboundPayment::Abandoned { .. } => {
578 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
579 err: "Payment already abandoned (with some HTLCs still pending)".to_owned()
583 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
584 assert!(payment.insert(*session_priv_bytes, path));
589 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
590 err: format!("Payment with ID {} not found", log_bytes!(payment_id.0)),
594 self.send_payment_internal(route, payment_hash, &payment_secret, None, payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height, send_payment_along_path)
597 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
598 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
599 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
600 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
602 ES::Target: EntropySource,
603 NS::Target: NodeSigner,
604 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
605 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
607 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
609 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
612 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
613 err: "No need probing a path with less than two hops".to_string()
617 let route = Route { paths: vec![hops], payment_params: None };
618 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, Retry::Attempts(0), None, entropy_source, best_block_height)?;
620 match self.send_payment_internal(&route, payment_hash, &None, None, payment_id, None, onion_session_privs, node_signer, best_block_height, send_payment_along_path) {
621 Ok(()) => Ok((payment_hash, payment_id)),
623 self.remove_outbound_if_all_failed(payment_id, &e);
630 pub(super) fn test_add_new_pending_payment<ES: Deref>(
631 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
632 route: &Route, retry_strategy: Retry, entropy_source: &ES, best_block_height: u32
633 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
634 self.add_new_pending_payment(payment_hash, payment_secret, payment_id, route, retry_strategy, None, entropy_source, best_block_height)
637 pub(super) fn add_new_pending_payment<ES: Deref>(
638 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
639 route: &Route, retry_strategy: Retry, route_params: Option<RouteParameters>,
640 entropy_source: &ES, best_block_height: u32
641 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
642 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
643 for _ in 0..route.paths.len() {
644 onion_session_privs.push(entropy_source.get_secure_random_bytes());
647 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
648 match pending_outbounds.entry(payment_id) {
649 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
650 hash_map::Entry::Vacant(entry) => {
651 let payment = entry.insert(PendingOutboundPayment::Retryable {
653 attempts: PaymentAttempts::new(),
655 session_privs: HashSet::new(),
657 pending_fee_msat: Some(0),
660 starting_block_height: best_block_height,
661 total_msat: route.get_total_amount(),
664 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
665 assert!(payment.insert(*session_priv_bytes, path));
668 Ok(onion_session_privs)
673 fn send_payment_internal<NS: Deref, F>(
674 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
675 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
676 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
677 send_payment_along_path: F
678 ) -> Result<(), PaymentSendFailure>
680 NS::Target: NodeSigner,
681 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
682 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
684 if route.paths.len() < 1 {
685 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over"}));
687 if payment_secret.is_none() && route.paths.len() > 1 {
688 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_string()}));
690 let mut total_value = 0;
691 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
692 let mut path_errs = Vec::with_capacity(route.paths.len());
693 'path_check: for path in route.paths.iter() {
694 if path.len() < 1 || path.len() > 20 {
695 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size"}));
696 continue 'path_check;
698 for (idx, hop) in path.iter().enumerate() {
699 if idx != path.len() - 1 && hop.pubkey == our_node_id {
700 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us"}));
701 continue 'path_check;
704 total_value += path.last().unwrap().fee_msat;
705 path_errs.push(Ok(()));
707 if path_errs.iter().any(|e| e.is_err()) {
708 return Err(PaymentSendFailure::PathParameterError(path_errs));
710 if let Some(amt_msat) = recv_value_msat {
711 debug_assert!(amt_msat >= total_value);
712 total_value = amt_msat;
715 let cur_height = best_block_height + 1;
716 let mut results = Vec::new();
717 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
718 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
719 let mut path_res = send_payment_along_path(&path, &route.payment_params, &payment_hash, payment_secret, total_value, cur_height, payment_id, &keysend_preimage, session_priv);
722 Err(APIError::MonitorUpdateInProgress) => {
723 // While a MonitorUpdateInProgress is an Err(_), the payment is still
724 // considered "in flight" and we shouldn't remove it from the
725 // PendingOutboundPayment set.
728 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
729 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
730 let removed = payment.remove(&session_priv, Some(path));
731 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
733 debug_assert!(false, "This can't happen as the payment was added by callers");
734 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
738 results.push(path_res);
740 let mut has_ok = false;
741 let mut has_err = false;
742 let mut pending_amt_unsent = 0;
743 let mut max_unsent_cltv_delta = 0;
744 for (res, path) in results.iter().zip(route.paths.iter()) {
745 if res.is_ok() { has_ok = true; }
746 if res.is_err() { has_err = true; }
747 if let &Err(APIError::MonitorUpdateInProgress) = res {
748 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
752 } else if res.is_err() {
753 pending_amt_unsent += path.last().unwrap().fee_msat;
754 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
757 if has_err && has_ok {
758 Err(PaymentSendFailure::PartialFailure {
761 failed_paths_retry: if pending_amt_unsent != 0 {
762 if let Some(payment_params) = &route.payment_params {
763 Some(RouteParameters {
764 payment_params: payment_params.clone(),
765 final_value_msat: pending_amt_unsent,
766 final_cltv_expiry_delta: max_unsent_cltv_delta,
772 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
779 pub(super) fn test_send_payment_internal<NS: Deref, F>(
780 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
781 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
782 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
783 send_payment_along_path: F
784 ) -> Result<(), PaymentSendFailure>
786 NS::Target: NodeSigner,
787 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
788 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
790 self.send_payment_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id,
791 recv_value_msat, onion_session_privs, node_signer, best_block_height,
792 send_payment_along_path)
793 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
796 // If we failed to send any paths, we should remove the new PaymentId from the
797 // `pending_outbound_payments` map, as the user isn't expected to `abandon_payment`.
798 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
799 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
800 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
801 debug_assert!(removed, "We should always have a pending payment to remove here");
805 pub(super) fn claim_htlc<L: Deref>(
806 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
807 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
808 ) where L::Target: Logger {
809 let mut session_priv_bytes = [0; 32];
810 session_priv_bytes.copy_from_slice(&session_priv[..]);
811 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
812 let mut pending_events = pending_events.lock().unwrap();
813 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
814 if !payment.get().is_fulfilled() {
815 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
816 let fee_paid_msat = payment.get().get_pending_fee_msat();
818 events::Event::PaymentSent {
819 payment_id: Some(payment_id),
825 payment.get_mut().mark_fulfilled();
829 // We currently immediately remove HTLCs which were fulfilled on-chain.
830 // This could potentially lead to removing a pending payment too early,
831 // with a reorg of one block causing us to re-add the fulfilled payment on
833 // TODO: We should have a second monitor event that informs us of payments
834 // irrevocably fulfilled.
835 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
836 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
838 events::Event::PaymentPathSuccessful {
847 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
851 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
852 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
853 let mut pending_events = pending_events.lock().unwrap();
854 for source in sources {
855 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
856 let mut session_priv_bytes = [0; 32];
857 session_priv_bytes.copy_from_slice(&session_priv[..]);
858 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
859 assert!(payment.get().is_fulfilled());
860 if payment.get_mut().remove(&session_priv_bytes, None) {
862 events::Event::PaymentPathSuccessful {
864 payment_hash: payment.get().payment_hash(),
874 pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
875 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
876 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
877 // this could race the user making a duplicate send_payment call and our idempotency
878 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
879 // removal. This should be more than sufficient to ensure the idempotency of any
880 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
882 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
883 let pending_events = pending_events.lock().unwrap();
884 pending_outbound_payments.retain(|payment_id, payment| {
885 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
886 let mut no_remaining_entries = session_privs.is_empty();
887 if no_remaining_entries {
888 for ev in pending_events.iter() {
890 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
891 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
892 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
893 if payment_id == ev_payment_id {
894 no_remaining_entries = false;
902 if no_remaining_entries {
903 *timer_ticks_without_htlcs += 1;
904 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
906 *timer_ticks_without_htlcs = 0;
913 pub(super) fn fail_htlc<L: Deref>(
914 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
915 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
916 payment_params: &Option<PaymentParameters>, probing_cookie_secret: [u8; 32],
917 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
918 ) where L::Target: Logger {
920 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
922 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
924 let mut session_priv_bytes = [0; 32];
925 session_priv_bytes.copy_from_slice(&session_priv[..]);
926 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
927 let mut all_paths_failed = false;
928 let mut full_failure_ev = None;
929 let mut pending_retry_ev = None;
930 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
931 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
932 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
935 if payment.get().is_fulfilled() {
936 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
939 let is_retryable_now = payment.get().is_retryable_now();
940 if let Some(scid) = short_channel_id {
941 payment.get_mut().insert_previously_failed_scid(scid);
943 if payment.get().remaining_parts() == 0 {
944 all_paths_failed = true;
945 if payment.get().abandoned() {
946 full_failure_ev = Some(events::Event::PaymentFailed {
947 payment_id: *payment_id,
948 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
955 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
958 core::mem::drop(outbounds);
959 let mut retry = if let Some(payment_params_data) = payment_params {
960 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
961 Some(RouteParameters {
962 payment_params: payment_params_data.clone(),
963 final_value_msat: path_last_hop.fee_msat,
964 final_cltv_expiry_delta: path_last_hop.cltv_expiry_delta,
967 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
970 if payment_is_probe(payment_hash, &payment_id, probing_cookie_secret) {
971 if !payment_retryable {
972 events::Event::ProbeSuccessful {
973 payment_id: *payment_id,
974 payment_hash: payment_hash.clone(),
978 events::Event::ProbeFailed {
979 payment_id: *payment_id,
980 payment_hash: payment_hash.clone(),
986 // TODO: If we decided to blame ourselves (or one of our channels) in
987 // process_onion_failure we should close that channel as it implies our
988 // next-hop is needlessly blaming us!
989 if let Some(scid) = short_channel_id {
990 retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
992 if payment_retryable && attempts_remaining && retry.is_some() {
993 debug_assert!(full_failure_ev.is_none());
994 pending_retry_ev = Some(events::Event::PendingHTLCsForwardable {
995 time_forwardable: Duration::from_millis(MIN_HTLC_RELAY_HOLDING_CELL_MILLIS),
998 events::Event::PaymentPathFailed {
999 payment_id: Some(*payment_id),
1000 payment_hash: payment_hash.clone(),
1001 payment_failed_permanently: !payment_retryable,
1008 error_code: onion_error_code,
1010 error_data: onion_error_data
1014 let mut pending_events = pending_events.lock().unwrap();
1015 pending_events.push(path_failure);
1016 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
1017 if let Some(ev) = pending_retry_ev { pending_events.push(ev); }
1020 pub(super) fn abandon_payment(&self, payment_id: PaymentId) -> Option<events::Event> {
1021 let mut failed_ev = None;
1022 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1023 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1024 if let Ok(()) = payment.get_mut().mark_abandoned() {
1025 if payment.get().remaining_parts() == 0 {
1026 failed_ev = Some(events::Event::PaymentFailed {
1028 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
1038 pub fn has_pending_payments(&self) -> bool {
1039 !self.pending_outbound_payments.lock().unwrap().is_empty()
1043 pub fn clear_pending_payments(&self) {
1044 self.pending_outbound_payments.lock().unwrap().clear()
1048 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1050 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1051 probing_cookie_secret: [u8; 32]) -> bool
1053 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1054 target_payment_hash == *payment_hash
1057 /// Returns the 'probing cookie' for the given [`PaymentId`].
1058 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1059 let mut preimage = [0u8; 64];
1060 preimage[..32].copy_from_slice(&probing_cookie_secret);
1061 preimage[32..].copy_from_slice(&payment_id.0);
1062 PaymentHash(Sha256::hash(&preimage).into_inner())
1065 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1067 (0, session_privs, required),
1070 (0, session_privs, required),
1071 (1, payment_hash, option),
1072 (3, timer_ticks_without_htlcs, (default_value, 0)),
1075 (0, session_privs, required),
1076 (1, pending_fee_msat, option),
1077 (2, payment_hash, required),
1078 (not_written, retry_strategy, (static_value, Retry::Attempts(0))),
1079 (4, payment_secret, option),
1080 (not_written, attempts, (static_value, PaymentAttempts::new())),
1081 (6, total_msat, required),
1082 (not_written, route_params, (static_value, None)),
1083 (8, pending_amt_msat, required),
1084 (10, starting_block_height, required),
1087 (0, session_privs, required),
1088 (2, payment_hash, required),