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::sign::{EntropySource, NodeSigner, Recipient};
17 use crate::events::{self, PaymentFailureReason};
18 use crate::ln::{PaymentHash, PaymentPreimage, PaymentSecret};
19 use crate::ln::channelmanager::{ChannelDetails, EventCompletionAction, HTLCSource, PaymentId};
20 use crate::ln::onion_utils::{DecodedOnionFailure, HTLCFailReason};
21 use crate::offers::invoice::Bolt12Invoice;
22 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, Router};
23 use crate::util::errors::APIError;
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;
28 use crate::util::ser::ReadableArgs;
30 use core::fmt::{self, Display, Formatter};
33 use crate::prelude::*;
34 use crate::sync::Mutex;
36 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the idempotency
37 /// of payments by [`PaymentId`]. See [`OutboundPayments::remove_stale_payments`].
39 /// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
40 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
42 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until an invoice request without
43 /// a response is timed out.
45 /// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
46 const INVOICE_REQUEST_TIMEOUT_TICKS: u8 = 3;
48 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
49 /// and later, also stores information for retrying the payment.
50 pub(crate) enum PendingOutboundPayment {
52 session_privs: HashSet<[u8; 32]>,
55 timer_ticks_without_response: u8,
58 payment_hash: PaymentHash,
61 retry_strategy: Option<Retry>,
62 attempts: PaymentAttempts,
63 payment_params: Option<PaymentParameters>,
64 session_privs: HashSet<[u8; 32]>,
65 payment_hash: PaymentHash,
66 payment_secret: Option<PaymentSecret>,
67 payment_metadata: Option<Vec<u8>>,
68 keysend_preimage: Option<PaymentPreimage>,
69 custom_tlvs: Vec<(u64, Vec<u8>)>,
70 pending_amt_msat: u64,
71 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
72 pending_fee_msat: Option<u64>,
73 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
75 /// Our best known block height at the time this payment was initiated.
76 starting_block_height: u32,
78 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
79 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
80 /// and add a pending payment that was already fulfilled.
82 session_privs: HashSet<[u8; 32]>,
83 /// Filled in for any payment which moved to `Fulfilled` on LDK 0.0.104 or later.
84 payment_hash: Option<PaymentHash>,
85 timer_ticks_without_htlcs: u8,
87 /// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
88 /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
90 session_privs: HashSet<[u8; 32]>,
91 payment_hash: PaymentHash,
92 /// Will be `None` if the payment was serialized before 0.0.115.
93 reason: Option<PaymentFailureReason>,
97 impl PendingOutboundPayment {
98 fn increment_attempts(&mut self) {
99 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
103 fn is_auto_retryable_now(&self) -> bool {
105 PendingOutboundPayment::Retryable {
106 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
108 strategy.is_retryable_now(&attempts)
113 fn is_retryable_now(&self) -> bool {
115 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
116 // We're handling retries manually, we can always retry.
119 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
120 strategy.is_retryable_now(&attempts)
125 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
126 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
127 params.previously_failed_channels.push(scid);
130 fn is_awaiting_invoice(&self) -> bool {
132 PendingOutboundPayment::AwaitingInvoice { .. } => true,
136 pub(super) fn is_fulfilled(&self) -> bool {
138 PendingOutboundPayment::Fulfilled { .. } => true,
142 pub(super) fn abandoned(&self) -> bool {
144 PendingOutboundPayment::Abandoned { .. } => true,
148 fn get_pending_fee_msat(&self) -> Option<u64> {
150 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
155 fn payment_hash(&self) -> Option<PaymentHash> {
157 PendingOutboundPayment::Legacy { .. } => None,
158 PendingOutboundPayment::AwaitingInvoice { .. } => None,
159 PendingOutboundPayment::InvoiceReceived { payment_hash } => Some(*payment_hash),
160 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
161 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
162 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
166 fn mark_fulfilled(&mut self) {
167 let mut session_privs = HashSet::new();
168 core::mem::swap(&mut session_privs, match self {
169 PendingOutboundPayment::Legacy { session_privs } |
170 PendingOutboundPayment::Retryable { session_privs, .. } |
171 PendingOutboundPayment::Fulfilled { session_privs, .. } |
172 PendingOutboundPayment::Abandoned { session_privs, .. } => session_privs,
173 PendingOutboundPayment::AwaitingInvoice { .. } |
174 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); return; },
176 let payment_hash = self.payment_hash();
177 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
180 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
181 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
182 let mut our_session_privs = HashSet::new();
183 core::mem::swap(&mut our_session_privs, session_privs);
184 *self = PendingOutboundPayment::Abandoned {
185 session_privs: our_session_privs,
186 payment_hash: *payment_hash,
189 } else if let PendingOutboundPayment::InvoiceReceived { payment_hash } = self {
190 *self = PendingOutboundPayment::Abandoned {
191 session_privs: HashSet::new(),
192 payment_hash: *payment_hash,
198 /// panics if path is None and !self.is_fulfilled
199 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
200 let remove_res = match self {
201 PendingOutboundPayment::Legacy { session_privs } |
202 PendingOutboundPayment::Retryable { session_privs, .. } |
203 PendingOutboundPayment::Fulfilled { session_privs, .. } |
204 PendingOutboundPayment::Abandoned { session_privs, .. } => {
205 session_privs.remove(session_priv)
207 PendingOutboundPayment::AwaitingInvoice { .. } |
208 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
211 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
212 let path = path.expect("Fulfilling a payment should always come with a path");
213 *pending_amt_msat -= path.final_value_msat();
214 if let Some(fee_msat) = pending_fee_msat.as_mut() {
215 *fee_msat -= path.fee_msat();
222 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
223 let insert_res = match self {
224 PendingOutboundPayment::Legacy { session_privs } |
225 PendingOutboundPayment::Retryable { session_privs, .. } => {
226 session_privs.insert(session_priv)
228 PendingOutboundPayment::AwaitingInvoice { .. } |
229 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
230 PendingOutboundPayment::Fulfilled { .. } => false,
231 PendingOutboundPayment::Abandoned { .. } => false,
234 if let PendingOutboundPayment::Retryable { ref mut pending_amt_msat, ref mut pending_fee_msat, .. } = self {
235 *pending_amt_msat += path.final_value_msat();
236 if let Some(fee_msat) = pending_fee_msat.as_mut() {
237 *fee_msat += path.fee_msat();
244 pub(super) fn remaining_parts(&self) -> usize {
246 PendingOutboundPayment::Legacy { session_privs } |
247 PendingOutboundPayment::Retryable { session_privs, .. } |
248 PendingOutboundPayment::Fulfilled { session_privs, .. } |
249 PendingOutboundPayment::Abandoned { session_privs, .. } => {
252 PendingOutboundPayment::AwaitingInvoice { .. } => 0,
253 PendingOutboundPayment::InvoiceReceived { .. } => 0,
258 /// Strategies available to retry payment path failures.
259 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
261 /// Max number of attempts to retry payment.
263 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
264 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
265 /// were retried along a route from a single call to [`Router::find_route_with_id`].
267 #[cfg(not(feature = "no-std"))]
268 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
269 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
271 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
272 Timeout(core::time::Duration),
276 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
277 match (self, attempts) {
278 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
279 max_retry_count > count
281 #[cfg(all(not(feature = "no-std"), not(test)))]
282 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
283 *max_duration >= crate::util::time::MonotonicTime::now().duration_since(*first_attempted_at),
284 #[cfg(all(not(feature = "no-std"), test))]
285 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
286 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
291 #[cfg(feature = "std")]
292 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
293 if let Some(expiry_time) = route_params.payment_params.expiry_time {
294 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
295 return elapsed > core::time::Duration::from_secs(expiry_time)
301 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
303 /// Storing minimal payment attempts information required for determining if a outbound payment can
305 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
306 /// This count will be incremented only after the result of the attempt is known. When it's 0,
307 /// it means the result of the first attempt is not known yet.
308 pub(crate) count: usize,
309 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
310 #[cfg(not(feature = "no-std"))]
311 first_attempted_at: T,
312 #[cfg(feature = "no-std")]
313 phantom: core::marker::PhantomData<T>,
317 #[cfg(not(any(feature = "no-std", test)))]
318 type ConfiguredTime = crate::util::time::MonotonicTime;
319 #[cfg(feature = "no-std")]
320 type ConfiguredTime = crate::util::time::Eternity;
321 #[cfg(all(not(feature = "no-std"), test))]
322 type ConfiguredTime = SinceEpoch;
324 impl<T: Time> PaymentAttemptsUsingTime<T> {
325 pub(crate) fn new() -> Self {
326 PaymentAttemptsUsingTime {
328 #[cfg(not(feature = "no-std"))]
329 first_attempted_at: T::now(),
330 #[cfg(feature = "no-std")]
331 phantom: core::marker::PhantomData,
336 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
337 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
338 #[cfg(feature = "no-std")]
339 return write!(f, "attempts: {}", self.count);
340 #[cfg(not(feature = "no-std"))]
343 "attempts: {}, duration: {}s",
345 T::now().duration_since(self.first_attempted_at).as_secs()
350 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
351 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
353 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
354 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
355 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
356 #[derive(Clone, Debug, PartialEq, Eq)]
357 pub enum RetryableSendFailure {
358 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
359 /// that this error is *not* caused by [`Retry::Timeout`].
361 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
363 /// We were unable to find a route to the destination.
365 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
366 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
368 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
369 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
370 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
374 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
375 /// of several states. This enum is returned as the Err() type describing which state the payment
376 /// is in, see the description of individual enum states for more.
378 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
379 #[derive(Clone, Debug)]
380 pub enum PaymentSendFailure {
381 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
382 /// send the payment at all.
384 /// You can freely resend the payment in full (with the parameter error fixed).
386 /// Because the payment failed outright, no payment tracking is done and no
387 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
389 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
390 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
391 ParameterError(APIError),
392 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
393 /// from attempting to send the payment at all.
395 /// You can freely resend the payment in full (with the parameter error fixed).
397 /// Because the payment failed outright, no payment tracking is done and no
398 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
400 /// The results here are ordered the same as the paths in the route object which was passed to
403 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
404 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
405 PathParameterError(Vec<Result<(), APIError>>),
406 /// All paths which were attempted failed to send, with no channel state change taking place.
407 /// You can freely resend the payment in full (though you probably want to do so over different
408 /// paths than the ones selected).
410 /// Because the payment failed outright, no payment tracking is done and no
411 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
413 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
414 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
415 AllFailedResendSafe(Vec<APIError>),
416 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
417 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
419 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
420 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
421 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
423 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
424 /// some paths have irrevocably committed to the HTLC.
426 /// The results here are ordered the same as the paths in the route object that was passed to
429 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
430 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
432 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
434 /// The errors themselves, in the same order as the paths from the route.
435 results: Vec<Result<(), APIError>>,
436 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
437 /// contain a [`RouteParameters`] object for the failing paths.
438 failed_paths_retry: Option<RouteParameters>,
439 /// The payment id for the payment, which is now at least partially pending.
440 payment_id: PaymentId,
444 /// An error when attempting to pay a BOLT 12 invoice.
445 pub(super) enum Bolt12PaymentError {
446 /// The invoice was not requested.
448 /// Payment for an invoice with the corresponding [`PaymentId`] was already initiated.
452 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
454 /// This should generally be constructed with data communicated to us from the recipient (via a
455 /// BOLT11 or BOLT12 invoice).
456 #[derive(Clone, Debug, PartialEq, Eq)]
457 pub struct RecipientOnionFields {
458 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
459 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
460 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
463 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
464 /// multi-path payments require a recipient-provided secret.
466 /// Some implementations may reject spontaneous payments with payment secrets, so you may only
467 /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
468 /// recipient will not reject it.
469 pub payment_secret: Option<PaymentSecret>,
470 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
471 /// arbitrary length. This gives recipients substantially more flexibility to receive
474 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
475 /// scheme to authenticate received payments against expected payments and invoices, this field
476 /// is not used in LDK for received payments, and can be used to store arbitrary data in
477 /// invoices which will be received with the payment.
479 /// Note that this field was added to the lightning specification more recently than
480 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
481 /// may not be supported as universally.
482 pub payment_metadata: Option<Vec<u8>>,
483 /// See [`Self::custom_tlvs`] for more info.
484 pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
487 impl_writeable_tlv_based!(RecipientOnionFields, {
488 (0, payment_secret, option),
489 (1, custom_tlvs, optional_vec),
490 (2, payment_metadata, option),
493 impl RecipientOnionFields {
494 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
495 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
496 /// but do not require or provide any further data.
497 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
498 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
501 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
502 /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
503 /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
504 /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
505 /// instead want to use [`RecipientOnionFields::secret_only`].
507 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
508 /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
509 pub fn spontaneous_empty() -> Self {
510 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
513 /// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
514 /// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
515 /// respectively. TLV type numbers must be unique and within the range
516 /// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
518 /// This method will also error for types in the experimental range which have been
519 /// standardized within the protocol, which only includes 5482373484 (keysend) for now.
521 /// See [`Self::custom_tlvs`] for more info.
522 pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
523 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
524 let mut prev_type = None;
525 for (typ, _) in custom_tlvs.iter() {
526 if *typ < 1 << 16 { return Err(()); }
527 if *typ == 5482373484 { return Err(()); } // keysend
529 Some(prev) if prev >= *typ => return Err(()),
532 prev_type = Some(*typ);
534 self.custom_tlvs = custom_tlvs;
538 /// Gets the custom TLVs that will be sent or have been received.
540 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
541 /// additional flexibility on top of payment metadata, as while other implementations may
542 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
543 /// do not have this restriction.
545 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
546 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
547 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
548 pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
552 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
553 /// have to make sure that some fields match exactly across the parts. For those that aren't
554 /// required to match, if they don't match we should remove them so as to not expose data
555 /// that's dependent on the HTLC receive order to users.
557 /// Here we implement this, first checking compatibility then mutating two objects and then
558 /// dropping any remaining non-matching fields from both.
559 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
560 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
561 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
563 let tlvs = &mut self.custom_tlvs;
564 let further_tlvs = &mut further_htlc_fields.custom_tlvs;
566 let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
567 let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
568 if even_tlvs.ne(further_even_tlvs) { return Err(()) }
570 tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
571 further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
577 /// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
578 pub(super) struct SendAlongPathArgs<'a> {
580 pub payment_hash: &'a PaymentHash,
581 pub recipient_onion: RecipientOnionFields,
582 pub total_value: u64,
584 pub payment_id: PaymentId,
585 pub keysend_preimage: &'a Option<PaymentPreimage>,
586 pub session_priv_bytes: [u8; 32],
589 const BOLT_12_INVOICE_RETRY_STRATEGY: Retry = Retry::Attempts(3);
591 pub(super) struct OutboundPayments {
592 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
593 pub(super) retry_lock: Mutex<()>,
596 impl OutboundPayments {
597 pub(super) fn new() -> Self {
599 pending_outbound_payments: Mutex::new(HashMap::new()),
600 retry_lock: Mutex::new(()),
604 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
605 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
606 retry_strategy: Retry, route_params: RouteParameters, router: &R,
607 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
608 node_signer: &NS, best_block_height: u32, logger: &L,
609 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
610 ) -> Result<(), RetryableSendFailure>
613 ES::Target: EntropySource,
614 NS::Target: NodeSigner,
616 IH: Fn() -> InFlightHtlcs,
617 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
619 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
620 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
621 best_block_height, logger, pending_events, &send_payment_along_path)
624 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
625 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
626 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
627 send_payment_along_path: F
628 ) -> Result<(), PaymentSendFailure>
630 ES::Target: EntropySource,
631 NS::Target: NodeSigner,
632 F: Fn(SendAlongPathArgs) -> Result<(), APIError>
634 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)?;
635 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
636 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
637 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
640 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
641 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
642 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
643 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
644 node_signer: &NS, best_block_height: u32, logger: &L,
645 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
646 ) -> Result<PaymentHash, RetryableSendFailure>
649 ES::Target: EntropySource,
650 NS::Target: NodeSigner,
652 IH: Fn() -> InFlightHtlcs,
653 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
655 let preimage = payment_preimage
656 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
657 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
658 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
659 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
660 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
661 .map(|()| payment_hash)
664 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
665 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
666 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
667 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
668 ) -> Result<PaymentHash, PaymentSendFailure>
670 ES::Target: EntropySource,
671 NS::Target: NodeSigner,
672 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
674 let preimage = payment_preimage
675 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
676 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
677 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
678 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
680 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
681 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
683 Ok(()) => Ok(payment_hash),
685 self.remove_outbound_if_all_failed(payment_id, &e);
692 pub(super) fn send_payment_for_bolt12_invoice<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
693 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
694 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
695 best_block_height: u32, logger: &L,
696 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
697 send_payment_along_path: SP,
698 ) -> Result<(), Bolt12PaymentError>
701 ES::Target: EntropySource,
702 NS::Target: NodeSigner,
704 IH: Fn() -> InFlightHtlcs,
705 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
707 let payment_hash = invoice.payment_hash();
708 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
709 hash_map::Entry::Occupied(entry) if entry.get().is_awaiting_invoice() => {
710 *entry.into_mut() = PendingOutboundPayment::InvoiceReceived { payment_hash };
712 hash_map::Entry::Occupied(_) => return Err(Bolt12PaymentError::DuplicateInvoice),
713 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
716 let route_params = RouteParameters {
717 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
718 final_value_msat: invoice.amount_msats(),
721 self.find_route_and_send_payment(
722 payment_hash, payment_id, route_params, router, first_hops, &inflight_htlcs,
723 entropy_source, node_signer, best_block_height, logger, pending_events,
724 &send_payment_along_path
730 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
731 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
732 best_block_height: u32,
733 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
734 send_payment_along_path: SP,
738 ES::Target: EntropySource,
739 NS::Target: NodeSigner,
740 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
741 IH: Fn() -> InFlightHtlcs,
742 FH: Fn() -> Vec<ChannelDetails>,
745 let _single_thread = self.retry_lock.lock().unwrap();
747 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
748 let mut retry_id_route_params = None;
749 for (pmt_id, pmt) in outbounds.iter_mut() {
750 if pmt.is_auto_retryable_now() {
751 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, .. } = pmt {
752 if pending_amt_msat < total_msat {
753 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
754 final_value_msat: *total_msat - *pending_amt_msat,
755 payment_params: params.clone(),
759 } else { debug_assert!(false); }
762 core::mem::drop(outbounds);
763 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
764 self.find_route_and_send_payment(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)
768 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
769 outbounds.retain(|pmt_id, pmt| {
770 let mut retain = true;
771 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
772 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
773 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
774 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
776 payment_hash: *payment_hash,
786 pub(super) fn needs_abandon(&self) -> bool {
787 let outbounds = self.pending_outbound_payments.lock().unwrap();
788 outbounds.iter().any(|(_, pmt)|
789 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
790 !pmt.is_awaiting_invoice())
793 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
794 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
796 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
797 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
798 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
799 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
800 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
801 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
802 node_signer: &NS, best_block_height: u32, logger: &L,
803 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
804 ) -> Result<(), RetryableSendFailure>
807 ES::Target: EntropySource,
808 NS::Target: NodeSigner,
810 IH: Fn() -> InFlightHtlcs,
811 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
813 #[cfg(feature = "std")] {
814 if has_expired(&route_params) {
815 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
816 payment_id, payment_hash);
817 return Err(RetryableSendFailure::PaymentExpired)
821 let route = router.find_route_with_id(
822 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
823 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
824 payment_hash, payment_id,
826 log_error!(logger, "Failed to find route for payment with id {} and hash {}",
827 payment_id, payment_hash);
828 RetryableSendFailure::RouteNotFound
831 let onion_session_privs = self.add_new_pending_payment(payment_hash,
832 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
833 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
835 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
836 payment_id, payment_hash);
837 RetryableSendFailure::DuplicatePayment
840 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage, payment_id, None,
841 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
842 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
843 payment_id, payment_hash, res);
844 if let Err(e) = res {
845 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);
850 fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
851 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
852 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
853 node_signer: &NS, best_block_height: u32, logger: &L,
854 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
858 ES::Target: EntropySource,
859 NS::Target: NodeSigner,
861 IH: Fn() -> InFlightHtlcs,
862 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
864 #[cfg(feature = "std")] {
865 if has_expired(&route_params) {
866 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
867 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
872 let route = match router.find_route_with_id(
873 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
874 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
875 payment_hash, payment_id,
879 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
880 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
884 for path in route.paths.iter() {
885 if path.hops.len() == 0 {
886 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
887 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
892 macro_rules! abandon_with_entry {
893 ($payment: expr, $reason: expr) => {
894 $payment.get_mut().mark_abandoned($reason);
895 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
896 if $payment.get().remaining_parts() == 0 {
897 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
907 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs) = {
908 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
909 match outbounds.entry(payment_id) {
910 hash_map::Entry::Occupied(mut payment) => {
911 match payment.get() {
912 PendingOutboundPayment::Retryable {
913 total_msat, keysend_preimage, payment_secret, payment_metadata,
914 custom_tlvs, pending_amt_msat, ..
916 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
917 let retry_amt_msat = route.get_total_amount();
918 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
919 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);
920 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
924 if !payment.get().is_retryable_now() {
925 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
926 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
930 let total_msat = *total_msat;
931 let recipient_onion = RecipientOnionFields {
932 payment_secret: *payment_secret,
933 payment_metadata: payment_metadata.clone(),
934 custom_tlvs: custom_tlvs.clone(),
936 let keysend_preimage = *keysend_preimage;
938 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
939 for _ in 0..route.paths.len() {
940 onion_session_privs.push(entropy_source.get_secure_random_bytes());
943 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
944 assert!(payment.get_mut().insert(*session_priv_bytes, path));
947 payment.get_mut().increment_attempts();
949 (total_msat, recipient_onion, keysend_preimage, onion_session_privs)
951 PendingOutboundPayment::Legacy { .. } => {
952 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
955 PendingOutboundPayment::AwaitingInvoice { .. } => {
956 log_error!(logger, "Payment not yet sent");
959 PendingOutboundPayment::InvoiceReceived { payment_hash } => {
960 let total_amount = route_params.final_value_msat;
961 let recipient_onion = RecipientOnionFields {
962 payment_secret: None,
963 payment_metadata: None,
966 let retry_strategy = Some(BOLT_12_INVOICE_RETRY_STRATEGY);
967 let payment_params = Some(route_params.payment_params.clone());
968 let (retryable_payment, onion_session_privs) = self.create_pending_payment(
969 *payment_hash, recipient_onion.clone(), None, &route,
970 retry_strategy, payment_params, entropy_source, best_block_height
972 *payment.into_mut() = retryable_payment;
973 (total_amount, recipient_onion, None, onion_session_privs)
975 PendingOutboundPayment::Fulfilled { .. } => {
976 log_error!(logger, "Payment already completed");
979 PendingOutboundPayment::Abandoned { .. } => {
980 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
985 hash_map::Entry::Vacant(_) => {
986 log_error!(logger, "Payment with ID {} not found", &payment_id);
991 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
992 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
993 &send_payment_along_path);
994 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
995 if let Err(e) = res {
996 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);
1000 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1001 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1002 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
1003 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
1004 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1008 ES::Target: EntropySource,
1009 NS::Target: NodeSigner,
1011 IH: Fn() -> InFlightHtlcs,
1012 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1015 PaymentSendFailure::AllFailedResendSafe(errs) => {
1016 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);
1017 self.find_route_and_send_payment(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);
1019 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1020 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1021 // Some paths were sent, even if we failed to send the full MPP value our recipient may
1022 // misbehave and claim the funds, at which point we have to consider the payment sent, so
1023 // return `Ok()` here, ignoring any retry errors.
1024 self.find_route_and_send_payment(payment_hash, payment_id, retry, router, first_hops, inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events, send_payment_along_path);
1026 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1027 // This may happen if we send a payment and some paths fail, but only due to a temporary
1028 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
1029 // initial HTLC-Add messages yet.
1031 PaymentSendFailure::PathParameterError(results) => {
1032 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1033 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1034 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1036 PaymentSendFailure::ParameterError(e) => {
1037 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1038 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1040 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1044 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1045 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1046 paths: Vec<Path>, path_results: I, logger: &L,
1047 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1048 ) where L::Target: Logger {
1049 let mut events = pending_events.lock().unwrap();
1050 debug_assert_eq!(paths.len(), path_results.len());
1051 for (path, path_res) in paths.into_iter().zip(path_results) {
1052 if let Err(e) = path_res {
1053 if let APIError::MonitorUpdateInProgress = e { continue }
1054 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1055 let mut failed_scid = None;
1056 if let APIError::ChannelUnavailable { .. } = e {
1057 let scid = path.hops[0].short_channel_id;
1058 failed_scid = Some(scid);
1059 route_params.payment_params.previously_failed_channels.push(scid);
1061 events.push_back((events::Event::PaymentPathFailed {
1062 payment_id: Some(payment_id),
1064 payment_failed_permanently: false,
1065 failure: events::PathFailure::InitialSend { err: e },
1067 short_channel_id: failed_scid,
1077 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1078 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1079 best_block_height: u32, send_payment_along_path: F
1080 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1082 ES::Target: EntropySource,
1083 NS::Target: NodeSigner,
1084 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1086 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1088 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1090 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1091 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1092 err: "No need probing a path with less than two hops".to_string()
1096 let route = Route { paths: vec![path], route_params: None };
1097 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1098 RecipientOnionFields::spontaneous_empty(), payment_id, None, &route, None, None,
1099 entropy_source, best_block_height)?;
1101 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
1102 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1104 Ok(()) => Ok((payment_hash, payment_id)),
1106 self.remove_outbound_if_all_failed(payment_id, &e);
1113 pub(super) fn test_set_payment_metadata(
1114 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1116 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1117 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1118 *payment_metadata = new_payment_metadata;
1120 _ => panic!("Need a retryable payment to update metadata on"),
1125 pub(super) fn test_add_new_pending_payment<ES: Deref>(
1126 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1127 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1128 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1129 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1132 pub(super) fn add_new_pending_payment<ES: Deref>(
1133 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1134 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1135 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1136 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1137 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1138 match pending_outbounds.entry(payment_id) {
1139 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1140 hash_map::Entry::Vacant(entry) => {
1141 let (payment, onion_session_privs) = self.create_pending_payment(
1142 payment_hash, recipient_onion, keysend_preimage, route, retry_strategy,
1143 payment_params, entropy_source, best_block_height
1145 entry.insert(payment);
1146 Ok(onion_session_privs)
1151 fn create_pending_payment<ES: Deref>(
1152 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1153 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1154 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1155 ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1157 ES::Target: EntropySource,
1159 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1160 for _ in 0..route.paths.len() {
1161 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1164 let mut payment = PendingOutboundPayment::Retryable {
1166 attempts: PaymentAttempts::new(),
1168 session_privs: HashSet::new(),
1169 pending_amt_msat: 0,
1170 pending_fee_msat: Some(0),
1172 payment_secret: recipient_onion.payment_secret,
1173 payment_metadata: recipient_onion.payment_metadata,
1175 custom_tlvs: recipient_onion.custom_tlvs,
1176 starting_block_height: best_block_height,
1177 total_msat: route.get_total_amount(),
1180 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1181 assert!(payment.insert(*session_priv_bytes, path));
1184 (payment, onion_session_privs)
1188 pub(super) fn add_new_awaiting_invoice(&self, payment_id: PaymentId) -> Result<(), ()> {
1189 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1190 match pending_outbounds.entry(payment_id) {
1191 hash_map::Entry::Occupied(_) => Err(()),
1192 hash_map::Entry::Vacant(entry) => {
1193 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1194 timer_ticks_without_response: 0,
1202 fn pay_route_internal<NS: Deref, F>(
1203 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1204 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1205 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1206 send_payment_along_path: &F
1207 ) -> Result<(), PaymentSendFailure>
1209 NS::Target: NodeSigner,
1210 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1212 if route.paths.len() < 1 {
1213 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1215 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1 {
1216 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1218 let mut total_value = 0;
1219 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1220 let mut path_errs = Vec::with_capacity(route.paths.len());
1221 'path_check: for path in route.paths.iter() {
1222 if path.hops.len() < 1 || path.hops.len() > 20 {
1223 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1224 continue 'path_check;
1226 if path.blinded_tail.is_some() {
1227 path_errs.push(Err(APIError::InvalidRoute{err: "Sending to blinded paths isn't supported yet".to_owned()}));
1228 continue 'path_check;
1230 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1231 usize::max_value() } else { path.hops.len() - 1 };
1232 for (idx, hop) in path.hops.iter().enumerate() {
1233 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1234 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1235 continue 'path_check;
1238 total_value += path.final_value_msat();
1239 path_errs.push(Ok(()));
1241 if path_errs.iter().any(|e| e.is_err()) {
1242 return Err(PaymentSendFailure::PathParameterError(path_errs));
1244 if let Some(amt_msat) = recv_value_msat {
1245 total_value = amt_msat;
1248 let cur_height = best_block_height + 1;
1249 let mut results = Vec::new();
1250 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1251 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1252 let mut path_res = send_payment_along_path(SendAlongPathArgs {
1253 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1254 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1258 Err(APIError::MonitorUpdateInProgress) => {
1259 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1260 // considered "in flight" and we shouldn't remove it from the
1261 // PendingOutboundPayment set.
1264 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1265 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1266 let removed = payment.remove(&session_priv_bytes, Some(path));
1267 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1269 debug_assert!(false, "This can't happen as the payment was added by callers");
1270 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1274 results.push(path_res);
1276 let mut has_ok = false;
1277 let mut has_err = false;
1278 let mut pending_amt_unsent = 0;
1279 for (res, path) in results.iter().zip(route.paths.iter()) {
1280 if res.is_ok() { has_ok = true; }
1281 if res.is_err() { has_err = true; }
1282 if let &Err(APIError::MonitorUpdateInProgress) = res {
1283 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1287 } else if res.is_err() {
1288 pending_amt_unsent += path.final_value_msat();
1291 if has_err && has_ok {
1292 Err(PaymentSendFailure::PartialFailure {
1295 failed_paths_retry: if pending_amt_unsent != 0 {
1296 if let Some(payment_params) = route.route_params.as_ref().map(|p| p.payment_params.clone()) {
1297 Some(RouteParameters {
1298 payment_params: payment_params,
1299 final_value_msat: pending_amt_unsent,
1305 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1312 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1313 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1314 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1315 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1316 send_payment_along_path: F
1317 ) -> Result<(), PaymentSendFailure>
1319 NS::Target: NodeSigner,
1320 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1322 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1323 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1324 &send_payment_along_path)
1325 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1328 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1329 // map as the payment is free to be resent.
1330 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1331 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1332 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1333 debug_assert!(removed, "We should always have a pending payment to remove here");
1337 pub(super) fn claim_htlc<L: Deref>(
1338 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1339 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1340 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1342 ) where L::Target: Logger {
1343 let mut session_priv_bytes = [0; 32];
1344 session_priv_bytes.copy_from_slice(&session_priv[..]);
1345 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1346 let mut pending_events = pending_events.lock().unwrap();
1347 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1348 if !payment.get().is_fulfilled() {
1349 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1350 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1351 let fee_paid_msat = payment.get().get_pending_fee_msat();
1352 pending_events.push_back((events::Event::PaymentSent {
1353 payment_id: Some(payment_id),
1357 }, Some(ev_completion_action.clone())));
1358 payment.get_mut().mark_fulfilled();
1362 // We currently immediately remove HTLCs which were fulfilled on-chain.
1363 // This could potentially lead to removing a pending payment too early,
1364 // with a reorg of one block causing us to re-add the fulfilled payment on
1366 // TODO: We should have a second monitor event that informs us of payments
1367 // irrevocably fulfilled.
1368 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1369 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1370 pending_events.push_back((events::Event::PaymentPathSuccessful {
1374 }, Some(ev_completion_action)));
1378 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1382 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1383 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1385 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1386 let mut pending_events = pending_events.lock().unwrap();
1387 for source in sources {
1388 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1389 let mut session_priv_bytes = [0; 32];
1390 session_priv_bytes.copy_from_slice(&session_priv[..]);
1391 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1392 assert!(payment.get().is_fulfilled());
1393 if payment.get_mut().remove(&session_priv_bytes, None) {
1394 let payment_hash = payment.get().payment_hash();
1395 debug_assert!(payment_hash.is_some());
1396 pending_events.push_back((events::Event::PaymentPathSuccessful {
1407 pub(super) fn remove_stale_payments(
1408 &self, pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1410 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1411 let mut pending_events = pending_events.lock().unwrap();
1412 pending_outbound_payments.retain(|payment_id, payment| {
1413 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1414 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1415 // this could race the user making a duplicate send_payment call and our idempotency
1416 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1417 // removal. This should be more than sufficient to ensure the idempotency of any
1418 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1420 if let PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } = payment {
1421 let mut no_remaining_entries = session_privs.is_empty();
1422 if no_remaining_entries {
1423 for (ev, _) in pending_events.iter() {
1425 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1426 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1427 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1428 if payment_id == ev_payment_id {
1429 no_remaining_entries = false;
1437 if no_remaining_entries {
1438 *timer_ticks_without_htlcs += 1;
1439 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1441 *timer_ticks_without_htlcs = 0;
1444 } else if let PendingOutboundPayment::AwaitingInvoice { timer_ticks_without_response, .. } = payment {
1445 *timer_ticks_without_response += 1;
1446 if *timer_ticks_without_response <= INVOICE_REQUEST_TIMEOUT_TICKS {
1449 pending_events.push_back(
1450 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1458 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1459 pub(super) fn fail_htlc<L: Deref>(
1460 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1461 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1462 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1463 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1464 ) -> bool where L::Target: Logger {
1466 let DecodedOnionFailure {
1467 network_update, short_channel_id, payment_retryable, onion_error_code, onion_error_data
1468 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1470 let DecodedOnionFailure { network_update, short_channel_id, payment_retryable } =
1471 onion_error.decode_onion_failure(secp_ctx, logger, &source);
1473 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1474 let mut session_priv_bytes = [0; 32];
1475 session_priv_bytes.copy_from_slice(&session_priv[..]);
1476 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1478 // If any payments already need retry, there's no need to generate a redundant
1479 // `PendingHTLCsForwardable`.
1480 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1481 let mut awaiting_retry = false;
1482 if pmt.is_auto_retryable_now() {
1483 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1484 if pending_amt_msat < total_msat {
1485 awaiting_retry = true;
1492 let mut full_failure_ev = None;
1493 let mut pending_retry_ev = false;
1494 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1495 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1496 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1499 if payment.get().is_fulfilled() {
1500 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1503 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1504 if let Some(scid) = short_channel_id {
1505 // TODO: If we decided to blame ourselves (or one of our channels) in
1506 // process_onion_failure we should close that channel as it implies our
1507 // next-hop is needlessly blaming us!
1508 payment.get_mut().insert_previously_failed_scid(scid);
1511 if payment_is_probe || !is_retryable_now || !payment_retryable {
1512 let reason = if !payment_retryable {
1513 PaymentFailureReason::RecipientRejected
1515 PaymentFailureReason::RetriesExhausted
1517 payment.get_mut().mark_abandoned(reason);
1518 is_retryable_now = false;
1520 if payment.get().remaining_parts() == 0 {
1521 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. }= payment.get() {
1522 if !payment_is_probe {
1523 full_failure_ev = Some(events::Event::PaymentFailed {
1524 payment_id: *payment_id,
1525 payment_hash: *payment_hash,
1534 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1537 core::mem::drop(outbounds);
1538 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1540 let path_failure = {
1541 if payment_is_probe {
1542 if !payment_retryable {
1543 events::Event::ProbeSuccessful {
1544 payment_id: *payment_id,
1545 payment_hash: payment_hash.clone(),
1549 events::Event::ProbeFailed {
1550 payment_id: *payment_id,
1551 payment_hash: payment_hash.clone(),
1557 // If we miss abandoning the payment above, we *must* generate an event here or else the
1558 // payment will sit in our outbounds forever.
1559 if attempts_remaining && !already_awaiting_retry {
1560 debug_assert!(full_failure_ev.is_none());
1561 pending_retry_ev = true;
1563 events::Event::PaymentPathFailed {
1564 payment_id: Some(*payment_id),
1565 payment_hash: payment_hash.clone(),
1566 payment_failed_permanently: !payment_retryable,
1567 failure: events::PathFailure::OnPath { network_update },
1571 error_code: onion_error_code,
1573 error_data: onion_error_data
1577 let mut pending_events = pending_events.lock().unwrap();
1578 pending_events.push_back((path_failure, None));
1579 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1583 pub(super) fn abandon_payment(
1584 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1585 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1587 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1588 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1589 payment.get_mut().mark_abandoned(reason);
1590 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1591 if payment.get().remaining_parts() == 0 {
1592 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1594 payment_hash: *payment_hash,
1599 } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1600 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1609 pub fn has_pending_payments(&self) -> bool {
1610 !self.pending_outbound_payments.lock().unwrap().is_empty()
1614 pub fn clear_pending_payments(&self) {
1615 self.pending_outbound_payments.lock().unwrap().clear()
1619 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1621 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1622 probing_cookie_secret: [u8; 32]) -> bool
1624 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1625 target_payment_hash == *payment_hash
1628 /// Returns the 'probing cookie' for the given [`PaymentId`].
1629 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1630 let mut preimage = [0u8; 64];
1631 preimage[..32].copy_from_slice(&probing_cookie_secret);
1632 preimage[32..].copy_from_slice(&payment_id.0);
1633 PaymentHash(Sha256::hash(&preimage).into_inner())
1636 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1638 (0, session_privs, required),
1641 (0, session_privs, required),
1642 (1, payment_hash, option),
1643 (3, timer_ticks_without_htlcs, (default_value, 0)),
1646 (0, session_privs, required),
1647 (1, pending_fee_msat, option),
1648 (2, payment_hash, required),
1649 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1650 // never see it - `payment_params` was added here after the field was added/required.
1651 (3, payment_params, (option: ReadableArgs, 0)),
1652 (4, payment_secret, option),
1653 (5, keysend_preimage, option),
1654 (6, total_msat, required),
1655 (7, payment_metadata, option),
1656 (8, pending_amt_msat, required),
1657 (9, custom_tlvs, optional_vec),
1658 (10, starting_block_height, required),
1659 (not_written, retry_strategy, (static_value, None)),
1660 (not_written, attempts, (static_value, PaymentAttempts::new())),
1663 (0, session_privs, required),
1664 (1, reason, option),
1665 (2, payment_hash, required),
1667 (5, AwaitingInvoice) => {
1668 (0, timer_ticks_without_response, required),
1670 (7, InvoiceReceived) => {
1671 (0, payment_hash, required),
1677 use bitcoin::network::constants::Network;
1678 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1680 use crate::events::{Event, PathFailure, PaymentFailureReason};
1681 use crate::ln::PaymentHash;
1682 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1683 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1684 use crate::ln::msgs::{ErrorAction, LightningError};
1685 use crate::ln::outbound_payment::{INVOICE_REQUEST_TIMEOUT_TICKS, OutboundPayments, Retry, RetryableSendFailure};
1686 use crate::routing::gossip::NetworkGraph;
1687 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1688 use crate::sync::{Arc, Mutex, RwLock};
1689 use crate::util::errors::APIError;
1690 use crate::util::test_utils;
1692 use alloc::collections::VecDeque;
1695 fn test_recipient_onion_fields_with_custom_tlvs() {
1696 let onion_fields = RecipientOnionFields::spontaneous_empty();
1698 let bad_type_range_tlvs = vec![
1702 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1704 let keysend_tlv = vec![
1705 (5482373484, vec![42; 32]),
1707 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1709 let good_tlvs = vec![
1710 ((1 << 16) + 1, vec![42]),
1711 ((1 << 16) + 3, vec![42; 32]),
1713 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1717 #[cfg(feature = "std")]
1718 fn fails_paying_after_expiration() {
1719 do_fails_paying_after_expiration(false);
1720 do_fails_paying_after_expiration(true);
1722 #[cfg(feature = "std")]
1723 fn do_fails_paying_after_expiration(on_retry: bool) {
1724 let outbound_payments = OutboundPayments::new();
1725 let logger = test_utils::TestLogger::new();
1726 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1727 let scorer = RwLock::new(test_utils::TestScorer::new());
1728 let router = test_utils::TestRouter::new(network_graph, &scorer);
1729 let secp_ctx = Secp256k1::new();
1730 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1732 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1733 let payment_params = PaymentParameters::from_node_id(
1734 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1736 ).with_expiry_time(past_expiry_time);
1737 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1738 let pending_events = Mutex::new(VecDeque::new());
1740 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1741 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1742 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1743 &&keys_manager, 0).unwrap();
1744 outbound_payments.find_route_and_send_payment(
1745 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1746 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1748 let events = pending_events.lock().unwrap();
1749 assert_eq!(events.len(), 1);
1750 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1751 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1752 } else { panic!("Unexpected event"); }
1754 let err = outbound_payments.send_payment(
1755 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1756 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1757 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1758 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1763 fn find_route_error() {
1764 do_find_route_error(false);
1765 do_find_route_error(true);
1767 fn do_find_route_error(on_retry: bool) {
1768 let outbound_payments = OutboundPayments::new();
1769 let logger = test_utils::TestLogger::new();
1770 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1771 let scorer = RwLock::new(test_utils::TestScorer::new());
1772 let router = test_utils::TestRouter::new(network_graph, &scorer);
1773 let secp_ctx = Secp256k1::new();
1774 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1776 let payment_params = PaymentParameters::from_node_id(
1777 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1778 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1779 router.expect_find_route(route_params.clone(),
1780 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1782 let pending_events = Mutex::new(VecDeque::new());
1784 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1785 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1786 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1787 &&keys_manager, 0).unwrap();
1788 outbound_payments.find_route_and_send_payment(
1789 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1790 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1792 let events = pending_events.lock().unwrap();
1793 assert_eq!(events.len(), 1);
1794 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1796 let err = outbound_payments.send_payment(
1797 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1798 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1799 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1800 if let RetryableSendFailure::RouteNotFound = err {
1801 } else { panic!("Unexpected error"); }
1806 fn initial_send_payment_path_failed_evs() {
1807 let outbound_payments = OutboundPayments::new();
1808 let logger = test_utils::TestLogger::new();
1809 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1810 let scorer = RwLock::new(test_utils::TestScorer::new());
1811 let router = test_utils::TestRouter::new(network_graph, &scorer);
1812 let secp_ctx = Secp256k1::new();
1813 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1815 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1816 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1817 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1818 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1819 let failed_scid = 42;
1821 paths: vec![Path { hops: vec![RouteHop {
1822 pubkey: receiver_pk,
1823 node_features: NodeFeatures::empty(),
1824 short_channel_id: failed_scid,
1825 channel_features: ChannelFeatures::empty(),
1827 cltv_expiry_delta: 0,
1828 }], blinded_tail: None }],
1829 route_params: Some(route_params.clone()),
1831 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1832 let mut route_params_w_failed_scid = route_params.clone();
1833 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1834 router.expect_find_route(route_params_w_failed_scid, Ok(route.clone()));
1835 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1836 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1838 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1839 // PaymentPathFailed event.
1840 let pending_events = Mutex::new(VecDeque::new());
1841 outbound_payments.send_payment(
1842 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1843 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1844 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1845 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
1846 let mut events = pending_events.lock().unwrap();
1847 assert_eq!(events.len(), 2);
1848 if let Event::PaymentPathFailed {
1850 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1852 assert_eq!(short_channel_id, Some(failed_scid));
1853 } else { panic!("Unexpected event"); }
1854 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1856 core::mem::drop(events);
1858 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1859 outbound_payments.send_payment(
1860 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1861 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1862 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1863 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
1864 assert_eq!(pending_events.lock().unwrap().len(), 0);
1866 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1867 outbound_payments.send_payment(
1868 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1869 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1870 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1871 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
1872 let events = pending_events.lock().unwrap();
1873 assert_eq!(events.len(), 2);
1874 if let Event::PaymentPathFailed {
1876 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
1878 assert_eq!(short_channel_id, None);
1879 } else { panic!("Unexpected event"); }
1880 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1884 fn removes_stale_awaiting_invoice() {
1885 let pending_events = Mutex::new(VecDeque::new());
1886 let outbound_payments = OutboundPayments::new();
1887 let payment_id = PaymentId([0; 32]);
1889 assert!(!outbound_payments.has_pending_payments());
1890 assert!(outbound_payments.add_new_awaiting_invoice(payment_id).is_ok());
1891 assert!(outbound_payments.has_pending_payments());
1893 for _ in 0..INVOICE_REQUEST_TIMEOUT_TICKS {
1894 outbound_payments.remove_stale_payments(&pending_events);
1895 assert!(outbound_payments.has_pending_payments());
1896 assert!(pending_events.lock().unwrap().is_empty());
1899 outbound_payments.remove_stale_payments(&pending_events);
1900 assert!(!outbound_payments.has_pending_payments());
1901 assert!(!pending_events.lock().unwrap().is_empty());
1903 pending_events.lock().unwrap().pop_front(),
1904 Some((Event::InvoiceRequestFailed { payment_id }, None)),
1906 assert!(pending_events.lock().unwrap().is_empty());
1908 assert!(outbound_payments.add_new_awaiting_invoice(payment_id).is_ok());
1909 assert!(outbound_payments.has_pending_payments());
1911 assert!(outbound_payments.add_new_awaiting_invoice(payment_id).is_err());
1915 fn removes_abandoned_awaiting_invoice() {
1916 let pending_events = Mutex::new(VecDeque::new());
1917 let outbound_payments = OutboundPayments::new();
1918 let payment_id = PaymentId([0; 32]);
1920 assert!(!outbound_payments.has_pending_payments());
1921 assert!(outbound_payments.add_new_awaiting_invoice(payment_id).is_ok());
1922 assert!(outbound_payments.has_pending_payments());
1924 outbound_payments.abandon_payment(
1925 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
1927 assert!(!outbound_payments.has_pending_payments());
1928 assert!(!pending_events.lock().unwrap().is_empty());
1930 pending_events.lock().unwrap().pop_front(),
1931 Some((Event::InvoiceRequestFailed { payment_id }, None)),
1933 assert!(pending_events.lock().unwrap().is_empty());