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::{HTLCSource, IDEMPOTENCY_TIMEOUT_TICKS, PaymentId};
19 use crate::ln::msgs::DecodeError;
20 use crate::ln::onion_utils::HTLCFailReason;
21 use crate::routing::router::{PaymentParameters, Route, RouteHop, RouteParameters, RoutePath};
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};
33 use crate::prelude::*;
34 use crate::sync::Mutex;
36 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
37 /// and later, also stores information for retrying the payment.
38 pub(crate) enum PendingOutboundPayment {
40 session_privs: HashSet<[u8; 32]>,
43 session_privs: HashSet<[u8; 32]>,
44 payment_hash: PaymentHash,
45 payment_secret: Option<PaymentSecret>,
46 pending_amt_msat: u64,
47 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
48 pending_fee_msat: Option<u64>,
49 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
51 /// Our best known block height at the time this payment was initiated.
52 starting_block_height: u32,
54 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
55 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
56 /// and add a pending payment that was already fulfilled.
58 session_privs: HashSet<[u8; 32]>,
59 payment_hash: Option<PaymentHash>,
60 timer_ticks_without_htlcs: u8,
62 /// When a payer gives up trying to retry a payment, they inform us, letting us generate a
63 /// `PaymentFailed` event when all HTLCs have irrevocably failed. This avoids a number of race
64 /// conditions in MPP-aware payment retriers (1), where the possibility of multiple
65 /// `PaymentPathFailed` events with `all_paths_failed` can be pending at once, confusing a
66 /// downstream event handler as to when a payment has actually failed.
68 /// (1) <https://github.com/lightningdevkit/rust-lightning/issues/1164>
70 session_privs: HashSet<[u8; 32]>,
71 payment_hash: PaymentHash,
75 impl PendingOutboundPayment {
76 pub(super) fn is_fulfilled(&self) -> bool {
78 PendingOutboundPayment::Fulfilled { .. } => true,
82 pub(super) fn abandoned(&self) -> bool {
84 PendingOutboundPayment::Abandoned { .. } => true,
88 fn get_pending_fee_msat(&self) -> Option<u64> {
90 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
95 fn payment_hash(&self) -> Option<PaymentHash> {
97 PendingOutboundPayment::Legacy { .. } => None,
98 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
99 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
100 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
104 fn mark_fulfilled(&mut self) {
105 let mut session_privs = HashSet::new();
106 core::mem::swap(&mut session_privs, match self {
107 PendingOutboundPayment::Legacy { session_privs } |
108 PendingOutboundPayment::Retryable { session_privs, .. } |
109 PendingOutboundPayment::Fulfilled { session_privs, .. } |
110 PendingOutboundPayment::Abandoned { session_privs, .. }
113 let payment_hash = self.payment_hash();
114 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
117 fn mark_abandoned(&mut self) -> Result<(), ()> {
118 let mut session_privs = HashSet::new();
119 let our_payment_hash;
120 core::mem::swap(&mut session_privs, match self {
121 PendingOutboundPayment::Legacy { .. } |
122 PendingOutboundPayment::Fulfilled { .. } =>
124 PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } |
125 PendingOutboundPayment::Abandoned { session_privs, payment_hash, .. } => {
126 our_payment_hash = *payment_hash;
130 *self = PendingOutboundPayment::Abandoned { session_privs, payment_hash: our_payment_hash };
134 /// panics if path is None and !self.is_fulfilled
135 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Vec<RouteHop>>) -> bool {
136 let remove_res = match self {
137 PendingOutboundPayment::Legacy { session_privs } |
138 PendingOutboundPayment::Retryable { session_privs, .. } |
139 PendingOutboundPayment::Fulfilled { session_privs, .. } |
140 PendingOutboundPayment::Abandoned { session_privs, .. } => {
141 session_privs.remove(session_priv)
145 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
146 let path = path.expect("Fulfilling a payment should always come with a path");
147 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
148 *pending_amt_msat -= path_last_hop.fee_msat;
149 if let Some(fee_msat) = pending_fee_msat.as_mut() {
150 *fee_msat -= path.get_path_fees();
157 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Vec<RouteHop>) -> bool {
158 let insert_res = match self {
159 PendingOutboundPayment::Legacy { session_privs } |
160 PendingOutboundPayment::Retryable { session_privs, .. } => {
161 session_privs.insert(session_priv)
163 PendingOutboundPayment::Fulfilled { .. } => false,
164 PendingOutboundPayment::Abandoned { .. } => false,
167 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
168 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
169 *pending_amt_msat += path_last_hop.fee_msat;
170 if let Some(fee_msat) = pending_fee_msat.as_mut() {
171 *fee_msat += path.get_path_fees();
178 pub(super) fn remaining_parts(&self) -> usize {
180 PendingOutboundPayment::Legacy { session_privs } |
181 PendingOutboundPayment::Retryable { session_privs, .. } |
182 PendingOutboundPayment::Fulfilled { session_privs, .. } |
183 PendingOutboundPayment::Abandoned { session_privs, .. } => {
190 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
192 /// Storing minimal payment attempts information required for determining if a outbound payment can
194 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
195 /// This count will be incremented only after the result of the attempt is known. When it's 0,
196 /// it means the result of the first attempt is not known yet.
197 pub(crate) count: usize,
198 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
199 first_attempted_at: T
202 #[cfg(not(any(feature = "no-std", test)))]
203 type ConfiguredTime = std::time::Instant;
204 #[cfg(feature = "no-std")]
205 type ConfiguredTime = crate::util::time::Eternity;
206 #[cfg(all(not(feature = "no-std"), test))]
207 type ConfiguredTime = SinceEpoch;
209 impl<T: Time> PaymentAttemptsUsingTime<T> {
210 pub(crate) fn new() -> Self {
211 PaymentAttemptsUsingTime {
213 first_attempted_at: T::now()
218 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
219 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
220 #[cfg(feature = "no-std")]
221 return write!(f, "attempts: {}", self.count);
222 #[cfg(not(feature = "no-std"))]
225 "attempts: {}, duration: {}s",
227 T::now().duration_since(self.first_attempted_at).as_secs()
232 /// If a payment fails to send, it can be in one of several states. This enum is returned as the
233 /// Err() type describing which state the payment is in, see the description of individual enum
235 #[derive(Clone, Debug)]
236 pub enum PaymentSendFailure {
237 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
238 /// send the payment at all.
240 /// You can freely resend the payment in full (with the parameter error fixed).
242 /// Because the payment failed outright, no payment tracking is done, you do not need to call
243 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
244 /// for this payment.
246 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
247 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
248 ParameterError(APIError),
249 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
250 /// from attempting to send the payment at all.
252 /// You can freely resend the payment in full (with the parameter error fixed).
254 /// The results here are ordered the same as the paths in the route object which was passed to
257 /// Because the payment failed outright, no payment tracking is done, you do not need to call
258 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
259 /// for this payment.
261 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
262 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
263 PathParameterError(Vec<Result<(), APIError>>),
264 /// All paths which were attempted failed to send, with no channel state change taking place.
265 /// You can freely resend the payment in full (though you probably want to do so over different
266 /// paths than the ones selected).
268 /// Because the payment failed outright, no payment tracking is done, you do not need to call
269 /// [`ChannelManager::abandon_payment`] and [`ChannelManager::retry_payment`] will *not* work
270 /// for this payment.
272 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
273 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
274 AllFailedResendSafe(Vec<APIError>),
275 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
276 /// yet completed (i.e. generated an [`Event::PaymentSent`]) or been abandoned (via
277 /// [`ChannelManager::abandon_payment`]).
279 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
280 /// [`Event::PaymentSent`]: crate::util::events::Event::PaymentSent
281 /// [`ChannelManager::abandon_payment`]: crate::ln::channelmanager::ChannelManager::abandon_payment
283 /// Some paths which were attempted failed to send, though possibly not all. At least some
284 /// paths have irrevocably committed to the HTLC and retrying the payment in full would result
285 /// in over-/re-payment.
287 /// The results here are ordered the same as the paths in the route object which was passed to
288 /// send_payment, and any `Err`s which are not [`APIError::MonitorUpdateInProgress`] can be
289 /// safely retried via [`ChannelManager::retry_payment`].
291 /// Any entries which contain `Err(APIError::MonitorUpdateInprogress)` or `Ok(())` MUST NOT be
292 /// retried as they will result in over-/re-payment. These HTLCs all either successfully sent
293 /// (in the case of `Ok(())`) or will send once a [`MonitorEvent::Completed`] is provided for
294 /// the next-hop channel with the latest update_id.
296 /// [`ChannelManager::retry_payment`]: crate::ln::channelmanager::ChannelManager::retry_payment
297 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
299 /// The errors themselves, in the same order as the route hops.
300 results: Vec<Result<(), APIError>>,
301 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
302 /// contain a [`RouteParameters`] object which can be used to calculate a new route that
303 /// will pay all remaining unpaid balance.
304 failed_paths_retry: Option<RouteParameters>,
305 /// The payment id for the payment, which is now at least partially pending.
306 payment_id: PaymentId,
310 pub(super) struct OutboundPayments {
311 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
314 impl OutboundPayments {
315 pub(super) fn new() -> Self {
317 pending_outbound_payments: Mutex::new(HashMap::new())
321 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
322 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
323 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
324 send_payment_along_path: F
325 ) -> Result<(), PaymentSendFailure>
327 ES::Target: EntropySource,
328 NS::Target: NodeSigner,
329 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
330 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
332 let onion_session_privs = self.add_new_pending_payment(payment_hash, *payment_secret, payment_id, route, entropy_source, best_block_height)?;
333 self.send_payment_internal(route, payment_hash, payment_secret, None, payment_id, None, onion_session_privs, node_signer, best_block_height, send_payment_along_path)
336 pub(super) fn send_spontaneous_payment<ES: Deref, NS: Deref, F>(
337 &self, route: &Route, payment_preimage: Option<PaymentPreimage>, payment_id: PaymentId,
338 entropy_source: &ES, node_signer: &NS, best_block_height: u32, send_payment_along_path: F
339 ) -> Result<PaymentHash, PaymentSendFailure>
341 ES::Target: EntropySource,
342 NS::Target: NodeSigner,
343 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
344 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
346 let preimage = match payment_preimage {
348 None => PaymentPreimage(entropy_source.get_secure_random_bytes()),
350 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
351 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, entropy_source, best_block_height)?;
353 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) {
354 Ok(()) => Ok(payment_hash),
359 pub(super) fn retry_payment_with_route<ES: Deref, NS: Deref, F>(
360 &self, route: &Route, payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
361 send_payment_along_path: F
362 ) -> Result<(), PaymentSendFailure>
364 ES::Target: EntropySource,
365 NS::Target: NodeSigner,
366 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
367 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
369 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
370 for path in route.paths.iter() {
372 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
373 err: "length-0 path in route".to_string()
378 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
379 for _ in 0..route.paths.len() {
380 onion_session_privs.push(entropy_source.get_secure_random_bytes());
383 let (total_msat, payment_hash, payment_secret) = {
384 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
385 match outbounds.get_mut(&payment_id) {
387 let res = match payment {
388 PendingOutboundPayment::Retryable {
389 total_msat, payment_hash, payment_secret, pending_amt_msat, ..
391 let retry_amt_msat: u64 = route.paths.iter().map(|path| path.last().unwrap().fee_msat).sum();
392 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
393 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
394 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()
397 (*total_msat, *payment_hash, *payment_secret)
399 PendingOutboundPayment::Legacy { .. } => {
400 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
401 err: "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102".to_string()
404 PendingOutboundPayment::Fulfilled { .. } => {
405 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
406 err: "Payment already completed".to_owned()
409 PendingOutboundPayment::Abandoned { .. } => {
410 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
411 err: "Payment already abandoned (with some HTLCs still pending)".to_owned()
415 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
416 assert!(payment.insert(*session_priv_bytes, path));
421 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
422 err: format!("Payment with ID {} not found", log_bytes!(payment_id.0)),
426 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)
429 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
430 &self, hops: Vec<RouteHop>, probing_cookie_secret: [u8; 32], entropy_source: &ES,
431 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
432 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
434 ES::Target: EntropySource,
435 NS::Target: NodeSigner,
436 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
437 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
439 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
441 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
444 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
445 err: "No need probing a path with less than two hops".to_string()
449 let route = Route { paths: vec![hops], payment_params: None };
450 let onion_session_privs = self.add_new_pending_payment(payment_hash, None, payment_id, &route, entropy_source, best_block_height)?;
452 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) {
453 Ok(()) => Ok((payment_hash, payment_id)),
459 pub(super) fn test_add_new_pending_payment<ES: Deref>(
460 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
461 route: &Route, entropy_source: &ES, best_block_height: u32
462 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
463 self.add_new_pending_payment(payment_hash, payment_secret, payment_id, route, entropy_source, best_block_height)
466 pub(super) fn add_new_pending_payment<ES: Deref>(
467 &self, payment_hash: PaymentHash, payment_secret: Option<PaymentSecret>, payment_id: PaymentId,
468 route: &Route, entropy_source: &ES, best_block_height: u32
469 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
470 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
471 for _ in 0..route.paths.len() {
472 onion_session_privs.push(entropy_source.get_secure_random_bytes());
475 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
476 match pending_outbounds.entry(payment_id) {
477 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
478 hash_map::Entry::Vacant(entry) => {
479 let payment = entry.insert(PendingOutboundPayment::Retryable {
480 session_privs: HashSet::new(),
482 pending_fee_msat: Some(0),
485 starting_block_height: best_block_height,
486 total_msat: route.get_total_amount(),
489 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
490 assert!(payment.insert(*session_priv_bytes, path));
493 Ok(onion_session_privs)
498 fn send_payment_internal<NS: Deref, F>(
499 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
500 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
501 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
502 send_payment_along_path: F
503 ) -> Result<(), PaymentSendFailure>
505 NS::Target: NodeSigner,
506 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
507 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
509 if route.paths.len() < 1 {
510 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over"}));
512 if payment_secret.is_none() && route.paths.len() > 1 {
513 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_string()}));
515 let mut total_value = 0;
516 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
517 let mut path_errs = Vec::with_capacity(route.paths.len());
518 'path_check: for path in route.paths.iter() {
519 if path.len() < 1 || path.len() > 20 {
520 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size"}));
521 continue 'path_check;
523 for (idx, hop) in path.iter().enumerate() {
524 if idx != path.len() - 1 && hop.pubkey == our_node_id {
525 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us"}));
526 continue 'path_check;
529 total_value += path.last().unwrap().fee_msat;
530 path_errs.push(Ok(()));
532 if path_errs.iter().any(|e| e.is_err()) {
533 return Err(PaymentSendFailure::PathParameterError(path_errs));
535 if let Some(amt_msat) = recv_value_msat {
536 debug_assert!(amt_msat >= total_value);
537 total_value = amt_msat;
540 let cur_height = best_block_height + 1;
541 let mut results = Vec::new();
542 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
543 for (path, session_priv) in route.paths.iter().zip(onion_session_privs.into_iter()) {
544 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);
547 Err(APIError::MonitorUpdateInProgress) => {
548 // While a MonitorUpdateInProgress is an Err(_), the payment is still
549 // considered "in flight" and we shouldn't remove it from the
550 // PendingOutboundPayment set.
553 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
554 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
555 let removed = payment.remove(&session_priv, Some(path));
556 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
558 debug_assert!(false, "This can't happen as the payment was added by callers");
559 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
563 results.push(path_res);
565 let mut has_ok = false;
566 let mut has_err = false;
567 let mut pending_amt_unsent = 0;
568 let mut max_unsent_cltv_delta = 0;
569 for (res, path) in results.iter().zip(route.paths.iter()) {
570 if res.is_ok() { has_ok = true; }
571 if res.is_err() { has_err = true; }
572 if let &Err(APIError::MonitorUpdateInProgress) = res {
573 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
577 } else if res.is_err() {
578 pending_amt_unsent += path.last().unwrap().fee_msat;
579 max_unsent_cltv_delta = cmp::max(max_unsent_cltv_delta, path.last().unwrap().cltv_expiry_delta);
582 if has_err && has_ok {
583 Err(PaymentSendFailure::PartialFailure {
586 failed_paths_retry: if pending_amt_unsent != 0 {
587 if let Some(payment_params) = &route.payment_params {
588 Some(RouteParameters {
589 payment_params: payment_params.clone(),
590 final_value_msat: pending_amt_unsent,
591 final_cltv_expiry_delta: max_unsent_cltv_delta,
597 // If we failed to send any paths, we should remove the new PaymentId from the
598 // `pending_outbound_payments` map, as the user isn't expected to `abandon_payment`.
599 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
600 debug_assert!(removed, "We should always have a pending payment to remove here");
601 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
608 pub(super) fn test_send_payment_internal<NS: Deref, F>(
609 &self, route: &Route, payment_hash: PaymentHash, payment_secret: &Option<PaymentSecret>,
610 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
611 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
612 send_payment_along_path: F
613 ) -> Result<(), PaymentSendFailure>
615 NS::Target: NodeSigner,
616 F: Fn(&Vec<RouteHop>, &Option<PaymentParameters>, &PaymentHash, &Option<PaymentSecret>, u64,
617 u32, PaymentId, &Option<PaymentPreimage>, [u8; 32]) -> Result<(), APIError>
619 self.send_payment_internal(route, payment_hash, payment_secret, keysend_preimage, payment_id,
620 recv_value_msat, onion_session_privs, node_signer, best_block_height,
621 send_payment_along_path)
624 pub(super) fn claim_htlc<L: Deref>(
625 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
626 path: Vec<RouteHop>, from_onchain: bool, pending_events: &Mutex<Vec<events::Event>>, logger: &L
627 ) where L::Target: Logger {
628 let mut session_priv_bytes = [0; 32];
629 session_priv_bytes.copy_from_slice(&session_priv[..]);
630 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
631 let mut pending_events = pending_events.lock().unwrap();
632 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
633 if !payment.get().is_fulfilled() {
634 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
635 let fee_paid_msat = payment.get().get_pending_fee_msat();
637 events::Event::PaymentSent {
638 payment_id: Some(payment_id),
644 payment.get_mut().mark_fulfilled();
648 // We currently immediately remove HTLCs which were fulfilled on-chain.
649 // This could potentially lead to removing a pending payment too early,
650 // with a reorg of one block causing us to re-add the fulfilled payment on
652 // TODO: We should have a second monitor event that informs us of payments
653 // irrevocably fulfilled.
654 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
655 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
657 events::Event::PaymentPathSuccessful {
666 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", log_bytes!(payment_preimage.0));
670 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>, pending_events: &Mutex<Vec<events::Event>>) {
671 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
672 let mut pending_events = pending_events.lock().unwrap();
673 for source in sources {
674 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
675 let mut session_priv_bytes = [0; 32];
676 session_priv_bytes.copy_from_slice(&session_priv[..]);
677 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
678 assert!(payment.get().is_fulfilled());
679 if payment.get_mut().remove(&session_priv_bytes, None) {
681 events::Event::PaymentPathSuccessful {
683 payment_hash: payment.get().payment_hash(),
693 pub(super) fn remove_stale_resolved_payments(&self, pending_events: &Mutex<Vec<events::Event>>) {
694 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
695 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
696 // this could race the user making a duplicate send_payment call and our idempotency
697 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
698 // removal. This should be more than sufficient to ensure the idempotency of any
699 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
701 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
702 let pending_events = pending_events.lock().unwrap();
703 pending_outbound_payments.retain(|payment_id, payment| {
704 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
705 let mut no_remaining_entries = session_privs.is_empty();
706 if no_remaining_entries {
707 for ev in pending_events.iter() {
709 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
710 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
711 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
712 if payment_id == ev_payment_id {
713 no_remaining_entries = false;
721 if no_remaining_entries {
722 *timer_ticks_without_htlcs += 1;
723 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
725 *timer_ticks_without_htlcs = 0;
732 pub(super) fn fail_htlc<L: Deref>(
733 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
734 path: &Vec<RouteHop>, session_priv: &SecretKey, payment_id: &PaymentId,
735 payment_params: &Option<PaymentParameters>, probing_cookie_secret: [u8; 32],
736 secp_ctx: &Secp256k1<secp256k1::All>, pending_events: &Mutex<Vec<events::Event>>, logger: &L
737 ) where L::Target: Logger {
738 let mut session_priv_bytes = [0; 32];
739 session_priv_bytes.copy_from_slice(&session_priv[..]);
740 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
741 let mut all_paths_failed = false;
742 let mut full_failure_ev = None;
743 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
744 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
745 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
748 if payment.get().is_fulfilled() {
749 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", log_bytes!(payment_hash.0));
752 if payment.get().remaining_parts() == 0 {
753 all_paths_failed = true;
754 if payment.get().abandoned() {
755 full_failure_ev = Some(events::Event::PaymentFailed {
756 payment_id: *payment_id,
757 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
763 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", log_bytes!(payment_hash.0));
766 let mut retry = if let Some(payment_params_data) = payment_params {
767 let path_last_hop = path.last().expect("Outbound payments must have had a valid path");
768 Some(RouteParameters {
769 payment_params: payment_params_data.clone(),
770 final_value_msat: path_last_hop.fee_msat,
771 final_cltv_expiry_delta: path_last_hop.cltv_expiry_delta,
774 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", log_bytes!(payment_hash.0));
778 let (network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
780 let (network_update, short_channel_id, payment_retryable, _, _) = onion_error.decode_onion_failure(secp_ctx, logger, &source);
782 if payment_is_probe(payment_hash, &payment_id, probing_cookie_secret) {
783 if !payment_retryable {
784 events::Event::ProbeSuccessful {
785 payment_id: *payment_id,
786 payment_hash: payment_hash.clone(),
790 events::Event::ProbeFailed {
791 payment_id: *payment_id,
792 payment_hash: payment_hash.clone(),
798 // TODO: If we decided to blame ourselves (or one of our channels) in
799 // process_onion_failure we should close that channel as it implies our
800 // next-hop is needlessly blaming us!
801 if let Some(scid) = short_channel_id {
802 retry.as_mut().map(|r| r.payment_params.previously_failed_channels.push(scid));
804 events::Event::PaymentPathFailed {
805 payment_id: Some(*payment_id),
806 payment_hash: payment_hash.clone(),
807 payment_failed_permanently: !payment_retryable,
814 error_code: onion_error_code,
816 error_data: onion_error_data
820 let mut pending_events = pending_events.lock().unwrap();
821 pending_events.push(path_failure);
822 if let Some(ev) = full_failure_ev { pending_events.push(ev); }
825 pub(super) fn abandon_payment(&self, payment_id: PaymentId) -> Option<events::Event> {
826 let mut failed_ev = None;
827 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
828 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
829 if let Ok(()) = payment.get_mut().mark_abandoned() {
830 if payment.get().remaining_parts() == 0 {
831 failed_ev = Some(events::Event::PaymentFailed {
833 payment_hash: payment.get().payment_hash().expect("PendingOutboundPayments::RetriesExceeded always has a payment hash set"),
843 pub fn has_pending_payments(&self) -> bool {
844 !self.pending_outbound_payments.lock().unwrap().is_empty()
848 pub fn clear_pending_payments(&self) {
849 self.pending_outbound_payments.lock().unwrap().clear()
853 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
855 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
856 probing_cookie_secret: [u8; 32]) -> bool
858 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
859 target_payment_hash == *payment_hash
862 /// Returns the 'probing cookie' for the given [`PaymentId`].
863 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
864 let mut preimage = [0u8; 64];
865 preimage[..32].copy_from_slice(&probing_cookie_secret);
866 preimage[32..].copy_from_slice(&payment_id.0);
867 PaymentHash(Sha256::hash(&preimage).into_inner())
870 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
872 (0, session_privs, required),
875 (0, session_privs, required),
876 (1, payment_hash, option),
877 (3, timer_ticks_without_htlcs, (default_value, 0)),
880 (0, session_privs, required),
881 (1, pending_fee_msat, option),
882 (2, payment_hash, required),
883 (4, payment_secret, option),
884 (6, total_msat, required),
885 (8, pending_amt_msat, required),
886 (10, starting_block_height, required),
889 (0, session_privs, required),
890 (2, payment_hash, required),