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};
32 use core::time::Duration;
34 use crate::prelude::*;
35 use crate::sync::Mutex;
37 /// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the idempotency
38 /// of payments by [`PaymentId`]. See [`OutboundPayments::remove_stale_payments`].
40 /// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
41 pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
43 /// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
44 /// and later, also stores information for retrying the payment.
45 pub(crate) enum PendingOutboundPayment {
47 session_privs: HashSet<[u8; 32]>,
50 absolute_expiry: Duration,
51 retry_strategy: Retry,
52 max_total_routing_fee_msat: Option<u64>,
55 payment_hash: PaymentHash,
56 retry_strategy: Retry,
57 // Note this field is currently just replicated from AwaitingInvoice but not actually
59 max_total_routing_fee_msat: Option<u64>,
62 retry_strategy: Option<Retry>,
63 attempts: PaymentAttempts,
64 payment_params: Option<PaymentParameters>,
65 session_privs: HashSet<[u8; 32]>,
66 payment_hash: PaymentHash,
67 payment_secret: Option<PaymentSecret>,
68 payment_metadata: Option<Vec<u8>>,
69 keysend_preimage: Option<PaymentPreimage>,
70 custom_tlvs: Vec<(u64, Vec<u8>)>,
71 pending_amt_msat: u64,
72 /// Used to track the fee paid. Only present if the payment was serialized on 0.0.103+.
73 pending_fee_msat: Option<u64>,
74 /// The total payment amount across all paths, used to verify that a retry is not overpaying.
76 /// Our best known block height at the time this payment was initiated.
77 starting_block_height: u32,
78 remaining_max_total_routing_fee_msat: Option<u64>,
80 /// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
81 /// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
82 /// and add a pending payment that was already fulfilled.
84 session_privs: HashSet<[u8; 32]>,
85 /// Filled in for any payment which moved to `Fulfilled` on LDK 0.0.104 or later.
86 payment_hash: Option<PaymentHash>,
87 timer_ticks_without_htlcs: u8,
89 /// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
90 /// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
92 session_privs: HashSet<[u8; 32]>,
93 payment_hash: PaymentHash,
94 /// Will be `None` if the payment was serialized before 0.0.115.
95 reason: Option<PaymentFailureReason>,
99 impl PendingOutboundPayment {
100 fn increment_attempts(&mut self) {
101 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
105 fn is_auto_retryable_now(&self) -> bool {
107 PendingOutboundPayment::Retryable {
108 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
110 strategy.is_retryable_now(&attempts)
115 fn is_retryable_now(&self) -> bool {
117 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
118 // We're handling retries manually, we can always retry.
121 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
122 strategy.is_retryable_now(&attempts)
127 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
128 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
129 params.previously_failed_channels.push(scid);
132 fn is_awaiting_invoice(&self) -> bool {
134 PendingOutboundPayment::AwaitingInvoice { .. } => true,
138 pub(super) fn is_fulfilled(&self) -> bool {
140 PendingOutboundPayment::Fulfilled { .. } => true,
144 pub(super) fn abandoned(&self) -> bool {
146 PendingOutboundPayment::Abandoned { .. } => true,
150 fn get_pending_fee_msat(&self) -> Option<u64> {
152 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
157 fn payment_hash(&self) -> Option<PaymentHash> {
159 PendingOutboundPayment::Legacy { .. } => None,
160 PendingOutboundPayment::AwaitingInvoice { .. } => None,
161 PendingOutboundPayment::InvoiceReceived { payment_hash, .. } => Some(*payment_hash),
162 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
163 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
164 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
168 fn mark_fulfilled(&mut self) {
169 let mut session_privs = HashSet::new();
170 core::mem::swap(&mut session_privs, match self {
171 PendingOutboundPayment::Legacy { session_privs } |
172 PendingOutboundPayment::Retryable { session_privs, .. } |
173 PendingOutboundPayment::Fulfilled { session_privs, .. } |
174 PendingOutboundPayment::Abandoned { session_privs, .. } => session_privs,
175 PendingOutboundPayment::AwaitingInvoice { .. } |
176 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); return; },
178 let payment_hash = self.payment_hash();
179 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
182 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
183 if let PendingOutboundPayment::Retryable { session_privs, payment_hash, .. } = self {
184 let mut our_session_privs = HashSet::new();
185 core::mem::swap(&mut our_session_privs, session_privs);
186 *self = PendingOutboundPayment::Abandoned {
187 session_privs: our_session_privs,
188 payment_hash: *payment_hash,
191 } else if let PendingOutboundPayment::InvoiceReceived { payment_hash, .. } = self {
192 *self = PendingOutboundPayment::Abandoned {
193 session_privs: HashSet::new(),
194 payment_hash: *payment_hash,
200 /// panics if path is None and !self.is_fulfilled
201 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
202 let remove_res = match self {
203 PendingOutboundPayment::Legacy { session_privs } |
204 PendingOutboundPayment::Retryable { session_privs, .. } |
205 PendingOutboundPayment::Fulfilled { session_privs, .. } |
206 PendingOutboundPayment::Abandoned { session_privs, .. } => {
207 session_privs.remove(session_priv)
209 PendingOutboundPayment::AwaitingInvoice { .. } |
210 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
213 if let PendingOutboundPayment::Retryable {
214 ref mut pending_amt_msat, ref mut pending_fee_msat,
215 ref mut remaining_max_total_routing_fee_msat, ..
217 let path = path.expect("Removing a failed payment should always come with a path");
218 *pending_amt_msat -= path.final_value_msat();
219 let path_fee_msat = path.fee_msat();
220 if let Some(fee_msat) = pending_fee_msat.as_mut() {
221 *fee_msat -= path_fee_msat;
224 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
225 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_add(path_fee_msat);
232 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
233 let insert_res = match self {
234 PendingOutboundPayment::Legacy { session_privs } |
235 PendingOutboundPayment::Retryable { session_privs, .. } => {
236 session_privs.insert(session_priv)
238 PendingOutboundPayment::AwaitingInvoice { .. } |
239 PendingOutboundPayment::InvoiceReceived { .. } => { debug_assert!(false); false },
240 PendingOutboundPayment::Fulfilled { .. } => false,
241 PendingOutboundPayment::Abandoned { .. } => false,
244 if let PendingOutboundPayment::Retryable {
245 ref mut pending_amt_msat, ref mut pending_fee_msat,
246 ref mut remaining_max_total_routing_fee_msat, ..
248 *pending_amt_msat += path.final_value_msat();
249 let path_fee_msat = path.fee_msat();
250 if let Some(fee_msat) = pending_fee_msat.as_mut() {
251 *fee_msat += path_fee_msat;
254 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
255 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_sub(path_fee_msat);
262 pub(super) fn remaining_parts(&self) -> usize {
264 PendingOutboundPayment::Legacy { session_privs } |
265 PendingOutboundPayment::Retryable { session_privs, .. } |
266 PendingOutboundPayment::Fulfilled { session_privs, .. } |
267 PendingOutboundPayment::Abandoned { session_privs, .. } => {
270 PendingOutboundPayment::AwaitingInvoice { .. } => 0,
271 PendingOutboundPayment::InvoiceReceived { .. } => 0,
276 /// Strategies available to retry payment path failures.
277 #[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
279 /// Max number of attempts to retry payment.
281 /// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
282 /// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
283 /// were retried along a route from a single call to [`Router::find_route_with_id`].
285 #[cfg(not(feature = "no-std"))]
286 /// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
287 /// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
289 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
290 Timeout(core::time::Duration),
293 #[cfg(feature = "no-std")]
294 impl_writeable_tlv_based_enum!(Retry,
299 #[cfg(not(feature = "no-std"))]
300 impl_writeable_tlv_based_enum!(Retry,
307 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
308 match (self, attempts) {
309 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
310 max_retry_count > count
312 #[cfg(all(not(feature = "no-std"), not(test)))]
313 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
314 *max_duration >= crate::util::time::MonotonicTime::now().duration_since(*first_attempted_at),
315 #[cfg(all(not(feature = "no-std"), test))]
316 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
317 *max_duration >= SinceEpoch::now().duration_since(*first_attempted_at),
322 #[cfg(feature = "std")]
323 pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
324 if let Some(expiry_time) = route_params.payment_params.expiry_time {
325 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
326 return elapsed > core::time::Duration::from_secs(expiry_time)
332 pub(crate) type PaymentAttempts = PaymentAttemptsUsingTime<ConfiguredTime>;
334 /// Storing minimal payment attempts information required for determining if a outbound payment can
336 pub(crate) struct PaymentAttemptsUsingTime<T: Time> {
337 /// This count will be incremented only after the result of the attempt is known. When it's 0,
338 /// it means the result of the first attempt is not known yet.
339 pub(crate) count: u32,
340 /// This field is only used when retry is `Retry::Timeout` which is only build with feature std
341 #[cfg(not(feature = "no-std"))]
342 first_attempted_at: T,
343 #[cfg(feature = "no-std")]
344 phantom: core::marker::PhantomData<T>,
348 #[cfg(not(any(feature = "no-std", test)))]
349 type ConfiguredTime = crate::util::time::MonotonicTime;
350 #[cfg(feature = "no-std")]
351 type ConfiguredTime = crate::util::time::Eternity;
352 #[cfg(all(not(feature = "no-std"), test))]
353 type ConfiguredTime = SinceEpoch;
355 impl<T: Time> PaymentAttemptsUsingTime<T> {
356 pub(crate) fn new() -> Self {
357 PaymentAttemptsUsingTime {
359 #[cfg(not(feature = "no-std"))]
360 first_attempted_at: T::now(),
361 #[cfg(feature = "no-std")]
362 phantom: core::marker::PhantomData,
367 impl<T: Time> Display for PaymentAttemptsUsingTime<T> {
368 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
369 #[cfg(feature = "no-std")]
370 return write!(f, "attempts: {}", self.count);
371 #[cfg(not(feature = "no-std"))]
374 "attempts: {}, duration: {}s",
376 T::now().duration_since(self.first_attempted_at).as_secs()
381 /// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
382 /// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
384 /// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
385 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
386 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
387 #[derive(Clone, Debug, PartialEq, Eq)]
388 pub enum RetryableSendFailure {
389 /// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired. Note
390 /// that this error is *not* caused by [`Retry::Timeout`].
392 /// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
394 /// We were unable to find a route to the destination.
396 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
397 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
399 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
400 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
401 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
405 /// If a payment fails to send with [`ChannelManager::send_payment_with_route`], it can be in one
406 /// of several states. This enum is returned as the Err() type describing which state the payment
407 /// is in, see the description of individual enum states for more.
409 /// [`ChannelManager::send_payment_with_route`]: crate::ln::channelmanager::ChannelManager::send_payment_with_route
410 #[derive(Clone, Debug, PartialEq, Eq)]
411 pub enum PaymentSendFailure {
412 /// A parameter which was passed to send_payment was invalid, preventing us from attempting to
413 /// send the payment at all.
415 /// You can freely resend the payment in full (with the parameter error fixed).
417 /// Because the payment failed outright, no payment tracking is done and no
418 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
420 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
421 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
422 ParameterError(APIError),
423 /// A parameter in a single path which was passed to send_payment was invalid, preventing us
424 /// from attempting to send the payment at all.
426 /// You can freely resend the payment in full (with the parameter error fixed).
428 /// Because the payment failed outright, no payment tracking is done and no
429 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
431 /// The results here are ordered the same as the paths in the route object which was passed to
434 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
435 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
436 PathParameterError(Vec<Result<(), APIError>>),
437 /// All paths which were attempted failed to send, with no channel state change taking place.
438 /// You can freely resend the payment in full (though you probably want to do so over different
439 /// paths than the ones selected).
441 /// Because the payment failed outright, no payment tracking is done and no
442 /// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
444 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
445 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
446 AllFailedResendSafe(Vec<APIError>),
447 /// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
448 /// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
450 /// [`PaymentId`]: crate::ln::channelmanager::PaymentId
451 /// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
452 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
454 /// Some paths that were attempted failed to send, though some paths may have succeeded. At least
455 /// some paths have irrevocably committed to the HTLC.
457 /// The results here are ordered the same as the paths in the route object that was passed to
460 /// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
461 /// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
463 /// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
465 /// The errors themselves, in the same order as the paths from the route.
466 results: Vec<Result<(), APIError>>,
467 /// If some paths failed without irrevocably committing to the new HTLC(s), this will
468 /// contain a [`RouteParameters`] object for the failing paths.
469 failed_paths_retry: Option<RouteParameters>,
470 /// The payment id for the payment, which is now at least partially pending.
471 payment_id: PaymentId,
475 /// An error when attempting to pay a BOLT 12 invoice.
476 #[derive(Clone, Debug, PartialEq, Eq)]
477 pub(super) enum Bolt12PaymentError {
478 /// The invoice was not requested.
480 /// Payment for an invoice with the corresponding [`PaymentId`] was already initiated.
484 /// Indicates that we failed to send a payment probe. Further errors may be surfaced later via
485 /// [`Event::ProbeFailed`].
487 /// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
488 #[derive(Clone, Debug, PartialEq, Eq)]
489 pub enum ProbeSendFailure {
490 /// We were unable to find a route to the destination.
492 /// We failed to send the payment probes.
493 SendingFailed(PaymentSendFailure),
496 /// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
498 /// This should generally be constructed with data communicated to us from the recipient (via a
499 /// BOLT11 or BOLT12 invoice).
500 #[derive(Clone, Debug, PartialEq, Eq)]
501 pub struct RecipientOnionFields {
502 /// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
503 /// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
504 /// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
507 /// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
508 /// multi-path payments require a recipient-provided secret.
510 /// Some implementations may reject spontaneous payments with payment secrets, so you may only
511 /// want to provide a secret for a spontaneous payment if MPP is needed and you know your
512 /// recipient will not reject it.
513 pub payment_secret: Option<PaymentSecret>,
514 /// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
515 /// arbitrary length. This gives recipients substantially more flexibility to receive
518 /// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
519 /// scheme to authenticate received payments against expected payments and invoices, this field
520 /// is not used in LDK for received payments, and can be used to store arbitrary data in
521 /// invoices which will be received with the payment.
523 /// Note that this field was added to the lightning specification more recently than
524 /// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
525 /// may not be supported as universally.
526 pub payment_metadata: Option<Vec<u8>>,
527 /// See [`Self::custom_tlvs`] for more info.
528 pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
531 impl_writeable_tlv_based!(RecipientOnionFields, {
532 (0, payment_secret, option),
533 (1, custom_tlvs, optional_vec),
534 (2, payment_metadata, option),
537 impl RecipientOnionFields {
538 /// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
539 /// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
540 /// but do not require or provide any further data.
541 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
542 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
545 /// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
546 /// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
547 /// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
548 /// a spontaneous MPP this will not work as all MPP require payment secrets; you may
549 /// instead want to use [`RecipientOnionFields::secret_only`].
551 /// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
552 /// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
553 pub fn spontaneous_empty() -> Self {
554 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
557 /// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
558 /// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
559 /// respectively. TLV type numbers must be unique and within the range
560 /// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
562 /// This method will also error for types in the experimental range which have been
563 /// standardized within the protocol, which only includes 5482373484 (keysend) for now.
565 /// See [`Self::custom_tlvs`] for more info.
566 pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
567 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
568 let mut prev_type = None;
569 for (typ, _) in custom_tlvs.iter() {
570 if *typ < 1 << 16 { return Err(()); }
571 if *typ == 5482373484 { return Err(()); } // keysend
573 Some(prev) if prev >= *typ => return Err(()),
576 prev_type = Some(*typ);
578 self.custom_tlvs = custom_tlvs;
582 /// Gets the custom TLVs that will be sent or have been received.
584 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
585 /// additional flexibility on top of payment metadata, as while other implementations may
586 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
587 /// do not have this restriction.
589 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
590 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
591 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
592 #[cfg(not(c_bindings))]
593 pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
597 /// Gets the custom TLVs that will be sent or have been received.
599 /// Custom TLVs allow sending extra application-specific data with a payment. They provide
600 /// additional flexibility on top of payment metadata, as while other implementations may
601 /// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
602 /// do not have this restriction.
604 /// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
605 /// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
606 /// This is validated when setting this field using [`Self::with_custom_tlvs`].
608 pub fn custom_tlvs(&self) -> Vec<(u64, Vec<u8>)> {
609 self.custom_tlvs.clone()
612 /// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
613 /// have to make sure that some fields match exactly across the parts. For those that aren't
614 /// required to match, if they don't match we should remove them so as to not expose data
615 /// that's dependent on the HTLC receive order to users.
617 /// Here we implement this, first checking compatibility then mutating two objects and then
618 /// dropping any remaining non-matching fields from both.
619 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
620 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
621 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
623 let tlvs = &mut self.custom_tlvs;
624 let further_tlvs = &mut further_htlc_fields.custom_tlvs;
626 let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
627 let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
628 if even_tlvs.ne(further_even_tlvs) { return Err(()) }
630 tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
631 further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
637 /// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
638 pub(super) struct SendAlongPathArgs<'a> {
640 pub payment_hash: &'a PaymentHash,
641 pub recipient_onion: RecipientOnionFields,
642 pub total_value: u64,
644 pub payment_id: PaymentId,
645 pub keysend_preimage: &'a Option<PaymentPreimage>,
646 pub session_priv_bytes: [u8; 32],
649 pub(super) struct OutboundPayments {
650 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
651 pub(super) retry_lock: Mutex<()>,
654 impl OutboundPayments {
655 pub(super) fn new() -> Self {
657 pending_outbound_payments: Mutex::new(HashMap::new()),
658 retry_lock: Mutex::new(()),
662 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
663 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
664 retry_strategy: Retry, route_params: RouteParameters, router: &R,
665 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
666 node_signer: &NS, best_block_height: u32, logger: &L,
667 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
668 ) -> Result<(), RetryableSendFailure>
671 ES::Target: EntropySource,
672 NS::Target: NodeSigner,
674 IH: Fn() -> InFlightHtlcs,
675 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
677 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
678 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
679 best_block_height, logger, pending_events, &send_payment_along_path)
682 pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
683 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
684 payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
685 send_payment_along_path: F
686 ) -> Result<(), PaymentSendFailure>
688 ES::Target: EntropySource,
689 NS::Target: NodeSigner,
690 F: Fn(SendAlongPathArgs) -> Result<(), APIError>
692 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)?;
693 self.pay_route_internal(route, payment_hash, recipient_onion, None, payment_id, None,
694 onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
695 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
698 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
699 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
700 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
701 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
702 node_signer: &NS, best_block_height: u32, logger: &L,
703 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
704 ) -> Result<PaymentHash, RetryableSendFailure>
707 ES::Target: EntropySource,
708 NS::Target: NodeSigner,
710 IH: Fn() -> InFlightHtlcs,
711 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
713 let preimage = payment_preimage
714 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
715 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
716 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
717 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
718 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
719 .map(|()| payment_hash)
722 pub(super) fn send_spontaneous_payment_with_route<ES: Deref, NS: Deref, F>(
723 &self, route: &Route, payment_preimage: Option<PaymentPreimage>,
724 recipient_onion: RecipientOnionFields, payment_id: PaymentId, entropy_source: &ES,
725 node_signer: &NS, best_block_height: u32, send_payment_along_path: F
726 ) -> Result<PaymentHash, PaymentSendFailure>
728 ES::Target: EntropySource,
729 NS::Target: NodeSigner,
730 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
732 let preimage = payment_preimage
733 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
734 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).into_inner());
735 let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(),
736 payment_id, Some(preimage), &route, None, None, entropy_source, best_block_height)?;
738 match self.pay_route_internal(route, payment_hash, recipient_onion, Some(preimage),
739 payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
741 Ok(()) => Ok(payment_hash),
743 self.remove_outbound_if_all_failed(payment_id, &e);
750 pub(super) fn send_payment_for_bolt12_invoice<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
751 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
752 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
753 best_block_height: u32, logger: &L,
754 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
755 send_payment_along_path: SP,
756 ) -> Result<(), Bolt12PaymentError>
759 ES::Target: EntropySource,
760 NS::Target: NodeSigner,
762 IH: Fn() -> InFlightHtlcs,
763 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
765 let payment_hash = invoice.payment_hash();
766 let mut max_total_routing_fee_msat = None;
767 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
768 hash_map::Entry::Occupied(entry) => match entry.get() {
769 PendingOutboundPayment::AwaitingInvoice { retry_strategy, max_total_routing_fee_msat: max_total_fee, .. } => {
770 max_total_routing_fee_msat = *max_total_fee;
771 *entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
773 retry_strategy: *retry_strategy,
774 max_total_routing_fee_msat,
777 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
779 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
782 let route_params = RouteParameters {
783 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
784 final_value_msat: invoice.amount_msats(),
785 max_total_routing_fee_msat,
788 self.find_route_and_send_payment(
789 payment_hash, payment_id, route_params, router, first_hops, &inflight_htlcs,
790 entropy_source, node_signer, best_block_height, logger, pending_events,
791 &send_payment_along_path
797 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
798 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
799 best_block_height: u32,
800 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
801 send_payment_along_path: SP,
805 ES::Target: EntropySource,
806 NS::Target: NodeSigner,
807 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
808 IH: Fn() -> InFlightHtlcs,
809 FH: Fn() -> Vec<ChannelDetails>,
812 let _single_thread = self.retry_lock.lock().unwrap();
814 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
815 let mut retry_id_route_params = None;
816 for (pmt_id, pmt) in outbounds.iter_mut() {
817 if pmt.is_auto_retryable_now() {
818 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, remaining_max_total_routing_fee_msat, .. } = pmt {
819 if pending_amt_msat < total_msat {
820 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
821 final_value_msat: *total_msat - *pending_amt_msat,
822 payment_params: params.clone(),
823 max_total_routing_fee_msat: *remaining_max_total_routing_fee_msat,
827 } else { debug_assert!(false); }
830 core::mem::drop(outbounds);
831 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
832 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)
836 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
837 outbounds.retain(|pmt_id, pmt| {
838 let mut retain = true;
839 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
840 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
841 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
842 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
844 payment_hash: *payment_hash,
854 pub(super) fn needs_abandon(&self) -> bool {
855 let outbounds = self.pending_outbound_payments.lock().unwrap();
856 outbounds.iter().any(|(_, pmt)|
857 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
858 !pmt.is_awaiting_invoice())
861 /// Errors immediately on [`RetryableSendFailure`] error conditions. Otherwise, further errors may
862 /// be surfaced asynchronously via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
864 /// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
865 /// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
866 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
867 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
868 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, route_params: RouteParameters,
869 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
870 node_signer: &NS, best_block_height: u32, logger: &L,
871 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
872 ) -> Result<(), RetryableSendFailure>
875 ES::Target: EntropySource,
876 NS::Target: NodeSigner,
878 IH: Fn() -> InFlightHtlcs,
879 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
881 #[cfg(feature = "std")] {
882 if has_expired(&route_params) {
883 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
884 payment_id, payment_hash);
885 return Err(RetryableSendFailure::PaymentExpired)
889 let mut route = router.find_route_with_id(
890 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
891 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
892 payment_hash, payment_id,
894 log_error!(logger, "Failed to find route for payment with id {} and hash {}",
895 payment_id, payment_hash);
896 RetryableSendFailure::RouteNotFound
899 if route.route_params.as_ref() != Some(&route_params) {
901 "Routers are expected to return a Route which includes the requested RouteParameters");
902 route.route_params = Some(route_params.clone());
905 let onion_session_privs = self.add_new_pending_payment(payment_hash,
906 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
907 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
909 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
910 payment_id, payment_hash);
911 RetryableSendFailure::DuplicatePayment
914 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage, payment_id, None,
915 onion_session_privs, node_signer, best_block_height, &send_payment_along_path);
916 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
917 payment_id, payment_hash, res);
918 if let Err(e) = res {
919 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);
924 fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
925 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
926 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
927 node_signer: &NS, best_block_height: u32, logger: &L,
928 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
932 ES::Target: EntropySource,
933 NS::Target: NodeSigner,
935 IH: Fn() -> InFlightHtlcs,
936 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
938 #[cfg(feature = "std")] {
939 if has_expired(&route_params) {
940 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
941 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
946 let mut route = match router.find_route_with_id(
947 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
948 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
949 payment_hash, payment_id,
953 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
954 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
959 if route.route_params.as_ref() != Some(&route_params) {
961 "Routers are expected to return a Route which includes the requested RouteParameters");
962 route.route_params = Some(route_params.clone());
965 for path in route.paths.iter() {
966 if path.hops.len() == 0 {
967 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
968 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
973 macro_rules! abandon_with_entry {
974 ($payment: expr, $reason: expr) => {
975 $payment.get_mut().mark_abandoned($reason);
976 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
977 if $payment.get().remaining_parts() == 0 {
978 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
988 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs) = {
989 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
990 match outbounds.entry(payment_id) {
991 hash_map::Entry::Occupied(mut payment) => {
992 match payment.get() {
993 PendingOutboundPayment::Retryable {
994 total_msat, keysend_preimage, payment_secret, payment_metadata,
995 custom_tlvs, pending_amt_msat, ..
997 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
998 let retry_amt_msat = route.get_total_amount();
999 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
1000 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);
1001 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
1005 if !payment.get().is_retryable_now() {
1006 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
1007 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
1011 let total_msat = *total_msat;
1012 let recipient_onion = RecipientOnionFields {
1013 payment_secret: *payment_secret,
1014 payment_metadata: payment_metadata.clone(),
1015 custom_tlvs: custom_tlvs.clone(),
1017 let keysend_preimage = *keysend_preimage;
1019 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1020 for _ in 0..route.paths.len() {
1021 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1024 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1025 assert!(payment.get_mut().insert(*session_priv_bytes, path));
1028 payment.get_mut().increment_attempts();
1030 (total_msat, recipient_onion, keysend_preimage, onion_session_privs)
1032 PendingOutboundPayment::Legacy { .. } => {
1033 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
1036 PendingOutboundPayment::AwaitingInvoice { .. } => {
1037 log_error!(logger, "Payment not yet sent");
1040 PendingOutboundPayment::InvoiceReceived { payment_hash, retry_strategy, .. } => {
1041 let total_amount = route_params.final_value_msat;
1042 let recipient_onion = RecipientOnionFields {
1043 payment_secret: None,
1044 payment_metadata: None,
1045 custom_tlvs: vec![],
1047 let retry_strategy = Some(*retry_strategy);
1048 let payment_params = Some(route_params.payment_params.clone());
1049 let (retryable_payment, onion_session_privs) = self.create_pending_payment(
1050 *payment_hash, recipient_onion.clone(), None, &route,
1051 retry_strategy, payment_params, entropy_source, best_block_height
1053 *payment.into_mut() = retryable_payment;
1054 (total_amount, recipient_onion, None, onion_session_privs)
1056 PendingOutboundPayment::Fulfilled { .. } => {
1057 log_error!(logger, "Payment already completed");
1060 PendingOutboundPayment::Abandoned { .. } => {
1061 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
1066 hash_map::Entry::Vacant(_) => {
1067 log_error!(logger, "Payment with ID {} not found", &payment_id);
1072 let res = self.pay_route_internal(&route, payment_hash, recipient_onion, keysend_preimage,
1073 payment_id, Some(total_msat), onion_session_privs, node_signer, best_block_height,
1074 &send_payment_along_path);
1075 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1076 if let Err(e) = res {
1077 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);
1081 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1082 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1083 mut route_params: RouteParameters, router: &R, first_hops: Vec<ChannelDetails>,
1084 inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS, best_block_height: u32, logger: &L,
1085 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1089 ES::Target: EntropySource,
1090 NS::Target: NodeSigner,
1092 IH: Fn() -> InFlightHtlcs,
1093 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1096 PaymentSendFailure::AllFailedResendSafe(errs) => {
1097 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);
1098 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);
1100 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1101 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1102 // Some paths were sent, even if we failed to send the full MPP value our recipient may
1103 // misbehave and claim the funds, at which point we have to consider the payment sent, so
1104 // return `Ok()` here, ignoring any retry errors.
1105 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);
1107 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1108 // This may happen if we send a payment and some paths fail, but only due to a temporary
1109 // monitor failure or the like, implying they're really in-flight, but we haven't sent the
1110 // initial HTLC-Add messages yet.
1112 PaymentSendFailure::PathParameterError(results) => {
1113 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1114 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1115 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1117 PaymentSendFailure::ParameterError(e) => {
1118 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1119 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1121 PaymentSendFailure::DuplicatePayment => debug_assert!(false), // unreachable
1125 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1126 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1127 paths: Vec<Path>, path_results: I, logger: &L,
1128 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1129 ) where L::Target: Logger {
1130 let mut events = pending_events.lock().unwrap();
1131 debug_assert_eq!(paths.len(), path_results.len());
1132 for (path, path_res) in paths.into_iter().zip(path_results) {
1133 if let Err(e) = path_res {
1134 if let APIError::MonitorUpdateInProgress = e { continue }
1135 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1136 let mut failed_scid = None;
1137 if let APIError::ChannelUnavailable { .. } = e {
1138 let scid = path.hops[0].short_channel_id;
1139 failed_scid = Some(scid);
1140 route_params.payment_params.previously_failed_channels.push(scid);
1142 events.push_back((events::Event::PaymentPathFailed {
1143 payment_id: Some(payment_id),
1145 payment_failed_permanently: false,
1146 failure: events::PathFailure::InitialSend { err: e },
1148 short_channel_id: failed_scid,
1158 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1159 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1160 best_block_height: u32, send_payment_along_path: F
1161 ) -> Result<(PaymentHash, PaymentId), PaymentSendFailure>
1163 ES::Target: EntropySource,
1164 NS::Target: NodeSigner,
1165 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1167 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1168 let payment_secret = PaymentSecret(entropy_source.get_secure_random_bytes());
1170 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1172 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1173 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError {
1174 err: "No need probing a path with less than two hops".to_string()
1178 let route = Route { paths: vec![path], route_params: None };
1179 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1180 RecipientOnionFields::secret_only(payment_secret), payment_id, None, &route, None, None,
1181 entropy_source, best_block_height)?;
1183 match self.pay_route_internal(&route, payment_hash, RecipientOnionFields::spontaneous_empty(),
1184 None, payment_id, None, onion_session_privs, node_signer, best_block_height, &send_payment_along_path
1186 Ok(()) => Ok((payment_hash, payment_id)),
1188 self.remove_outbound_if_all_failed(payment_id, &e);
1195 pub(super) fn test_set_payment_metadata(
1196 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1198 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1199 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1200 *payment_metadata = new_payment_metadata;
1202 _ => panic!("Need a retryable payment to update metadata on"),
1207 pub(super) fn test_add_new_pending_payment<ES: Deref>(
1208 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1209 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1210 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1211 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1214 pub(super) fn add_new_pending_payment<ES: Deref>(
1215 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1216 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1217 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1218 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1219 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1220 match pending_outbounds.entry(payment_id) {
1221 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1222 hash_map::Entry::Vacant(entry) => {
1223 let (payment, onion_session_privs) = self.create_pending_payment(
1224 payment_hash, recipient_onion, keysend_preimage, route, retry_strategy,
1225 payment_params, entropy_source, best_block_height
1227 entry.insert(payment);
1228 Ok(onion_session_privs)
1233 fn create_pending_payment<ES: Deref>(
1234 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1235 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1236 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1237 ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1239 ES::Target: EntropySource,
1241 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1242 for _ in 0..route.paths.len() {
1243 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1246 let mut payment = PendingOutboundPayment::Retryable {
1248 attempts: PaymentAttempts::new(),
1250 session_privs: HashSet::new(),
1251 pending_amt_msat: 0,
1252 pending_fee_msat: Some(0),
1254 payment_secret: recipient_onion.payment_secret,
1255 payment_metadata: recipient_onion.payment_metadata,
1257 custom_tlvs: recipient_onion.custom_tlvs,
1258 starting_block_height: best_block_height,
1259 total_msat: route.get_total_amount(),
1260 remaining_max_total_routing_fee_msat:
1261 route.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat),
1264 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1265 assert!(payment.insert(*session_priv_bytes, path));
1268 (payment, onion_session_privs)
1271 pub(super) fn add_new_awaiting_invoice(
1272 &self, payment_id: PaymentId, absolute_expiry: Duration, retry_strategy: Retry,
1273 max_total_routing_fee_msat: Option<u64>
1274 ) -> Result<(), ()> {
1275 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1276 match pending_outbounds.entry(payment_id) {
1277 hash_map::Entry::Occupied(_) => Err(()),
1278 hash_map::Entry::Vacant(entry) => {
1279 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1282 max_total_routing_fee_msat,
1290 fn pay_route_internal<NS: Deref, F>(
1291 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1292 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1293 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1294 send_payment_along_path: &F
1295 ) -> Result<(), PaymentSendFailure>
1297 NS::Target: NodeSigner,
1298 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1300 if route.paths.len() < 1 {
1301 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1303 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
1304 && !route.paths.iter().any(|p| p.blinded_tail.is_some())
1306 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1308 let mut total_value = 0;
1309 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); // TODO no unwrap
1310 let mut path_errs = Vec::with_capacity(route.paths.len());
1311 'path_check: for path in route.paths.iter() {
1312 if path.hops.len() < 1 || path.hops.len() > 20 {
1313 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1314 continue 'path_check;
1316 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1317 usize::max_value() } else { path.hops.len() - 1 };
1318 for (idx, hop) in path.hops.iter().enumerate() {
1319 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1320 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1321 continue 'path_check;
1324 total_value += path.final_value_msat();
1325 path_errs.push(Ok(()));
1327 if path_errs.iter().any(|e| e.is_err()) {
1328 return Err(PaymentSendFailure::PathParameterError(path_errs));
1330 if let Some(amt_msat) = recv_value_msat {
1331 total_value = amt_msat;
1334 let cur_height = best_block_height + 1;
1335 let mut results = Vec::new();
1336 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1337 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.into_iter()) {
1338 let mut path_res = send_payment_along_path(SendAlongPathArgs {
1339 path: &path, payment_hash: &payment_hash, recipient_onion: recipient_onion.clone(),
1340 total_value, cur_height, payment_id, keysend_preimage: &keysend_preimage, session_priv_bytes
1344 Err(APIError::MonitorUpdateInProgress) => {
1345 // While a MonitorUpdateInProgress is an Err(_), the payment is still
1346 // considered "in flight" and we shouldn't remove it from the
1347 // PendingOutboundPayment set.
1350 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1351 if let Some(payment) = pending_outbounds.get_mut(&payment_id) {
1352 let removed = payment.remove(&session_priv_bytes, Some(path));
1353 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1355 debug_assert!(false, "This can't happen as the payment was added by callers");
1356 path_res = Err(APIError::APIMisuseError { err: "Internal error: payment disappeared during processing. Please report this bug!".to_owned() });
1360 results.push(path_res);
1362 let mut has_ok = false;
1363 let mut has_err = false;
1364 let mut has_unsent = false;
1365 let mut total_ok_fees_msat = 0;
1366 let mut total_ok_amt_sent_msat = 0;
1367 for (res, path) in results.iter().zip(route.paths.iter()) {
1370 total_ok_fees_msat += path.fee_msat();
1371 total_ok_amt_sent_msat += path.final_value_msat();
1373 if res.is_err() { has_err = true; }
1374 if let &Err(APIError::MonitorUpdateInProgress) = res {
1375 // MonitorUpdateInProgress is inherently unsafe to retry, so we call it a
1379 total_ok_fees_msat += path.fee_msat();
1380 total_ok_amt_sent_msat += path.final_value_msat();
1381 } else if res.is_err() {
1385 if has_err && has_ok {
1386 Err(PaymentSendFailure::PartialFailure {
1389 failed_paths_retry: if has_unsent {
1390 if let Some(route_params) = &route.route_params {
1391 let mut route_params = route_params.clone();
1392 // We calculate the leftover fee budget we're allowed to spend by
1393 // subtracting the used fee from the total fee budget.
1394 route_params.max_total_routing_fee_msat = route_params
1395 .max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
1397 // We calculate the remaining target amount by subtracting the succeded
1399 route_params.final_value_msat = route_params.final_value_msat
1400 .saturating_sub(total_ok_amt_sent_msat);
1406 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1413 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1414 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1415 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1416 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1417 send_payment_along_path: F
1418 ) -> Result<(), PaymentSendFailure>
1420 NS::Target: NodeSigner,
1421 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1423 self.pay_route_internal(route, payment_hash, recipient_onion, keysend_preimage, payment_id,
1424 recv_value_msat, onion_session_privs, node_signer, best_block_height,
1425 &send_payment_along_path)
1426 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1429 // If we failed to send any paths, remove the new PaymentId from the `pending_outbound_payments`
1430 // map as the payment is free to be resent.
1431 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1432 if let &PaymentSendFailure::AllFailedResendSafe(_) = err {
1433 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1434 debug_assert!(removed, "We should always have a pending payment to remove here");
1438 pub(super) fn claim_htlc<L: Deref>(
1439 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1440 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1441 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1443 ) where L::Target: Logger {
1444 let mut session_priv_bytes = [0; 32];
1445 session_priv_bytes.copy_from_slice(&session_priv[..]);
1446 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1447 let mut pending_events = pending_events.lock().unwrap();
1448 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1449 if !payment.get().is_fulfilled() {
1450 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).into_inner());
1451 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1452 let fee_paid_msat = payment.get().get_pending_fee_msat();
1453 pending_events.push_back((events::Event::PaymentSent {
1454 payment_id: Some(payment_id),
1458 }, Some(ev_completion_action.clone())));
1459 payment.get_mut().mark_fulfilled();
1463 // We currently immediately remove HTLCs which were fulfilled on-chain.
1464 // This could potentially lead to removing a pending payment too early,
1465 // with a reorg of one block causing us to re-add the fulfilled payment on
1467 // TODO: We should have a second monitor event that informs us of payments
1468 // irrevocably fulfilled.
1469 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1470 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).into_inner()));
1471 pending_events.push_back((events::Event::PaymentPathSuccessful {
1475 }, Some(ev_completion_action)));
1479 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1483 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1484 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1486 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1487 let mut pending_events = pending_events.lock().unwrap();
1488 for source in sources {
1489 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1490 let mut session_priv_bytes = [0; 32];
1491 session_priv_bytes.copy_from_slice(&session_priv[..]);
1492 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1493 assert!(payment.get().is_fulfilled());
1494 if payment.get_mut().remove(&session_priv_bytes, None) {
1495 let payment_hash = payment.get().payment_hash();
1496 debug_assert!(payment_hash.is_some());
1497 pending_events.push_back((events::Event::PaymentPathSuccessful {
1508 pub(super) fn remove_stale_payments(
1509 &self, duration_since_epoch: Duration,
1510 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1512 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
1513 #[cfg(not(invreqfailed))]
1514 let pending_events = pending_events.lock().unwrap();
1515 #[cfg(invreqfailed)]
1516 let mut pending_events = pending_events.lock().unwrap();
1517 pending_outbound_payments.retain(|payment_id, payment| match payment {
1518 // If an outbound payment was completed, and no pending HTLCs remain, we should remove it
1519 // from the map. However, if we did that immediately when the last payment HTLC is claimed,
1520 // this could race the user making a duplicate send_payment call and our idempotency
1521 // guarantees would be violated. Instead, we wait a few timer ticks to do the actual
1522 // removal. This should be more than sufficient to ensure the idempotency of any
1523 // `send_payment` calls that were made at the same time the `PaymentSent` event was being
1525 PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
1526 let mut no_remaining_entries = session_privs.is_empty();
1527 if no_remaining_entries {
1528 for (ev, _) in pending_events.iter() {
1530 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
1531 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
1532 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
1533 if payment_id == ev_payment_id {
1534 no_remaining_entries = false;
1542 if no_remaining_entries {
1543 *timer_ticks_without_htlcs += 1;
1544 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
1546 *timer_ticks_without_htlcs = 0;
1550 PendingOutboundPayment::AwaitingInvoice { absolute_expiry, .. } => {
1551 if duration_since_epoch < *absolute_expiry {
1554 #[cfg(invreqfailed)]
1555 pending_events.push_back(
1556 (events::Event::InvoiceRequestFailed { payment_id: *payment_id }, None)
1565 // Returns a bool indicating whether a PendingHTLCsForwardable event should be generated.
1566 pub(super) fn fail_htlc<L: Deref>(
1567 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
1568 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
1569 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
1570 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1571 ) -> bool where L::Target: Logger {
1573 let DecodedOnionFailure {
1574 network_update, short_channel_id, payment_failed_permanently, onion_error_code,
1576 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
1578 let DecodedOnionFailure { network_update, short_channel_id, payment_failed_permanently } =
1579 onion_error.decode_onion_failure(secp_ctx, logger, &source);
1581 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
1582 let mut session_priv_bytes = [0; 32];
1583 session_priv_bytes.copy_from_slice(&session_priv[..]);
1584 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1586 // If any payments already need retry, there's no need to generate a redundant
1587 // `PendingHTLCsForwardable`.
1588 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
1589 let mut awaiting_retry = false;
1590 if pmt.is_auto_retryable_now() {
1591 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
1592 if pending_amt_msat < total_msat {
1593 awaiting_retry = true;
1600 let mut full_failure_ev = None;
1601 let mut pending_retry_ev = false;
1602 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
1603 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1604 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1607 if payment.get().is_fulfilled() {
1608 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
1611 let mut is_retryable_now = payment.get().is_auto_retryable_now();
1612 if let Some(scid) = short_channel_id {
1613 // TODO: If we decided to blame ourselves (or one of our channels) in
1614 // process_onion_failure we should close that channel as it implies our
1615 // next-hop is needlessly blaming us!
1616 payment.get_mut().insert_previously_failed_scid(scid);
1619 if payment_is_probe || !is_retryable_now || payment_failed_permanently {
1620 let reason = if payment_failed_permanently {
1621 PaymentFailureReason::RecipientRejected
1623 PaymentFailureReason::RetriesExhausted
1625 payment.get_mut().mark_abandoned(reason);
1626 is_retryable_now = false;
1628 if payment.get().remaining_parts() == 0 {
1629 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1630 if !payment_is_probe {
1631 full_failure_ev = Some(events::Event::PaymentFailed {
1632 payment_id: *payment_id,
1633 payment_hash: *payment_hash,
1642 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
1645 core::mem::drop(outbounds);
1646 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
1648 let path_failure = {
1649 if payment_is_probe {
1650 if payment_failed_permanently {
1651 events::Event::ProbeSuccessful {
1652 payment_id: *payment_id,
1653 payment_hash: payment_hash.clone(),
1657 events::Event::ProbeFailed {
1658 payment_id: *payment_id,
1659 payment_hash: payment_hash.clone(),
1665 // If we miss abandoning the payment above, we *must* generate an event here or else the
1666 // payment will sit in our outbounds forever.
1667 if attempts_remaining && !already_awaiting_retry {
1668 debug_assert!(full_failure_ev.is_none());
1669 pending_retry_ev = true;
1671 events::Event::PaymentPathFailed {
1672 payment_id: Some(*payment_id),
1673 payment_hash: payment_hash.clone(),
1674 payment_failed_permanently,
1675 failure: events::PathFailure::OnPath { network_update },
1679 error_code: onion_error_code,
1681 error_data: onion_error_data
1685 let mut pending_events = pending_events.lock().unwrap();
1686 pending_events.push_back((path_failure, None));
1687 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
1691 pub(super) fn abandon_payment(
1692 &self, payment_id: PaymentId, reason: PaymentFailureReason,
1693 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
1695 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1696 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1697 payment.get_mut().mark_abandoned(reason);
1698 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
1699 if payment.get().remaining_parts() == 0 {
1700 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1702 payment_hash: *payment_hash,
1707 } else if let PendingOutboundPayment::AwaitingInvoice { .. } = payment.get() {
1708 #[cfg(invreqfailed)]
1709 pending_events.lock().unwrap().push_back((events::Event::InvoiceRequestFailed {
1718 pub fn has_pending_payments(&self) -> bool {
1719 !self.pending_outbound_payments.lock().unwrap().is_empty()
1723 pub fn clear_pending_payments(&self) {
1724 self.pending_outbound_payments.lock().unwrap().clear()
1728 /// Returns whether a payment with the given [`PaymentHash`] and [`PaymentId`] is, in fact, a
1730 pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
1731 probing_cookie_secret: [u8; 32]) -> bool
1733 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
1734 target_payment_hash == *payment_hash
1737 /// Returns the 'probing cookie' for the given [`PaymentId`].
1738 fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
1739 let mut preimage = [0u8; 64];
1740 preimage[..32].copy_from_slice(&probing_cookie_secret);
1741 preimage[32..].copy_from_slice(&payment_id.0);
1742 PaymentHash(Sha256::hash(&preimage).into_inner())
1745 impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
1747 (0, session_privs, required),
1750 (0, session_privs, required),
1751 (1, payment_hash, option),
1752 (3, timer_ticks_without_htlcs, (default_value, 0)),
1755 (0, session_privs, required),
1756 (1, pending_fee_msat, option),
1757 (2, payment_hash, required),
1758 // Note that while we "default" payment_param's final CLTV expiry delta to 0 we should
1759 // never see it - `payment_params` was added here after the field was added/required.
1760 (3, payment_params, (option: ReadableArgs, 0)),
1761 (4, payment_secret, option),
1762 (5, keysend_preimage, option),
1763 (6, total_msat, required),
1764 (7, payment_metadata, option),
1765 (8, pending_amt_msat, required),
1766 (9, custom_tlvs, optional_vec),
1767 (10, starting_block_height, required),
1768 (11, remaining_max_total_routing_fee_msat, option),
1769 (not_written, retry_strategy, (static_value, None)),
1770 (not_written, attempts, (static_value, PaymentAttempts::new())),
1773 (0, session_privs, required),
1774 (1, reason, option),
1775 (2, payment_hash, required),
1777 (5, AwaitingInvoice) => {
1778 (0, absolute_expiry, required),
1779 (2, retry_strategy, required),
1780 (4, max_total_routing_fee_msat, option),
1782 (7, InvoiceReceived) => {
1783 (0, payment_hash, required),
1784 (2, retry_strategy, required),
1785 (4, max_total_routing_fee_msat, option),
1791 use bitcoin::network::constants::Network;
1792 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
1794 use core::time::Duration;
1796 use crate::events::{Event, PathFailure, PaymentFailureReason};
1797 use crate::ln::PaymentHash;
1798 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
1799 use crate::ln::features::{ChannelFeatures, NodeFeatures};
1800 use crate::ln::msgs::{ErrorAction, LightningError};
1801 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, Retry, RetryableSendFailure};
1802 use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
1803 use crate::offers::offer::OfferBuilder;
1804 use crate::offers::test_utils::*;
1805 use crate::routing::gossip::NetworkGraph;
1806 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
1807 use crate::sync::{Arc, Mutex, RwLock};
1808 use crate::util::errors::APIError;
1809 use crate::util::test_utils;
1811 use alloc::collections::VecDeque;
1814 fn test_recipient_onion_fields_with_custom_tlvs() {
1815 let onion_fields = RecipientOnionFields::spontaneous_empty();
1817 let bad_type_range_tlvs = vec![
1821 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
1823 let keysend_tlv = vec![
1824 (5482373484, vec![42; 32]),
1826 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
1828 let good_tlvs = vec![
1829 ((1 << 16) + 1, vec![42]),
1830 ((1 << 16) + 3, vec![42; 32]),
1832 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
1836 #[cfg(feature = "std")]
1837 fn fails_paying_after_expiration() {
1838 do_fails_paying_after_expiration(false);
1839 do_fails_paying_after_expiration(true);
1841 #[cfg(feature = "std")]
1842 fn do_fails_paying_after_expiration(on_retry: bool) {
1843 let outbound_payments = OutboundPayments::new();
1844 let logger = test_utils::TestLogger::new();
1845 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1846 let scorer = RwLock::new(test_utils::TestScorer::new());
1847 let router = test_utils::TestRouter::new(network_graph, &scorer);
1848 let secp_ctx = Secp256k1::new();
1849 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1851 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
1852 let payment_params = PaymentParameters::from_node_id(
1853 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
1855 ).with_expiry_time(past_expiry_time);
1856 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1857 let pending_events = Mutex::new(VecDeque::new());
1859 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1860 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1861 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
1862 &&keys_manager, 0).unwrap();
1863 outbound_payments.find_route_and_send_payment(
1864 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
1865 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1867 let events = pending_events.lock().unwrap();
1868 assert_eq!(events.len(), 1);
1869 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
1870 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
1871 } else { panic!("Unexpected event"); }
1873 let err = outbound_payments.send_payment(
1874 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1875 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
1876 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1877 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
1882 fn find_route_error() {
1883 do_find_route_error(false);
1884 do_find_route_error(true);
1886 fn do_find_route_error(on_retry: bool) {
1887 let outbound_payments = OutboundPayments::new();
1888 let logger = test_utils::TestLogger::new();
1889 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1890 let scorer = RwLock::new(test_utils::TestScorer::new());
1891 let router = test_utils::TestRouter::new(network_graph, &scorer);
1892 let secp_ctx = Secp256k1::new();
1893 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1895 let payment_params = PaymentParameters::from_node_id(
1896 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
1897 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
1898 router.expect_find_route(route_params.clone(),
1899 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
1901 let pending_events = Mutex::new(VecDeque::new());
1903 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
1904 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
1905 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
1906 &&keys_manager, 0).unwrap();
1907 outbound_payments.find_route_and_send_payment(
1908 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
1909 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1911 let events = pending_events.lock().unwrap();
1912 assert_eq!(events.len(), 1);
1913 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
1915 let err = outbound_payments.send_payment(
1916 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1917 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
1918 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
1919 if let RetryableSendFailure::RouteNotFound = err {
1920 } else { panic!("Unexpected error"); }
1925 fn initial_send_payment_path_failed_evs() {
1926 let outbound_payments = OutboundPayments::new();
1927 let logger = test_utils::TestLogger::new();
1928 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
1929 let scorer = RwLock::new(test_utils::TestScorer::new());
1930 let router = test_utils::TestRouter::new(network_graph, &scorer);
1931 let secp_ctx = Secp256k1::new();
1932 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
1934 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
1935 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
1936 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
1937 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
1938 let failed_scid = 42;
1940 paths: vec![Path { hops: vec![RouteHop {
1941 pubkey: receiver_pk,
1942 node_features: NodeFeatures::empty(),
1943 short_channel_id: failed_scid,
1944 channel_features: ChannelFeatures::empty(),
1946 cltv_expiry_delta: 0,
1947 maybe_announced_channel: true,
1948 }], blinded_tail: None }],
1949 route_params: Some(route_params.clone()),
1951 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1952 let mut route_params_w_failed_scid = route_params.clone();
1953 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
1954 let mut route_w_failed_scid = route.clone();
1955 route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
1956 router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
1957 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1958 router.expect_find_route(route_params.clone(), Ok(route.clone()));
1960 // Ensure that a ChannelUnavailable error will result in blaming an scid in the
1961 // PaymentPathFailed event.
1962 let pending_events = Mutex::new(VecDeque::new());
1963 outbound_payments.send_payment(
1964 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1965 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1966 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1967 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
1968 let mut events = pending_events.lock().unwrap();
1969 assert_eq!(events.len(), 2);
1970 if let Event::PaymentPathFailed {
1972 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
1974 assert_eq!(short_channel_id, Some(failed_scid));
1975 } else { panic!("Unexpected event"); }
1976 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
1978 core::mem::drop(events);
1980 // Ensure that a MonitorUpdateInProgress "error" will not result in a PaymentPathFailed event.
1981 outbound_payments.send_payment(
1982 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
1983 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1984 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1985 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
1986 assert_eq!(pending_events.lock().unwrap().len(), 0);
1988 // Ensure that any other error will result in a PaymentPathFailed event but no blamed scid.
1989 outbound_payments.send_payment(
1990 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
1991 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
1992 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
1993 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
1994 let events = pending_events.lock().unwrap();
1995 assert_eq!(events.len(), 2);
1996 if let Event::PaymentPathFailed {
1998 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
2000 assert_eq!(short_channel_id, None);
2001 } else { panic!("Unexpected event"); }
2002 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2006 #[cfg(invreqfailed)]
2007 fn removes_stale_awaiting_invoice() {
2008 let pending_events = Mutex::new(VecDeque::new());
2009 let outbound_payments = OutboundPayments::new();
2010 let payment_id = PaymentId([0; 32]);
2011 let absolute_expiry = 100;
2012 let tick_interval = 10;
2014 assert!(!outbound_payments.has_pending_payments());
2016 outbound_payments.add_new_awaiting_invoice(
2017 payment_id, Duration::from_secs(absolute_expiry), Retry::Attempts(0), None
2020 assert!(outbound_payments.has_pending_payments());
2022 for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
2023 let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
2024 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2026 assert!(outbound_payments.has_pending_payments());
2027 assert!(pending_events.lock().unwrap().is_empty());
2030 let duration_since_epoch = Duration::from_secs(absolute_expiry);
2031 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2033 assert!(!outbound_payments.has_pending_payments());
2034 assert!(!pending_events.lock().unwrap().is_empty());
2036 pending_events.lock().unwrap().pop_front(),
2037 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2039 assert!(pending_events.lock().unwrap().is_empty());
2042 outbound_payments.add_new_awaiting_invoice(
2043 payment_id, Duration::from_secs(absolute_expiry + 1), Retry::Attempts(0), None
2046 assert!(outbound_payments.has_pending_payments());
2049 outbound_payments.add_new_awaiting_invoice(
2050 payment_id, Duration::from_secs(absolute_expiry + 1), Retry::Attempts(0), None
2056 #[cfg(invreqfailed)]
2057 fn removes_abandoned_awaiting_invoice() {
2058 let pending_events = Mutex::new(VecDeque::new());
2059 let outbound_payments = OutboundPayments::new();
2060 let payment_id = PaymentId([0; 32]);
2061 let absolute_expiry = 100;
2063 assert!(!outbound_payments.has_pending_payments());
2065 outbound_payments.add_new_awaiting_invoice(
2066 payment_id, Duration::from_secs(absolute_expiry), Retry::Attempts(0), None
2069 assert!(outbound_payments.has_pending_payments());
2071 outbound_payments.abandon_payment(
2072 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
2074 assert!(!outbound_payments.has_pending_payments());
2075 assert!(!pending_events.lock().unwrap().is_empty());
2077 pending_events.lock().unwrap().pop_front(),
2078 Some((Event::InvoiceRequestFailed { payment_id }, None)),
2080 assert!(pending_events.lock().unwrap().is_empty());
2083 #[cfg(feature = "std")]
2085 fn fails_sending_payment_for_expired_bolt12_invoice() {
2086 let logger = test_utils::TestLogger::new();
2087 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2088 let scorer = RwLock::new(test_utils::TestScorer::new());
2089 let router = test_utils::TestRouter::new(network_graph, &scorer);
2090 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2092 let pending_events = Mutex::new(VecDeque::new());
2093 let outbound_payments = OutboundPayments::new();
2094 let payment_id = PaymentId([0; 32]);
2095 let absolute_expiry = 100;
2098 outbound_payments.add_new_awaiting_invoice(
2099 payment_id, Duration::from_secs(absolute_expiry), Retry::Attempts(0), None
2102 assert!(outbound_payments.has_pending_payments());
2104 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2105 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2108 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2110 .sign(payer_sign).unwrap()
2111 .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2113 .sign(recipient_sign).unwrap();
2116 outbound_payments.send_payment_for_bolt12_invoice(
2117 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2118 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2122 assert!(!outbound_payments.has_pending_payments());
2124 let payment_hash = invoice.payment_hash();
2125 let reason = Some(PaymentFailureReason::PaymentExpired);
2127 assert!(!pending_events.lock().unwrap().is_empty());
2129 pending_events.lock().unwrap().pop_front(),
2130 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2132 assert!(pending_events.lock().unwrap().is_empty());
2136 fn fails_finding_route_for_bolt12_invoice() {
2137 let logger = test_utils::TestLogger::new();
2138 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2139 let scorer = RwLock::new(test_utils::TestScorer::new());
2140 let router = test_utils::TestRouter::new(network_graph, &scorer);
2141 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2143 let pending_events = Mutex::new(VecDeque::new());
2144 let outbound_payments = OutboundPayments::new();
2145 let payment_id = PaymentId([0; 32]);
2146 let absolute_expiry = 100;
2148 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2151 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2153 .sign(payer_sign).unwrap()
2154 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2156 .sign(recipient_sign).unwrap();
2159 outbound_payments.add_new_awaiting_invoice(
2160 payment_id, Duration::from_secs(absolute_expiry), Retry::Attempts(0),
2161 Some(invoice.amount_msats() / 100 + 50_000)
2164 assert!(outbound_payments.has_pending_payments());
2166 router.expect_find_route(
2167 RouteParameters::from_payment_params_and_value(
2168 PaymentParameters::from_bolt12_invoice(&invoice),
2169 invoice.amount_msats(),
2171 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2175 outbound_payments.send_payment_for_bolt12_invoice(
2176 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2177 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2181 assert!(!outbound_payments.has_pending_payments());
2183 let payment_hash = invoice.payment_hash();
2184 let reason = Some(PaymentFailureReason::RouteNotFound);
2186 assert!(!pending_events.lock().unwrap().is_empty());
2188 pending_events.lock().unwrap().pop_front(),
2189 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2191 assert!(pending_events.lock().unwrap().is_empty());
2195 fn fails_paying_for_bolt12_invoice() {
2196 let logger = test_utils::TestLogger::new();
2197 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2198 let scorer = RwLock::new(test_utils::TestScorer::new());
2199 let router = test_utils::TestRouter::new(network_graph, &scorer);
2200 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2202 let pending_events = Mutex::new(VecDeque::new());
2203 let outbound_payments = OutboundPayments::new();
2204 let payment_id = PaymentId([0; 32]);
2205 let absolute_expiry = 100;
2207 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2210 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2212 .sign(payer_sign).unwrap()
2213 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2215 .sign(recipient_sign).unwrap();
2218 outbound_payments.add_new_awaiting_invoice(
2219 payment_id, Duration::from_secs(absolute_expiry), Retry::Attempts(0),
2220 Some(invoice.amount_msats() / 100 + 50_000)
2223 assert!(outbound_payments.has_pending_payments());
2225 let route_params = RouteParameters::from_payment_params_and_value(
2226 PaymentParameters::from_bolt12_invoice(&invoice),
2227 invoice.amount_msats(),
2229 router.expect_find_route(
2230 route_params.clone(), Ok(Route { paths: vec![], route_params: Some(route_params) })
2234 outbound_payments.send_payment_for_bolt12_invoice(
2235 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2236 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2240 assert!(!outbound_payments.has_pending_payments());
2242 let payment_hash = invoice.payment_hash();
2243 let reason = Some(PaymentFailureReason::UnexpectedError);
2245 assert!(!pending_events.lock().unwrap().is_empty());
2247 pending_events.lock().unwrap().pop_front(),
2248 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2250 assert!(pending_events.lock().unwrap().is_empty());
2254 fn sends_payment_for_bolt12_invoice() {
2255 let logger = test_utils::TestLogger::new();
2256 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2257 let scorer = RwLock::new(test_utils::TestScorer::new());
2258 let router = test_utils::TestRouter::new(network_graph, &scorer);
2259 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2261 let pending_events = Mutex::new(VecDeque::new());
2262 let outbound_payments = OutboundPayments::new();
2263 let payment_id = PaymentId([0; 32]);
2264 let absolute_expiry = 100;
2266 let invoice = OfferBuilder::new("foo".into(), recipient_pubkey())
2269 .request_invoice(vec![1; 32], payer_pubkey()).unwrap()
2271 .sign(payer_sign).unwrap()
2272 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2274 .sign(recipient_sign).unwrap();
2276 let route_params = RouteParameters {
2277 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2278 final_value_msat: invoice.amount_msats(),
2279 max_total_routing_fee_msat: Some(1234),
2281 router.expect_find_route(
2282 route_params.clone(),
2288 pubkey: recipient_pubkey(),
2289 node_features: NodeFeatures::empty(),
2290 short_channel_id: 42,
2291 channel_features: ChannelFeatures::empty(),
2292 fee_msat: invoice.amount_msats(),
2293 cltv_expiry_delta: 0,
2294 maybe_announced_channel: true,
2300 route_params: Some(route_params),
2304 assert!(!outbound_payments.has_pending_payments());
2306 outbound_payments.send_payment_for_bolt12_invoice(
2307 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2308 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2310 Err(Bolt12PaymentError::UnexpectedInvoice),
2312 assert!(!outbound_payments.has_pending_payments());
2313 assert!(pending_events.lock().unwrap().is_empty());
2316 outbound_payments.add_new_awaiting_invoice(
2317 payment_id, Duration::from_secs(absolute_expiry), Retry::Attempts(0), Some(1234)
2320 assert!(outbound_payments.has_pending_payments());
2323 outbound_payments.send_payment_for_bolt12_invoice(
2324 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2325 &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())
2329 assert!(outbound_payments.has_pending_payments());
2330 assert!(pending_events.lock().unwrap().is_empty());
2333 outbound_payments.send_payment_for_bolt12_invoice(
2334 &invoice, payment_id, &&router, vec![], || InFlightHtlcs::new(), &&keys_manager,
2335 &&keys_manager, 0, &&logger, &pending_events, |_| panic!()
2337 Err(Bolt12PaymentError::DuplicateInvoice),
2339 assert!(outbound_payments.has_pending_payments());
2340 assert!(pending_events.lock().unwrap().is_empty());