1use bitcoin::hashes::Hash;
13use bitcoin::hashes::sha256::Hash as Sha256;
14use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
15
16use crate::blinded_path::{IntroductionNode, NodeIdLookUp};
17use crate::events::{self, PaymentFailureReason};
18use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
19use crate::ln::channel_state::ChannelDetails;
20use crate::ln::channelmanager::{EventCompletionAction, HTLCSource, PaymentId};
21use crate::types::features::Bolt12InvoiceFeatures;
22use crate::ln::onion_utils;
23use crate::ln::onion_utils::{DecodedOnionFailure, HTLCFailReason};
24use crate::offers::invoice::Bolt12Invoice;
25use crate::offers::invoice_request::InvoiceRequest;
26use crate::offers::nonce::Nonce;
27use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, Router};
28use crate::sign::{EntropySource, NodeSigner, Recipient};
29use crate::util::errors::APIError;
30use crate::util::logger::Logger;
31#[cfg(feature = "std")]
32use crate::util::time::Instant;
33use crate::util::ser::ReadableArgs;
34
35#[cfg(async_payments)]
36use {
37 crate::offers::invoice::{DerivedSigningPubkey, InvoiceBuilder},
38 crate::offers::static_invoice::StaticInvoice,
39};
40
41use core::fmt::{self, Display, Formatter};
42use core::ops::Deref;
43use core::sync::atomic::{AtomicBool, Ordering};
44use core::time::Duration;
45
46use crate::prelude::*;
47use crate::sync::Mutex;
48
49pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
54
55pub(crate) enum PendingOutboundPayment {
58 Legacy {
59 session_privs: HashSet<[u8; 32]>,
60 },
61 AwaitingOffer {
63 expiration: StaleExpiration,
64 retry_strategy: Retry,
65 max_total_routing_fee_msat: Option<u64>,
66 amount_msats: u64,
69 },
70 AwaitingInvoice {
71 expiration: StaleExpiration,
72 retry_strategy: Retry,
73 max_total_routing_fee_msat: Option<u64>,
74 retryable_invoice_request: Option<RetryableInvoiceRequest>
75 },
76 InvoiceReceived {
80 payment_hash: PaymentHash,
81 retry_strategy: Retry,
82 max_total_routing_fee_msat: Option<u64>,
85 },
86 StaticInvoiceReceived {
91 payment_hash: PaymentHash,
92 keysend_preimage: PaymentPreimage,
93 retry_strategy: Retry,
94 route_params: RouteParameters,
95 invoice_request: InvoiceRequest,
96 },
97 Retryable {
98 retry_strategy: Option<Retry>,
99 attempts: PaymentAttempts,
100 payment_params: Option<PaymentParameters>,
101 session_privs: HashSet<[u8; 32]>,
102 payment_hash: PaymentHash,
103 payment_secret: Option<PaymentSecret>,
104 payment_metadata: Option<Vec<u8>>,
105 keysend_preimage: Option<PaymentPreimage>,
106 invoice_request: Option<InvoiceRequest>,
107 custom_tlvs: Vec<(u64, Vec<u8>)>,
108 pending_amt_msat: u64,
109 pending_fee_msat: Option<u64>,
111 total_msat: u64,
113 starting_block_height: u32,
115 remaining_max_total_routing_fee_msat: Option<u64>,
116 },
117 Fulfilled {
121 session_privs: HashSet<[u8; 32]>,
122 payment_hash: Option<PaymentHash>,
124 timer_ticks_without_htlcs: u8,
125 },
126 Abandoned {
129 session_privs: HashSet<[u8; 32]>,
130 payment_hash: PaymentHash,
131 reason: Option<PaymentFailureReason>,
134 },
135}
136
137pub(crate) struct RetryableInvoiceRequest {
138 pub(crate) invoice_request: InvoiceRequest,
139 pub(crate) nonce: Nonce,
140}
141
142impl_writeable_tlv_based!(RetryableInvoiceRequest, {
143 (0, invoice_request, required),
144 (2, nonce, required),
145});
146
147impl PendingOutboundPayment {
148 fn increment_attempts(&mut self) {
149 if let PendingOutboundPayment::Retryable { attempts, .. } = self {
150 attempts.count += 1;
151 }
152 }
153 fn is_auto_retryable_now(&self) -> bool {
154 match self {
155 PendingOutboundPayment::Retryable {
156 retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
157 } => {
158 strategy.is_retryable_now(&attempts)
159 },
160 _ => false,
161 }
162 }
163 fn is_retryable_now(&self) -> bool {
164 match self {
165 PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
166 true
168 },
169 PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
170 strategy.is_retryable_now(&attempts)
171 },
172 _ => false,
173 }
174 }
175 pub fn insert_previously_failed_scid(&mut self, scid: u64) {
176 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
177 params.previously_failed_channels.push(scid);
178 }
179 }
180 pub fn insert_previously_failed_blinded_path(&mut self, blinded_tail: &BlindedTail) {
181 if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
182 params.insert_previously_failed_blinded_path(blinded_tail);
183 }
184 }
185 fn is_awaiting_invoice(&self) -> bool {
186 match self {
187 PendingOutboundPayment::AwaitingInvoice { .. } => true,
188 _ => false,
189 }
190 }
191 pub(super) fn is_fulfilled(&self) -> bool {
192 match self {
193 PendingOutboundPayment::Fulfilled { .. } => true,
194 _ => false,
195 }
196 }
197 pub(super) fn abandoned(&self) -> bool {
198 match self {
199 PendingOutboundPayment::Abandoned { .. } => true,
200 _ => false,
201 }
202 }
203 fn get_pending_fee_msat(&self) -> Option<u64> {
204 match self {
205 PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
206 _ => None,
207 }
208 }
209
210 fn payment_hash(&self) -> Option<PaymentHash> {
211 match self {
212 PendingOutboundPayment::Legacy { .. } => None,
213 PendingOutboundPayment::AwaitingOffer { .. } => None,
214 PendingOutboundPayment::AwaitingInvoice { .. } => None,
215 PendingOutboundPayment::InvoiceReceived { payment_hash, .. } => Some(*payment_hash),
216 PendingOutboundPayment::StaticInvoiceReceived { payment_hash, .. } => Some(*payment_hash),
217 PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
218 PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
219 PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
220 }
221 }
222
223 fn mark_fulfilled(&mut self) {
224 let mut session_privs = new_hash_set();
225 core::mem::swap(&mut session_privs, match self {
226 PendingOutboundPayment::Legacy { session_privs } |
227 PendingOutboundPayment::Retryable { session_privs, .. } |
228 PendingOutboundPayment::Fulfilled { session_privs, .. } |
229 PendingOutboundPayment::Abandoned { session_privs, .. } => session_privs,
230 PendingOutboundPayment::AwaitingOffer { .. } |
231 PendingOutboundPayment::AwaitingInvoice { .. } |
232 PendingOutboundPayment::InvoiceReceived { .. } |
233 PendingOutboundPayment::StaticInvoiceReceived { .. } => { debug_assert!(false); return; },
234 });
235 let payment_hash = self.payment_hash();
236 *self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
237 }
238
239 fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
240 let session_privs = match self {
241 PendingOutboundPayment::Retryable { session_privs, .. } => {
242 let mut our_session_privs = new_hash_set();
243 core::mem::swap(&mut our_session_privs, session_privs);
244 our_session_privs
245 },
246 _ => new_hash_set(),
247 };
248 match self {
249 Self::Retryable { payment_hash, .. } |
250 Self::InvoiceReceived { payment_hash, .. } |
251 Self::StaticInvoiceReceived { payment_hash, .. } =>
252 {
253 *self = Self::Abandoned {
254 session_privs,
255 payment_hash: *payment_hash,
256 reason: Some(reason),
257 };
258 },
259 _ => {}
260 }
261 }
262
263 fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
265 let remove_res = match self {
266 PendingOutboundPayment::Legacy { session_privs } |
267 PendingOutboundPayment::Retryable { session_privs, .. } |
268 PendingOutboundPayment::Fulfilled { session_privs, .. } |
269 PendingOutboundPayment::Abandoned { session_privs, .. } => {
270 session_privs.remove(session_priv)
271 },
272 PendingOutboundPayment::AwaitingOffer { .. } |
273 PendingOutboundPayment::AwaitingInvoice { .. } |
274 PendingOutboundPayment::InvoiceReceived { .. } |
275 PendingOutboundPayment::StaticInvoiceReceived { .. } => { debug_assert!(false); false },
276 };
277 if remove_res {
278 if let PendingOutboundPayment::Retryable {
279 ref mut pending_amt_msat, ref mut pending_fee_msat,
280 ref mut remaining_max_total_routing_fee_msat, ..
281 } = self {
282 let path = path.expect("Removing a failed payment should always come with a path");
283 *pending_amt_msat -= path.final_value_msat();
284 let path_fee_msat = path.fee_msat();
285 if let Some(fee_msat) = pending_fee_msat.as_mut() {
286 *fee_msat -= path_fee_msat;
287 }
288
289 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
290 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_add(path_fee_msat);
291 }
292 }
293 }
294 remove_res
295 }
296
297 pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
298 let insert_res = match self {
299 PendingOutboundPayment::Legacy { session_privs } |
300 PendingOutboundPayment::Retryable { session_privs, .. } => {
301 session_privs.insert(session_priv)
302 },
303 PendingOutboundPayment::AwaitingOffer { .. } |
304 PendingOutboundPayment::AwaitingInvoice { .. } |
305 PendingOutboundPayment::InvoiceReceived { .. } |
306 PendingOutboundPayment::StaticInvoiceReceived { .. } => { debug_assert!(false); false },
307 PendingOutboundPayment::Fulfilled { .. } => false,
308 PendingOutboundPayment::Abandoned { .. } => false,
309 };
310 if insert_res {
311 if let PendingOutboundPayment::Retryable {
312 ref mut pending_amt_msat, ref mut pending_fee_msat,
313 ref mut remaining_max_total_routing_fee_msat, ..
314 } = self {
315 *pending_amt_msat += path.final_value_msat();
316 let path_fee_msat = path.fee_msat();
317 if let Some(fee_msat) = pending_fee_msat.as_mut() {
318 *fee_msat += path_fee_msat;
319 }
320
321 if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
322 *max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_sub(path_fee_msat);
323 }
324 }
325 }
326 insert_res
327 }
328
329 pub(super) fn remaining_parts(&self) -> usize {
330 match self {
331 PendingOutboundPayment::Legacy { session_privs } |
332 PendingOutboundPayment::Retryable { session_privs, .. } |
333 PendingOutboundPayment::Fulfilled { session_privs, .. } |
334 PendingOutboundPayment::Abandoned { session_privs, .. } => {
335 session_privs.len()
336 },
337 PendingOutboundPayment::AwaitingInvoice { .. } => 0,
338 PendingOutboundPayment::AwaitingOffer { .. } => 0,
339 PendingOutboundPayment::InvoiceReceived { .. } => 0,
340 PendingOutboundPayment::StaticInvoiceReceived { .. } => 0,
341 }
342 }
343}
344
345#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
347pub enum Retry {
348 Attempts(u32),
354 #[cfg(feature = "std")]
355 Timeout(core::time::Duration),
360}
361
362#[cfg(not(feature = "std"))]
363impl_writeable_tlv_based_enum_legacy!(Retry,
364 ;
365 (0, Attempts)
366);
367
368#[cfg(feature = "std")]
369impl_writeable_tlv_based_enum_legacy!(Retry,
370 ;
371 (0, Attempts),
372 (2, Timeout)
373);
374
375impl Retry {
376 pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
377 match (self, attempts) {
378 (Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
379 max_retry_count > count
380 },
381 #[cfg(feature = "std")]
382 (Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
383 *max_duration >= Instant::now().duration_since(*first_attempted_at),
384 }
385 }
386}
387
388#[cfg(feature = "std")]
389pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
390 if let Some(expiry_time) = route_params.payment_params.expiry_time {
391 if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
392 return elapsed > core::time::Duration::from_secs(expiry_time)
393 }
394 }
395 false
396}
397
398pub(crate) struct PaymentAttempts {
401 pub(crate) count: u32,
404 #[cfg(feature = "std")]
406 first_attempted_at: Instant,
407}
408
409impl PaymentAttempts {
410 pub(crate) fn new() -> Self {
411 PaymentAttempts {
412 count: 0,
413 #[cfg(feature = "std")]
414 first_attempted_at: Instant::now(),
415 }
416 }
417}
418
419impl Display for PaymentAttempts {
420 fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
421 #[cfg(not(feature = "std"))]
422 return write!(f, "attempts: {}", self.count);
423 #[cfg(feature = "std")]
424 return write!(
425 f,
426 "attempts: {}, duration: {}s",
427 self.count,
428 Instant::now().duration_since(self.first_attempted_at).as_secs()
429 );
430 }
431}
432
433#[derive(Clone, Copy)]
437pub(crate) enum StaleExpiration {
438 TimerTicks(u64),
440 AbsoluteTimeout(core::time::Duration),
442}
443
444impl_writeable_tlv_based_enum_legacy!(StaleExpiration,
445 ;
446 (0, TimerTicks),
447 (2, AbsoluteTimeout)
448);
449
450#[derive(Clone, Debug, PartialEq, Eq)]
457pub enum RetryableSendFailure {
458 #[cfg_attr(feature = "std", doc = "")]
460 #[cfg_attr(feature = "std", doc = "Note that this error is *not* caused by [`Retry::Timeout`].")]
461 PaymentExpired,
464 RouteNotFound,
466 DuplicatePayment,
473 OnionPacketSizeExceeded,
479}
480
481#[derive(Clone, Debug, PartialEq, Eq)]
485pub(crate) enum PaymentSendFailure {
486 ParameterError(APIError),
497 PathParameterError(Vec<Result<(), APIError>>),
511 AllFailedResendSafe(Vec<APIError>),
521 DuplicatePayment,
528 PartialFailure {
539 results: Vec<Result<(), APIError>>,
541 failed_paths_retry: Option<RouteParameters>,
544 payment_id: PaymentId,
546 },
547}
548
549#[derive(Clone, Debug, PartialEq, Eq)]
551pub enum Bolt12PaymentError {
552 UnexpectedInvoice,
554 DuplicateInvoice,
556 UnknownRequiredFeatures,
558 SendingFailed(RetryableSendFailure),
560 #[cfg(async_payments)]
561 BlindedPathCreationFailed,
569}
570
571#[derive(Clone, Debug, PartialEq, Eq)]
576pub enum ProbeSendFailure {
577 RouteNotFound,
579 ParameterError(APIError),
590 DuplicateProbe,
597}
598
599#[derive(Clone, Debug, PartialEq, Eq)]
604pub struct RecipientOnionFields {
605 pub payment_secret: Option<PaymentSecret>,
617 pub payment_metadata: Option<Vec<u8>>,
630 pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
632}
633
634impl_writeable_tlv_based!(RecipientOnionFields, {
635 (0, payment_secret, option),
636 (1, custom_tlvs, optional_vec),
637 (2, payment_metadata, option),
638});
639
640impl RecipientOnionFields {
641 pub fn secret_only(payment_secret: PaymentSecret) -> Self {
645 Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
646 }
647
648 pub fn spontaneous_empty() -> Self {
657 Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
658 }
659
660 pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
670 custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
671 let mut prev_type = None;
672 for (typ, _) in custom_tlvs.iter() {
673 if *typ < 1 << 16 { return Err(()); }
674 if *typ == 5482373484 { return Err(()); } if *typ == 77_777 { return Err(()); } match prev_type {
677 Some(prev) if prev >= *typ => return Err(()),
678 _ => {},
679 }
680 prev_type = Some(*typ);
681 }
682 self.custom_tlvs = custom_tlvs;
683 Ok(self)
684 }
685
686 #[cfg(not(c_bindings))]
697 pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
698 &self.custom_tlvs
699 }
700
701 #[cfg(c_bindings)]
712 pub fn custom_tlvs(&self) -> Vec<(u64, Vec<u8>)> {
713 self.custom_tlvs.clone()
714 }
715
716 pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
724 if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
725 if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
726
727 let tlvs = &mut self.custom_tlvs;
728 let further_tlvs = &mut further_htlc_fields.custom_tlvs;
729
730 let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
731 let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
732 if even_tlvs.ne(further_even_tlvs) { return Err(()) }
733
734 tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
735 further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
736
737 Ok(())
738 }
739}
740
741pub(super) struct SendAlongPathArgs<'a> {
743 pub path: &'a Path,
744 pub payment_hash: &'a PaymentHash,
745 pub recipient_onion: &'a RecipientOnionFields,
746 pub total_value: u64,
747 pub cur_height: u32,
748 pub payment_id: PaymentId,
749 pub keysend_preimage: &'a Option<PaymentPreimage>,
750 pub invoice_request: Option<&'a InvoiceRequest>,
751 pub session_priv_bytes: [u8; 32],
752}
753
754pub(super) struct OutboundPayments {
755 pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
756 awaiting_invoice: AtomicBool,
757 retry_lock: Mutex<()>,
758}
759
760impl OutboundPayments {
761 pub(super) fn new(pending_outbound_payments: HashMap<PaymentId, PendingOutboundPayment>) -> Self {
762 let has_invoice_requests = pending_outbound_payments.values().any(|payment| {
763 matches!(payment, PendingOutboundPayment::AwaitingInvoice { retryable_invoice_request: Some(_), .. })
764 });
765
766 Self {
767 pending_outbound_payments: Mutex::new(pending_outbound_payments),
768 awaiting_invoice: AtomicBool::new(has_invoice_requests),
769 retry_lock: Mutex::new(()),
770 }
771 }
772
773 pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
774 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
775 retry_strategy: Retry, route_params: RouteParameters, router: &R,
776 first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
777 node_signer: &NS, best_block_height: u32, logger: &L,
778 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
779 ) -> Result<(), RetryableSendFailure>
780 where
781 R::Target: Router,
782 ES::Target: EntropySource,
783 NS::Target: NodeSigner,
784 L::Target: Logger,
785 IH: Fn() -> InFlightHtlcs,
786 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
787 {
788 self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
789 route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
790 best_block_height, logger, pending_events, &send_payment_along_path)
791 }
792
793 pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
794 &self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
795 payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
796 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
797 node_signer: &NS, best_block_height: u32, logger: &L,
798 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
799 ) -> Result<PaymentHash, RetryableSendFailure>
800 where
801 R::Target: Router,
802 ES::Target: EntropySource,
803 NS::Target: NodeSigner,
804 L::Target: Logger,
805 IH: Fn() -> InFlightHtlcs,
806 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
807 {
808 let preimage = payment_preimage
809 .unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
810 let payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array());
811 self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
812 retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
813 node_signer, best_block_height, logger, pending_events, send_payment_along_path)
814 .map(|()| payment_hash)
815 }
816
817 pub(super) fn send_payment_for_bolt12_invoice<
818 R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref
819 >(
820 &self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
821 first_hops: Vec<ChannelDetails>, features: Bolt12InvoiceFeatures, inflight_htlcs: IH,
822 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
823 secp_ctx: &Secp256k1<secp256k1::All>, best_block_height: u32, logger: &L,
824 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
825 send_payment_along_path: SP,
826 ) -> Result<(), Bolt12PaymentError>
827 where
828 R::Target: Router,
829 ES::Target: EntropySource,
830 NS::Target: NodeSigner,
831 NL::Target: NodeIdLookUp,
832 L::Target: Logger,
833 IH: Fn() -> InFlightHtlcs,
834 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
835 {
836 let (payment_hash, retry_strategy, max_total_routing_fee_msat, _) = self
837 .mark_invoice_received_and_get_details(invoice, payment_id)?;
838
839 if invoice.invoice_features().requires_unknown_bits_from(&features) {
840 self.abandon_payment(
841 payment_id, PaymentFailureReason::UnknownRequiredFeatures, pending_events,
842 );
843 return Err(Bolt12PaymentError::UnknownRequiredFeatures);
844 }
845
846 let mut route_params = RouteParameters::from_payment_params_and_value(
847 PaymentParameters::from_bolt12_invoice(&invoice), invoice.amount_msats()
848 );
849 if let Some(max_fee_msat) = max_total_routing_fee_msat {
850 route_params.max_total_routing_fee_msat = Some(max_fee_msat);
851 }
852 self.send_payment_for_bolt12_invoice_internal(
853 payment_id, payment_hash, None, None, route_params, retry_strategy, router, first_hops,
854 inflight_htlcs, entropy_source, node_signer, node_id_lookup, secp_ctx, best_block_height,
855 logger, pending_events, send_payment_along_path
856 )
857 }
858
859 fn send_payment_for_bolt12_invoice_internal<
860 R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref
861 >(
862 &self, payment_id: PaymentId, payment_hash: PaymentHash,
863 keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&InvoiceRequest>,
864 mut route_params: RouteParameters, retry_strategy: Retry, router: &R,
865 first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
866 node_id_lookup: &NL, secp_ctx: &Secp256k1<secp256k1::All>, best_block_height: u32, logger: &L,
867 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
868 send_payment_along_path: SP,
869 ) -> Result<(), Bolt12PaymentError>
870 where
871 R::Target: Router,
872 ES::Target: EntropySource,
873 NS::Target: NodeSigner,
874 NL::Target: NodeIdLookUp,
875 L::Target: Logger,
876 IH: Fn() -> InFlightHtlcs,
877 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
878 {
879 if let Ok(our_node_id) = node_signer.get_node_id(Recipient::Node) {
881 for path in route_params.payment_params.payee.blinded_route_hints_mut().iter_mut() {
882 let introduction_node_id = match path.introduction_node() {
883 IntroductionNode::NodeId(pubkey) => *pubkey,
884 IntroductionNode::DirectedShortChannelId(direction, scid) => {
885 match node_id_lookup.next_node_id(*scid) {
886 Some(next_node_id) => *direction.select_pubkey(&our_node_id, &next_node_id),
887 None => continue,
888 }
889 },
890 };
891 if introduction_node_id == our_node_id {
892 let _ = path.advance_path_by_one(node_signer, node_id_lookup, secp_ctx);
893 }
894 }
895 }
896
897 let recipient_onion = RecipientOnionFields {
898 payment_secret: None,
899 payment_metadata: None,
900 custom_tlvs: vec![],
901 };
902 let route = match self.find_initial_route(
903 payment_id, payment_hash, &recipient_onion, keysend_preimage, invoice_request,
904 &mut route_params, router, &first_hops, &inflight_htlcs, node_signer, best_block_height,
905 logger,
906 ) {
907 Ok(route) => route,
908 Err(e) => {
909 let reason = match e {
910 RetryableSendFailure::PaymentExpired => PaymentFailureReason::PaymentExpired,
911 RetryableSendFailure::RouteNotFound => PaymentFailureReason::RouteNotFound,
912 RetryableSendFailure::DuplicatePayment => PaymentFailureReason::UnexpectedError,
913 RetryableSendFailure::OnionPacketSizeExceeded => PaymentFailureReason::UnexpectedError,
914 };
915 self.abandon_payment(payment_id, reason, pending_events);
916 return Err(Bolt12PaymentError::SendingFailed(e));
917 },
918 };
919
920 let payment_params = Some(route_params.payment_params.clone());
921 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
922 let onion_session_privs = match outbounds.entry(payment_id) {
923 hash_map::Entry::Occupied(entry) => match entry.get() {
924 PendingOutboundPayment::InvoiceReceived { .. } => {
925 let (retryable_payment, onion_session_privs) = Self::create_pending_payment(
926 payment_hash, recipient_onion.clone(), keysend_preimage, None, &route,
927 Some(retry_strategy), payment_params, entropy_source, best_block_height
928 );
929 *entry.into_mut() = retryable_payment;
930 onion_session_privs
931 },
932 PendingOutboundPayment::StaticInvoiceReceived { .. } => {
933 let invreq = if let PendingOutboundPayment::StaticInvoiceReceived { invoice_request, .. } = entry.remove() {
934 invoice_request
935 } else { unreachable!() };
936 let (retryable_payment, onion_session_privs) = Self::create_pending_payment(
937 payment_hash, recipient_onion.clone(), keysend_preimage, Some(invreq), &route,
938 Some(retry_strategy), payment_params, entropy_source, best_block_height
939 );
940 outbounds.insert(payment_id, retryable_payment);
941 onion_session_privs
942 },
943 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
944 },
945 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
946 };
947 core::mem::drop(outbounds);
948
949 let result = self.pay_route_internal(
950 &route, payment_hash, &recipient_onion, keysend_preimage, invoice_request, payment_id,
951 Some(route_params.final_value_msat), &onion_session_privs, node_signer, best_block_height,
952 &send_payment_along_path
953 );
954 log_info!(
955 logger, "Sending payment with id {} and hash {} returned {:?}", payment_id,
956 payment_hash, result
957 );
958 if let Err(e) = result {
959 self.handle_pay_route_err(
960 e, payment_id, payment_hash, route, route_params, onion_session_privs, router, first_hops,
961 &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events,
962 &send_payment_along_path
963 );
964 }
965 Ok(())
966 }
967
968 #[cfg(async_payments)]
969 pub(super) fn static_invoice_received<ES: Deref>(
970 &self, invoice: &StaticInvoice, payment_id: PaymentId, features: Bolt12InvoiceFeatures,
971 best_block_height: u32, entropy_source: ES,
972 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
973 ) -> Result<(), Bolt12PaymentError> where ES::Target: EntropySource {
974 macro_rules! abandon_with_entry {
975 ($payment: expr, $reason: expr) => {
976 $payment.get_mut().mark_abandoned($reason);
977 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
978 if $payment.get().remaining_parts() == 0 {
979 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
980 payment_id,
981 payment_hash: None,
982 reason: *reason,
983 }, None));
984 $payment.remove();
985 }
986 }
987 }
988 }
989
990 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
991 hash_map::Entry::Occupied(mut entry) => match entry.get_mut() {
992 PendingOutboundPayment::AwaitingInvoice {
993 retry_strategy, retryable_invoice_request, max_total_routing_fee_msat, ..
994 } => {
995 let invreq = &retryable_invoice_request
996 .as_ref()
997 .ok_or(Bolt12PaymentError::UnexpectedInvoice)?
998 .invoice_request;
999 if !invoice.from_same_offer(invreq) {
1000 return Err(Bolt12PaymentError::UnexpectedInvoice)
1001 }
1002 if invoice.invoice_features().requires_unknown_bits_from(&features) {
1003 abandon_with_entry!(entry, PaymentFailureReason::UnknownRequiredFeatures);
1004 return Err(Bolt12PaymentError::UnknownRequiredFeatures)
1005 }
1006 let amount_msat = match InvoiceBuilder::<DerivedSigningPubkey>::amount_msats(invreq) {
1007 Ok(amt) => amt,
1008 Err(_) => {
1009 debug_assert!(false, "LDK requires an msat amount in either the invreq or the invreq's underlying offer");
1012 abandon_with_entry!(entry, PaymentFailureReason::UnexpectedError);
1013 return Err(Bolt12PaymentError::UnknownRequiredFeatures)
1014 }
1015 };
1016 let keysend_preimage = PaymentPreimage(entropy_source.get_secure_random_bytes());
1017 let payment_hash = PaymentHash(Sha256::hash(&keysend_preimage.0).to_byte_array());
1018 let pay_params = PaymentParameters::from_static_invoice(invoice);
1019 let mut route_params = RouteParameters::from_payment_params_and_value(pay_params, amount_msat);
1020 route_params.max_total_routing_fee_msat = *max_total_routing_fee_msat;
1021
1022 if let Err(()) = onion_utils::set_max_path_length(
1023 &mut route_params, &RecipientOnionFields::spontaneous_empty(), Some(keysend_preimage),
1024 Some(invreq), best_block_height
1025 ) {
1026 abandon_with_entry!(entry, PaymentFailureReason::RouteNotFound);
1027 return Err(Bolt12PaymentError::SendingFailed(RetryableSendFailure::OnionPacketSizeExceeded))
1028 }
1029
1030 *entry.into_mut() = PendingOutboundPayment::StaticInvoiceReceived {
1031 payment_hash,
1032 keysend_preimage,
1033 retry_strategy: *retry_strategy,
1034 route_params,
1035 invoice_request:
1036 retryable_invoice_request
1037 .take()
1038 .ok_or(Bolt12PaymentError::UnexpectedInvoice)?
1039 .invoice_request,
1040 };
1041 return Ok(())
1042 },
1043 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
1044 },
1045 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
1046 };
1047 }
1048
1049 #[cfg(async_payments)]
1050 pub(super) fn send_payment_for_static_invoice<
1051 R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref
1052 >(
1053 &self, payment_id: PaymentId, router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH,
1054 entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
1055 secp_ctx: &Secp256k1<secp256k1::All>, best_block_height: u32, logger: &L,
1056 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1057 send_payment_along_path: SP,
1058 ) -> Result<(), Bolt12PaymentError>
1059 where
1060 R::Target: Router,
1061 ES::Target: EntropySource,
1062 NS::Target: NodeSigner,
1063 NL::Target: NodeIdLookUp,
1064 L::Target: Logger,
1065 IH: Fn() -> InFlightHtlcs,
1066 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1067 {
1068 let (payment_hash, keysend_preimage, route_params, retry_strategy, invoice_request) =
1069 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
1070 hash_map::Entry::Occupied(entry) => match entry.get() {
1071 PendingOutboundPayment::StaticInvoiceReceived {
1072 payment_hash, route_params, retry_strategy, keysend_preimage, invoice_request, ..
1073 } => {
1074 (*payment_hash, *keysend_preimage, route_params.clone(), *retry_strategy,
1075 invoice_request.clone())
1076 },
1077 _ => return Err(Bolt12PaymentError::DuplicateInvoice),
1078 },
1079 hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
1080 };
1081
1082 self.send_payment_for_bolt12_invoice_internal(
1083 payment_id, payment_hash, Some(keysend_preimage), Some(&invoice_request), route_params,
1084 retry_strategy, router, first_hops, inflight_htlcs, entropy_source, node_signer,
1085 node_id_lookup, secp_ctx, best_block_height, logger, pending_events, send_payment_along_path
1086 )
1087 }
1088
1089 pub(super) fn check_retry_payments<R: Deref, ES: Deref, NS: Deref, SP, IH, FH, L: Deref>(
1090 &self, router: &R, first_hops: FH, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
1091 best_block_height: u32,
1092 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
1093 send_payment_along_path: SP,
1094 )
1095 where
1096 R::Target: Router,
1097 ES::Target: EntropySource,
1098 NS::Target: NodeSigner,
1099 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1100 IH: Fn() -> InFlightHtlcs,
1101 FH: Fn() -> Vec<ChannelDetails>,
1102 L::Target: Logger,
1103 {
1104 let _single_thread = self.retry_lock.lock().unwrap();
1105 loop {
1106 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1107 let mut retry_id_route_params = None;
1108 for (pmt_id, pmt) in outbounds.iter_mut() {
1109 if pmt.is_auto_retryable_now() {
1110 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, payment_params: Some(params), payment_hash, remaining_max_total_routing_fee_msat, .. } = pmt {
1111 if pending_amt_msat < total_msat {
1112 retry_id_route_params = Some((*payment_hash, *pmt_id, RouteParameters {
1113 final_value_msat: *total_msat - *pending_amt_msat,
1114 payment_params: params.clone(),
1115 max_total_routing_fee_msat: *remaining_max_total_routing_fee_msat,
1116 }));
1117 break
1118 }
1119 } else { debug_assert!(false); }
1120 }
1121 }
1122 core::mem::drop(outbounds);
1123 if let Some((payment_hash, payment_id, route_params)) = retry_id_route_params {
1124 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)
1125 } else { break }
1126 }
1127
1128 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1129 outbounds.retain(|pmt_id, pmt| {
1130 let mut retain = true;
1131 if !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_awaiting_invoice() {
1132 pmt.mark_abandoned(PaymentFailureReason::RetriesExhausted);
1133 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = pmt {
1134 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1135 payment_id: *pmt_id,
1136 payment_hash: Some(*payment_hash),
1137 reason: *reason,
1138 }, None));
1139 retain = false;
1140 }
1141 }
1142 retain
1143 });
1144 }
1145
1146 pub(super) fn needs_abandon(&self) -> bool {
1147 let outbounds = self.pending_outbound_payments.lock().unwrap();
1148 outbounds.iter().any(|(_, pmt)|
1149 !pmt.is_auto_retryable_now() && pmt.remaining_parts() == 0 && !pmt.is_fulfilled() &&
1150 !pmt.is_awaiting_invoice())
1151 }
1152
1153 fn find_initial_route<R: Deref, NS: Deref, IH, L: Deref>(
1154 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields,
1155 keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&InvoiceRequest>,
1156 route_params: &mut RouteParameters, router: &R, first_hops: &Vec<ChannelDetails>,
1157 inflight_htlcs: &IH, node_signer: &NS, best_block_height: u32, logger: &L,
1158 ) -> Result<Route, RetryableSendFailure>
1159 where
1160 R::Target: Router,
1161 NS::Target: NodeSigner,
1162 L::Target: Logger,
1163 IH: Fn() -> InFlightHtlcs,
1164 {
1165 #[cfg(feature = "std")] {
1166 if has_expired(&route_params) {
1167 log_error!(logger, "Payment with id {} and hash {} had expired before we started paying",
1168 payment_id, payment_hash);
1169 return Err(RetryableSendFailure::PaymentExpired)
1170 }
1171 }
1172
1173 onion_utils::set_max_path_length(
1174 route_params, recipient_onion, keysend_preimage, invoice_request, best_block_height
1175 )
1176 .map_err(|()| {
1177 log_error!(logger, "Can't construct an onion packet without exceeding 1300-byte onion \
1178 hop_data length for payment with id {} and hash {}", payment_id, payment_hash);
1179 RetryableSendFailure::OnionPacketSizeExceeded
1180 })?;
1181
1182 let mut route = router.find_route_with_id(
1183 &node_signer.get_node_id(Recipient::Node).unwrap(), route_params,
1184 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
1185 payment_hash, payment_id,
1186 ).map_err(|_| {
1187 log_error!(logger, "Failed to find route for payment with id {} and hash {}",
1188 payment_id, payment_hash);
1189 RetryableSendFailure::RouteNotFound
1190 })?;
1191
1192 if route.route_params.as_ref() != Some(route_params) {
1193 debug_assert!(false,
1194 "Routers are expected to return a Route which includes the requested RouteParameters. Got {:?}, expected {:?}",
1195 route.route_params, route_params);
1196 route.route_params = Some(route_params.clone());
1197 }
1198
1199 Ok(route)
1200 }
1201
1202 fn send_payment_internal<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1208 &self, payment_id: PaymentId, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1209 keysend_preimage: Option<PaymentPreimage>, retry_strategy: Retry, mut route_params: RouteParameters,
1210 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
1211 node_signer: &NS, best_block_height: u32, logger: &L,
1212 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
1213 ) -> Result<(), RetryableSendFailure>
1214 where
1215 R::Target: Router,
1216 ES::Target: EntropySource,
1217 NS::Target: NodeSigner,
1218 L::Target: Logger,
1219 IH: Fn() -> InFlightHtlcs,
1220 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1221 {
1222 let route = self.find_initial_route(
1223 payment_id, payment_hash, &recipient_onion, keysend_preimage, None, &mut route_params, router,
1224 &first_hops, &inflight_htlcs, node_signer, best_block_height, logger,
1225 )?;
1226
1227 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1228 recipient_onion.clone(), payment_id, keysend_preimage, &route, Some(retry_strategy),
1229 Some(route_params.payment_params.clone()), entropy_source, best_block_height)
1230 .map_err(|_| {
1231 log_error!(logger, "Payment with id {} is already pending. New payment had payment hash {}",
1232 payment_id, payment_hash);
1233 RetryableSendFailure::DuplicatePayment
1234 })?;
1235
1236 let res = self.pay_route_internal(&route, payment_hash, &recipient_onion,
1237 keysend_preimage, None, payment_id, None, &onion_session_privs, node_signer,
1238 best_block_height, &send_payment_along_path);
1239 log_info!(logger, "Sending payment with id {} and hash {} returned {:?}",
1240 payment_id, payment_hash, res);
1241 if let Err(e) = res {
1242 self.handle_pay_route_err(
1243 e, payment_id, payment_hash, route, route_params, onion_session_privs, router, first_hops,
1244 &inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events,
1245 &send_payment_along_path
1246 );
1247 }
1248 Ok(())
1249 }
1250
1251 fn find_route_and_send_payment<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1252 &self, payment_hash: PaymentHash, payment_id: PaymentId, route_params: RouteParameters,
1253 router: &R, first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES,
1254 node_signer: &NS, best_block_height: u32, logger: &L,
1255 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: &SP,
1256 )
1257 where
1258 R::Target: Router,
1259 ES::Target: EntropySource,
1260 NS::Target: NodeSigner,
1261 L::Target: Logger,
1262 IH: Fn() -> InFlightHtlcs,
1263 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1264 {
1265 #[cfg(feature = "std")] {
1266 if has_expired(&route_params) {
1267 log_error!(logger, "Payment params expired on retry, abandoning payment {}", &payment_id);
1268 self.abandon_payment(payment_id, PaymentFailureReason::PaymentExpired, pending_events);
1269 return
1270 }
1271 }
1272
1273 let mut route = match router.find_route_with_id(
1274 &node_signer.get_node_id(Recipient::Node).unwrap(), &route_params,
1275 Some(&first_hops.iter().collect::<Vec<_>>()), inflight_htlcs(),
1276 payment_hash, payment_id,
1277 ) {
1278 Ok(route) => route,
1279 Err(e) => {
1280 log_error!(logger, "Failed to find a route on retry, abandoning payment {}: {:#?}", &payment_id, e);
1281 self.abandon_payment(payment_id, PaymentFailureReason::RouteNotFound, pending_events);
1282 return
1283 }
1284 };
1285
1286 if route.route_params.as_ref() != Some(&route_params) {
1287 debug_assert!(false,
1288 "Routers are expected to return a Route which includes the requested RouteParameters");
1289 route.route_params = Some(route_params.clone());
1290 }
1291
1292 for path in route.paths.iter() {
1293 if path.hops.len() == 0 {
1294 log_error!(logger, "Unusable path in route (path.hops.len() must be at least 1");
1295 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1296 return
1297 }
1298 }
1299
1300 macro_rules! abandon_with_entry {
1301 ($payment: expr, $reason: expr) => {
1302 $payment.get_mut().mark_abandoned($reason);
1303 if let PendingOutboundPayment::Abandoned { reason, .. } = $payment.get() {
1304 if $payment.get().remaining_parts() == 0 {
1305 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
1306 payment_id,
1307 payment_hash: Some(payment_hash),
1308 reason: *reason,
1309 }, None));
1310 $payment.remove();
1311 }
1312 }
1313 }
1314 }
1315 let (total_msat, recipient_onion, keysend_preimage, onion_session_privs, invoice_request) = {
1316 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1317 match outbounds.entry(payment_id) {
1318 hash_map::Entry::Occupied(mut payment) => {
1319 match payment.get() {
1320 PendingOutboundPayment::Retryable {
1321 total_msat, keysend_preimage, payment_secret, payment_metadata,
1322 custom_tlvs, pending_amt_msat, invoice_request, ..
1323 } => {
1324 const RETRY_OVERFLOW_PERCENTAGE: u64 = 10;
1325 let retry_amt_msat = route.get_total_amount();
1326 if retry_amt_msat + *pending_amt_msat > *total_msat * (100 + RETRY_OVERFLOW_PERCENTAGE) / 100 {
1327 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);
1328 abandon_with_entry!(payment, PaymentFailureReason::UnexpectedError);
1329 return
1330 }
1331
1332 if !payment.get().is_retryable_now() {
1333 log_error!(logger, "Retries exhausted for payment id {}", &payment_id);
1334 abandon_with_entry!(payment, PaymentFailureReason::RetriesExhausted);
1335 return
1336 }
1337
1338 let total_msat = *total_msat;
1339 let recipient_onion = RecipientOnionFields {
1340 payment_secret: *payment_secret,
1341 payment_metadata: payment_metadata.clone(),
1342 custom_tlvs: custom_tlvs.clone(),
1343 };
1344 let keysend_preimage = *keysend_preimage;
1345 let invoice_request = invoice_request.clone();
1346
1347 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1348 for _ in 0..route.paths.len() {
1349 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1350 }
1351
1352 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1353 assert!(payment.get_mut().insert(*session_priv_bytes, path));
1354 }
1355
1356 payment.get_mut().increment_attempts();
1357
1358 (total_msat, recipient_onion, keysend_preimage, onion_session_privs, invoice_request)
1359 },
1360 PendingOutboundPayment::Legacy { .. } => {
1361 log_error!(logger, "Unable to retry payments that were initially sent on LDK versions prior to 0.0.102");
1362 return
1363 },
1364 PendingOutboundPayment::AwaitingInvoice { .. }
1365 | PendingOutboundPayment::AwaitingOffer { .. } =>
1366 {
1367 log_error!(logger, "Payment not yet sent");
1368 debug_assert!(false);
1369 return
1370 },
1371 PendingOutboundPayment::InvoiceReceived { .. } => {
1372 log_error!(logger, "Payment already initiating");
1373 debug_assert!(false);
1374 return
1375 },
1376 PendingOutboundPayment::StaticInvoiceReceived { .. } => {
1377 log_error!(logger, "Payment already initiating");
1378 debug_assert!(false);
1379 return
1380 },
1381 PendingOutboundPayment::Fulfilled { .. } => {
1382 log_error!(logger, "Payment already completed");
1383 return
1384 },
1385 PendingOutboundPayment::Abandoned { .. } => {
1386 log_error!(logger, "Payment already abandoned (with some HTLCs still pending)");
1387 return
1388 },
1389 }
1390 },
1391 hash_map::Entry::Vacant(_) => {
1392 log_error!(logger, "Payment with ID {} not found", &payment_id);
1393 return
1394 }
1395 }
1396 };
1397 let res = self.pay_route_internal(&route, payment_hash, &recipient_onion, keysend_preimage,
1398 invoice_request.as_ref(), payment_id, Some(total_msat), &onion_session_privs, node_signer,
1399 best_block_height, &send_payment_along_path);
1400 log_info!(logger, "Result retrying payment id {}: {:?}", &payment_id, res);
1401 if let Err(e) = res {
1402 self.handle_pay_route_err(
1403 e, payment_id, payment_hash, route, route_params, onion_session_privs, router, first_hops,
1404 inflight_htlcs, entropy_source, node_signer, best_block_height, logger, pending_events,
1405 send_payment_along_path
1406 );
1407 }
1408 }
1409
1410 fn handle_pay_route_err<R: Deref, NS: Deref, ES: Deref, IH, SP, L: Deref>(
1411 &self, err: PaymentSendFailure, payment_id: PaymentId, payment_hash: PaymentHash, route: Route,
1412 mut route_params: RouteParameters, onion_session_privs: Vec<[u8; 32]>, router: &R,
1413 first_hops: Vec<ChannelDetails>, inflight_htlcs: &IH, entropy_source: &ES, node_signer: &NS,
1414 best_block_height: u32, logger: &L,
1415 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1416 send_payment_along_path: &SP,
1417 )
1418 where
1419 R::Target: Router,
1420 ES::Target: EntropySource,
1421 NS::Target: NodeSigner,
1422 L::Target: Logger,
1423 IH: Fn() -> InFlightHtlcs,
1424 SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1425 {
1426 match err {
1427 PaymentSendFailure::AllFailedResendSafe(errs) => {
1428 self.remove_session_privs(payment_id, route.paths.iter().zip(onion_session_privs.iter()));
1429 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);
1430 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);
1431 },
1432 PaymentSendFailure::PartialFailure { failed_paths_retry: Some(mut retry), results, .. } => {
1433 debug_assert_eq!(results.len(), route.paths.len());
1434 debug_assert_eq!(results.len(), onion_session_privs.len());
1435 let failed_paths = results.iter().zip(route.paths.iter().zip(onion_session_privs.iter()))
1436 .filter_map(|(path_res, (path, session_priv))| {
1437 match path_res {
1438 Ok(_) | Err(APIError::MonitorUpdateInProgress) => None,
1442 _ => Some((path, session_priv))
1443 }
1444 });
1445 self.remove_session_privs(payment_id, failed_paths);
1446 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut retry, route.paths, results.into_iter(), logger, pending_events);
1447 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);
1451 },
1452 PaymentSendFailure::PartialFailure { failed_paths_retry: None, .. } => {
1453 },
1457 PaymentSendFailure::PathParameterError(results) => {
1458 log_error!(logger, "Failed to send to route due to parameter error in a single path. Your router is buggy");
1459 self.remove_session_privs(payment_id, route.paths.iter().zip(onion_session_privs.iter()));
1460 Self::push_path_failed_evs_and_scids(payment_id, payment_hash, &mut route_params, route.paths, results.into_iter(), logger, pending_events);
1461 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1462 },
1463 PaymentSendFailure::ParameterError(e) => {
1464 log_error!(logger, "Failed to send to route due to parameter error: {:?}. Your router is buggy", e);
1465 self.remove_session_privs(payment_id, route.paths.iter().zip(onion_session_privs.iter()));
1466 self.abandon_payment(payment_id, PaymentFailureReason::UnexpectedError, pending_events);
1467 },
1468 PaymentSendFailure::DuplicatePayment => debug_assert!(false), }
1470 }
1471
1472 fn push_path_failed_evs_and_scids<I: ExactSizeIterator + Iterator<Item = Result<(), APIError>>, L: Deref>(
1473 payment_id: PaymentId, payment_hash: PaymentHash, route_params: &mut RouteParameters,
1474 paths: Vec<Path>, path_results: I, logger: &L,
1475 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1476 ) where L::Target: Logger {
1477 let mut events = pending_events.lock().unwrap();
1478 debug_assert_eq!(paths.len(), path_results.len());
1479 for (path, path_res) in paths.into_iter().zip(path_results) {
1480 if let Err(e) = path_res {
1481 if let APIError::MonitorUpdateInProgress = e { continue }
1482 log_error!(logger, "Failed to send along path due to error: {:?}", e);
1483 let mut failed_scid = None;
1484 if let APIError::ChannelUnavailable { .. } = e {
1485 let scid = path.hops[0].short_channel_id;
1486 failed_scid = Some(scid);
1487 route_params.payment_params.previously_failed_channels.push(scid);
1488 }
1489 events.push_back((events::Event::PaymentPathFailed {
1490 payment_id: Some(payment_id),
1491 payment_hash,
1492 payment_failed_permanently: false,
1493 failure: events::PathFailure::InitialSend { err: e },
1494 path,
1495 short_channel_id: failed_scid,
1496 #[cfg(test)]
1497 error_code: None,
1498 #[cfg(test)]
1499 error_data: None,
1500 }, None));
1501 }
1502 }
1503 }
1504
1505 fn remove_session_privs<'a, I: Iterator<Item = (&'a Path, &'a [u8; 32])>>(
1508 &self, payment_id: PaymentId, path_session_priv: I
1509 ) {
1510 if let Some(payment) = self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id) {
1511 for (path, session_priv_bytes) in path_session_priv {
1512 let removed = payment.remove(session_priv_bytes, Some(path));
1513 debug_assert!(removed, "This can't happen as the payment has an entry for this path added by callers");
1514 }
1515 } else {
1516 debug_assert!(false, "This can't happen as the payment was added by callers");
1517 }
1518 }
1519
1520 pub(super) fn send_probe<ES: Deref, NS: Deref, F>(
1521 &self, path: Path, probing_cookie_secret: [u8; 32], entropy_source: &ES, node_signer: &NS,
1522 best_block_height: u32, send_payment_along_path: F
1523 ) -> Result<(PaymentHash, PaymentId), ProbeSendFailure>
1524 where
1525 ES::Target: EntropySource,
1526 NS::Target: NodeSigner,
1527 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1528 {
1529 let payment_id = PaymentId(entropy_source.get_secure_random_bytes());
1530 let payment_secret = PaymentSecret(entropy_source.get_secure_random_bytes());
1531
1532 let payment_hash = probing_cookie_from_id(&payment_id, probing_cookie_secret);
1533
1534 if path.hops.len() < 2 && path.blinded_tail.is_none() {
1535 return Err(ProbeSendFailure::ParameterError(APIError::APIMisuseError {
1536 err: "No need probing a path with less than two hops".to_string()
1537 }))
1538 }
1539
1540 let route = Route { paths: vec![path], route_params: None };
1541 let onion_session_privs = self.add_new_pending_payment(payment_hash,
1542 RecipientOnionFields::secret_only(payment_secret), payment_id, None, &route, None, None,
1543 entropy_source, best_block_height
1544 ).map_err(|e| {
1545 debug_assert!(matches!(e, PaymentSendFailure::DuplicatePayment));
1546 ProbeSendFailure::DuplicateProbe
1547 })?;
1548
1549 let recipient_onion_fields = RecipientOnionFields::spontaneous_empty();
1550 match self.pay_route_internal(&route, payment_hash, &recipient_onion_fields,
1551 None, None, payment_id, None, &onion_session_privs, node_signer, best_block_height,
1552 &send_payment_along_path
1553 ) {
1554 Ok(()) => Ok((payment_hash, payment_id)),
1555 Err(e) => {
1556 self.remove_outbound_if_all_failed(payment_id, &e);
1557 match e {
1558 PaymentSendFailure::DuplicatePayment => Err(ProbeSendFailure::DuplicateProbe),
1559 PaymentSendFailure::ParameterError(err) => Err(ProbeSendFailure::ParameterError(err)),
1560 PaymentSendFailure::PartialFailure { results, .. }
1561 | PaymentSendFailure::PathParameterError(results) => {
1562 debug_assert_eq!(results.len(), 1);
1563 let err = results.into_iter()
1564 .find(|res| res.is_err())
1565 .map(|err| err.unwrap_err())
1566 .unwrap_or(APIError::APIMisuseError { err: "Unexpected error".to_owned() });
1567 Err(ProbeSendFailure::ParameterError(err))
1568 },
1569 PaymentSendFailure::AllFailedResendSafe(mut errors) => {
1570 debug_assert_eq!(errors.len(), 1);
1571 let err = errors
1572 .pop()
1573 .unwrap_or(APIError::APIMisuseError { err: "Unexpected error".to_owned() });
1574 Err(ProbeSendFailure::ParameterError(err))
1575 }
1576 }
1577 }
1578 }
1579 }
1580
1581 #[cfg(test)]
1582 pub(super) fn test_set_payment_metadata(
1583 &self, payment_id: PaymentId, new_payment_metadata: Option<Vec<u8>>
1584 ) {
1585 match self.pending_outbound_payments.lock().unwrap().get_mut(&payment_id).unwrap() {
1586 PendingOutboundPayment::Retryable { payment_metadata, .. } => {
1587 *payment_metadata = new_payment_metadata;
1588 },
1589 _ => panic!("Need a retryable payment to update metadata on"),
1590 }
1591 }
1592
1593 #[cfg(test)]
1594 pub(super) fn test_add_new_pending_payment<ES: Deref>(
1595 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1596 route: &Route, retry_strategy: Option<Retry>, entropy_source: &ES, best_block_height: u32
1597 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1598 self.add_new_pending_payment(payment_hash, recipient_onion, payment_id, None, route, retry_strategy, None, entropy_source, best_block_height)
1599 }
1600
1601 pub(super) fn add_new_pending_payment<ES: Deref>(
1602 &self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
1603 keysend_preimage: Option<PaymentPreimage>, route: &Route, retry_strategy: Option<Retry>,
1604 payment_params: Option<PaymentParameters>, entropy_source: &ES, best_block_height: u32
1605 ) -> Result<Vec<[u8; 32]>, PaymentSendFailure> where ES::Target: EntropySource {
1606 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1607 match pending_outbounds.entry(payment_id) {
1608 hash_map::Entry::Occupied(_) => Err(PaymentSendFailure::DuplicatePayment),
1609 hash_map::Entry::Vacant(entry) => {
1610 let (payment, onion_session_privs) = Self::create_pending_payment(
1611 payment_hash, recipient_onion, keysend_preimage, None, route, retry_strategy,
1612 payment_params, entropy_source, best_block_height
1613 );
1614 entry.insert(payment);
1615 Ok(onion_session_privs)
1616 },
1617 }
1618 }
1619
1620 fn create_pending_payment<ES: Deref>(
1621 payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1622 keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<InvoiceRequest>,
1623 route: &Route, retry_strategy: Option<Retry>, payment_params: Option<PaymentParameters>,
1624 entropy_source: &ES, best_block_height: u32
1625 ) -> (PendingOutboundPayment, Vec<[u8; 32]>)
1626 where
1627 ES::Target: EntropySource,
1628 {
1629 let mut onion_session_privs = Vec::with_capacity(route.paths.len());
1630 for _ in 0..route.paths.len() {
1631 onion_session_privs.push(entropy_source.get_secure_random_bytes());
1632 }
1633
1634 let mut payment = PendingOutboundPayment::Retryable {
1635 retry_strategy,
1636 attempts: PaymentAttempts::new(),
1637 payment_params,
1638 session_privs: new_hash_set(),
1639 pending_amt_msat: 0,
1640 pending_fee_msat: Some(0),
1641 payment_hash,
1642 payment_secret: recipient_onion.payment_secret,
1643 payment_metadata: recipient_onion.payment_metadata,
1644 keysend_preimage,
1645 invoice_request,
1646 custom_tlvs: recipient_onion.custom_tlvs,
1647 starting_block_height: best_block_height,
1648 total_msat: route.get_total_amount(),
1649 remaining_max_total_routing_fee_msat:
1650 route.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat),
1651 };
1652
1653 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1654 assert!(payment.insert(*session_priv_bytes, path));
1655 }
1656
1657 (payment, onion_session_privs)
1658 }
1659
1660 #[cfg(feature = "dnssec")]
1661 pub(super) fn add_new_awaiting_offer(
1662 &self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry,
1663 max_total_routing_fee_msat: Option<u64>, amount_msats: u64,
1664 ) -> Result<(), ()> {
1665 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1666 match pending_outbounds.entry(payment_id) {
1667 hash_map::Entry::Occupied(_) => Err(()),
1668 hash_map::Entry::Vacant(entry) => {
1669 entry.insert(PendingOutboundPayment::AwaitingOffer {
1670 expiration,
1671 retry_strategy,
1672 max_total_routing_fee_msat,
1673 amount_msats,
1674 });
1675
1676 Ok(())
1677 },
1678 }
1679 }
1680
1681 #[cfg(feature = "dnssec")]
1682 pub(super) fn amt_msats_for_payment_awaiting_offer(&self, payment_id: PaymentId) -> Result<u64, ()> {
1683 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
1684 hash_map::Entry::Occupied(entry) => match entry.get() {
1685 PendingOutboundPayment::AwaitingOffer { amount_msats, .. } => Ok(*amount_msats),
1686 _ => Err(()),
1687 },
1688 _ => Err(()),
1689 }
1690 }
1691
1692 #[cfg(feature = "dnssec")]
1693 pub(super) fn received_offer(
1694 &self, payment_id: PaymentId, retryable_invoice_request: Option<RetryableInvoiceRequest>,
1695 ) -> Result<(), ()> {
1696 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
1697 hash_map::Entry::Occupied(entry) => match entry.get() {
1698 PendingOutboundPayment::AwaitingOffer {
1699 expiration, retry_strategy, max_total_routing_fee_msat, ..
1700 } => {
1701 let mut new_val = PendingOutboundPayment::AwaitingInvoice {
1702 expiration: *expiration,
1703 retry_strategy: *retry_strategy,
1704 max_total_routing_fee_msat: *max_total_routing_fee_msat,
1705 retryable_invoice_request,
1706 };
1707 core::mem::swap(&mut new_val, entry.into_mut());
1708 Ok(())
1709 },
1710 _ => Err(()),
1711 },
1712 hash_map::Entry::Vacant(_) => Err(()),
1713 }
1714 }
1715
1716 pub(super) fn add_new_awaiting_invoice(
1717 &self, payment_id: PaymentId, expiration: StaleExpiration, retry_strategy: Retry,
1718 max_total_routing_fee_msat: Option<u64>, retryable_invoice_request: Option<RetryableInvoiceRequest>
1719 ) -> Result<(), ()> {
1720 let mut pending_outbounds = self.pending_outbound_payments.lock().unwrap();
1721 match pending_outbounds.entry(payment_id) {
1722 hash_map::Entry::Occupied(_) => Err(()),
1723 hash_map::Entry::Vacant(entry) => {
1724 if retryable_invoice_request.is_some() {
1725 self.awaiting_invoice.store(true, Ordering::Release);
1726 }
1727 entry.insert(PendingOutboundPayment::AwaitingInvoice {
1728 expiration,
1729 retry_strategy,
1730 max_total_routing_fee_msat,
1731 retryable_invoice_request,
1732 });
1733
1734 Ok(())
1735 },
1736 }
1737 }
1738
1739 pub(super) fn mark_invoice_received(
1740 &self, invoice: &Bolt12Invoice, payment_id: PaymentId
1741 ) -> Result<(), Bolt12PaymentError> {
1742 self.mark_invoice_received_and_get_details(invoice, payment_id)
1743 .and_then(|(_, _, _, is_newly_marked)| {
1744 is_newly_marked
1745 .then_some(())
1746 .ok_or(Bolt12PaymentError::DuplicateInvoice)
1747 })
1748 }
1749
1750 fn mark_invoice_received_and_get_details(
1751 &self, invoice: &Bolt12Invoice, payment_id: PaymentId
1752 ) -> Result<(PaymentHash, Retry, Option<u64>, bool), Bolt12PaymentError> {
1753 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
1754 hash_map::Entry::Occupied(entry) => match entry.get() {
1755 PendingOutboundPayment::AwaitingInvoice {
1756 retry_strategy: retry, max_total_routing_fee_msat: max_total_fee, ..
1757 } => {
1758 let payment_hash = invoice.payment_hash();
1759 let retry = *retry;
1760 let max_total_fee = *max_total_fee;
1761 *entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
1762 payment_hash,
1763 retry_strategy: retry,
1764 max_total_routing_fee_msat: max_total_fee,
1765 };
1766
1767 Ok((payment_hash, retry, max_total_fee, true))
1768 },
1769 PendingOutboundPayment::InvoiceReceived {
1774 retry_strategy, max_total_routing_fee_msat, ..
1775 } => {
1776 Ok((invoice.payment_hash(), *retry_strategy, *max_total_routing_fee_msat, false))
1777 },
1778 _ => Err(Bolt12PaymentError::DuplicateInvoice),
1779 },
1780 hash_map::Entry::Vacant(_) => Err(Bolt12PaymentError::UnexpectedInvoice),
1781 }
1782 }
1783
1784 fn pay_route_internal<NS: Deref, F>(
1785 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: &RecipientOnionFields,
1786 keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&InvoiceRequest>,
1787 payment_id: PaymentId, recv_value_msat: Option<u64>, onion_session_privs: &Vec<[u8; 32]>,
1788 node_signer: &NS, best_block_height: u32, send_payment_along_path: &F
1789 ) -> Result<(), PaymentSendFailure>
1790 where
1791 NS::Target: NodeSigner,
1792 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1793 {
1794 if route.paths.len() < 1 {
1795 return Err(PaymentSendFailure::ParameterError(APIError::InvalidRoute{err: "There must be at least one path to send over".to_owned()}));
1796 }
1797 if recipient_onion.payment_secret.is_none() && route.paths.len() > 1
1798 && !route.paths.iter().any(|p| p.blinded_tail.is_some())
1799 {
1800 return Err(PaymentSendFailure::ParameterError(APIError::APIMisuseError{err: "Payment secret is required for multi-path payments".to_owned()}));
1801 }
1802 let mut total_value = 0;
1803 let our_node_id = node_signer.get_node_id(Recipient::Node).unwrap(); let mut path_errs = Vec::with_capacity(route.paths.len());
1805 'path_check: for path in route.paths.iter() {
1806 if path.hops.len() < 1 || path.hops.len() > 20 {
1807 path_errs.push(Err(APIError::InvalidRoute{err: "Path didn't go anywhere/had bogus size".to_owned()}));
1808 continue 'path_check;
1809 }
1810 let dest_hop_idx = if path.blinded_tail.is_some() && path.blinded_tail.as_ref().unwrap().hops.len() > 1 {
1811 usize::max_value() } else { path.hops.len() - 1 };
1812 for (idx, hop) in path.hops.iter().enumerate() {
1813 if idx != dest_hop_idx && hop.pubkey == our_node_id {
1814 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through us but wasn't a simple rebalance loop to us".to_owned()}));
1815 continue 'path_check;
1816 }
1817 }
1818 for (i, hop) in path.hops.iter().enumerate() {
1819 if path.hops.iter().skip(i + 1).any(|other_hop| other_hop.short_channel_id == hop.short_channel_id) {
1821 path_errs.push(Err(APIError::InvalidRoute{err: "Path went through the same channel twice".to_owned()}));
1822 continue 'path_check;
1823 }
1824 }
1825 total_value += path.final_value_msat();
1826 path_errs.push(Ok(()));
1827 }
1828 if path_errs.iter().any(|e| e.is_err()) {
1829 return Err(PaymentSendFailure::PathParameterError(path_errs));
1830 }
1831 if let Some(amt_msat) = recv_value_msat {
1832 total_value = amt_msat;
1833 }
1834
1835 let cur_height = best_block_height + 1;
1836 let mut results = Vec::new();
1837 debug_assert_eq!(route.paths.len(), onion_session_privs.len());
1838 for (path, session_priv_bytes) in route.paths.iter().zip(onion_session_privs.iter()) {
1839 let path_res = send_payment_along_path(SendAlongPathArgs {
1840 path: &path, payment_hash: &payment_hash, recipient_onion, total_value,
1841 cur_height, payment_id, keysend_preimage: &keysend_preimage, invoice_request,
1842 session_priv_bytes: *session_priv_bytes
1843 });
1844 results.push(path_res);
1845 }
1846 let mut has_ok = false;
1847 let mut has_err = false;
1848 let mut has_unsent = false;
1849 let mut total_ok_fees_msat = 0;
1850 let mut total_ok_amt_sent_msat = 0;
1851 for (res, path) in results.iter().zip(route.paths.iter()) {
1852 if res.is_ok() {
1853 has_ok = true;
1854 total_ok_fees_msat += path.fee_msat();
1855 total_ok_amt_sent_msat += path.final_value_msat();
1856 }
1857 if res.is_err() { has_err = true; }
1858 if let &Err(APIError::MonitorUpdateInProgress) = res {
1859 has_err = true;
1862 has_ok = true;
1863 total_ok_fees_msat += path.fee_msat();
1864 total_ok_amt_sent_msat += path.final_value_msat();
1865 } else if res.is_err() {
1866 has_unsent = true;
1867 }
1868 }
1869 if has_err && has_ok {
1870 Err(PaymentSendFailure::PartialFailure {
1871 results,
1872 payment_id,
1873 failed_paths_retry: if has_unsent {
1874 if let Some(route_params) = &route.route_params {
1875 let mut route_params = route_params.clone();
1876 route_params.max_total_routing_fee_msat = route_params
1879 .max_total_routing_fee_msat.map(|m| m.saturating_sub(total_ok_fees_msat));
1880
1881 route_params.final_value_msat = route_params.final_value_msat
1884 .saturating_sub(total_ok_amt_sent_msat);
1885 Some(route_params)
1886 } else { None }
1887 } else { None },
1888 })
1889 } else if has_err {
1890 Err(PaymentSendFailure::AllFailedResendSafe(results.drain(..).map(|r| r.unwrap_err()).collect()))
1891 } else {
1892 Ok(())
1893 }
1894 }
1895
1896 #[cfg(test)]
1897 pub(super) fn test_send_payment_internal<NS: Deref, F>(
1898 &self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
1899 keysend_preimage: Option<PaymentPreimage>, payment_id: PaymentId, recv_value_msat: Option<u64>,
1900 onion_session_privs: Vec<[u8; 32]>, node_signer: &NS, best_block_height: u32,
1901 send_payment_along_path: F
1902 ) -> Result<(), PaymentSendFailure>
1903 where
1904 NS::Target: NodeSigner,
1905 F: Fn(SendAlongPathArgs) -> Result<(), APIError>,
1906 {
1907 self.pay_route_internal(route, payment_hash, &recipient_onion,
1908 keysend_preimage, None, payment_id, recv_value_msat, &onion_session_privs,
1909 node_signer, best_block_height, &send_payment_along_path)
1910 .map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
1911 }
1912
1913 fn remove_outbound_if_all_failed(&self, payment_id: PaymentId, err: &PaymentSendFailure) {
1916 match err {
1917 PaymentSendFailure::AllFailedResendSafe(_)
1918 | PaymentSendFailure::ParameterError(_)
1919 | PaymentSendFailure::PathParameterError(_) =>
1920 {
1921 let removed = self.pending_outbound_payments.lock().unwrap().remove(&payment_id).is_some();
1922 debug_assert!(removed, "We should always have a pending payment to remove here");
1923 },
1924 PaymentSendFailure::DuplicatePayment | PaymentSendFailure::PartialFailure { .. } => {}
1925 }
1926 }
1927
1928 pub(super) fn claim_htlc<L: Deref>(
1929 &self, payment_id: PaymentId, payment_preimage: PaymentPreimage, session_priv: SecretKey,
1930 path: Path, from_onchain: bool, ev_completion_action: EventCompletionAction,
1931 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
1932 logger: &L,
1933 ) where L::Target: Logger {
1934 let mut session_priv_bytes = [0; 32];
1935 session_priv_bytes.copy_from_slice(&session_priv[..]);
1936 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1937 let mut pending_events = pending_events.lock().unwrap();
1938 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1939 if !payment.get().is_fulfilled() {
1940 let payment_hash = PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array());
1941 log_info!(logger, "Payment with id {} and hash {} sent!", payment_id, payment_hash);
1942 let fee_paid_msat = payment.get().get_pending_fee_msat();
1943 pending_events.push_back((events::Event::PaymentSent {
1944 payment_id: Some(payment_id),
1945 payment_preimage,
1946 payment_hash,
1947 fee_paid_msat,
1948 }, Some(ev_completion_action.clone())));
1949 payment.get_mut().mark_fulfilled();
1950 }
1951
1952 if from_onchain {
1953 if payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
1960 let payment_hash = Some(PaymentHash(Sha256::hash(&payment_preimage.0).to_byte_array()));
1961 pending_events.push_back((events::Event::PaymentPathSuccessful {
1962 payment_id,
1963 payment_hash,
1964 path,
1965 }, Some(ev_completion_action)));
1966 }
1967 }
1968 } else {
1969 log_trace!(logger, "Received duplicative fulfill for HTLC with payment_preimage {}", &payment_preimage);
1970 }
1971 }
1972
1973 pub(super) fn finalize_claims(&self, sources: Vec<HTLCSource>,
1974 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
1975 {
1976 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
1977 let mut pending_events = pending_events.lock().unwrap();
1978 for source in sources {
1979 if let HTLCSource::OutboundRoute { session_priv, payment_id, path, .. } = source {
1980 let mut session_priv_bytes = [0; 32];
1981 session_priv_bytes.copy_from_slice(&session_priv[..]);
1982 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
1983 assert!(payment.get().is_fulfilled());
1984 if payment.get_mut().remove(&session_priv_bytes, None) {
1985 let payment_hash = payment.get().payment_hash();
1986 debug_assert!(payment_hash.is_some());
1987 pending_events.push_back((events::Event::PaymentPathSuccessful {
1988 payment_id,
1989 payment_hash,
1990 path,
1991 }, None));
1992 }
1993 }
1994 }
1995 }
1996 }
1997
1998 pub(super) fn remove_stale_payments(
1999 &self, duration_since_epoch: Duration,
2000 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>)
2001 {
2002 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
2003 let mut pending_events = pending_events.lock().unwrap();
2004 pending_outbound_payments.retain(|payment_id, payment| match payment {
2005 PendingOutboundPayment::Fulfilled { session_privs, timer_ticks_without_htlcs, .. } => {
2013 let mut no_remaining_entries = session_privs.is_empty();
2014 if no_remaining_entries {
2015 for (ev, _) in pending_events.iter() {
2016 match ev {
2017 events::Event::PaymentSent { payment_id: Some(ev_payment_id), .. } |
2018 events::Event::PaymentPathSuccessful { payment_id: ev_payment_id, .. } |
2019 events::Event::PaymentPathFailed { payment_id: Some(ev_payment_id), .. } => {
2020 if payment_id == ev_payment_id {
2021 no_remaining_entries = false;
2022 break;
2023 }
2024 },
2025 _ => {},
2026 }
2027 }
2028 }
2029 if no_remaining_entries {
2030 *timer_ticks_without_htlcs += 1;
2031 *timer_ticks_without_htlcs <= IDEMPOTENCY_TIMEOUT_TICKS
2032 } else {
2033 *timer_ticks_without_htlcs = 0;
2034 true
2035 }
2036 },
2037 PendingOutboundPayment::AwaitingInvoice { expiration, .. }
2038 | PendingOutboundPayment::AwaitingOffer { expiration, .. } =>
2039 {
2040 let is_stale = match expiration {
2041 StaleExpiration::AbsoluteTimeout(absolute_expiry) => {
2042 *absolute_expiry <= duration_since_epoch
2043 },
2044 StaleExpiration::TimerTicks(timer_ticks_remaining) => {
2045 if *timer_ticks_remaining > 0 {
2046 *timer_ticks_remaining -= 1;
2047 false
2048 } else {
2049 true
2050 }
2051 },
2052 };
2053 if is_stale {
2054 let event = events::Event::PaymentFailed {
2055 payment_id: *payment_id,
2056 payment_hash: None,
2057 reason: Some(PaymentFailureReason::InvoiceRequestExpired),
2058 };
2059 pending_events.push_back((event, None));
2060 false
2061 } else {
2062 true
2063 }
2064 },
2065 PendingOutboundPayment::StaticInvoiceReceived { route_params, payment_hash, .. } => {
2066 let is_stale =
2067 route_params.payment_params.expiry_time.unwrap_or(u64::MAX) <
2068 duration_since_epoch.as_secs();
2069 if is_stale {
2070 let fail_ev = events::Event::PaymentFailed {
2071 payment_id: *payment_id,
2072 payment_hash: Some(*payment_hash),
2073 reason: Some(PaymentFailureReason::PaymentExpired)
2074 };
2075 pending_events.push_back((fail_ev, None));
2076 false
2077 } else {
2078 true
2079 }
2080 },
2081 _ => true,
2082 });
2083 }
2084
2085 pub(super) fn fail_htlc<L: Deref>(
2087 &self, source: &HTLCSource, payment_hash: &PaymentHash, onion_error: &HTLCFailReason,
2088 path: &Path, session_priv: &SecretKey, payment_id: &PaymentId,
2089 probing_cookie_secret: [u8; 32], secp_ctx: &Secp256k1<secp256k1::All>,
2090 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, logger: &L,
2091 ) -> bool where L::Target: Logger {
2092 #[cfg(test)]
2093 let DecodedOnionFailure {
2094 network_update, short_channel_id, payment_failed_permanently, onion_error_code,
2095 onion_error_data, failed_within_blinded_path
2096 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
2097 #[cfg(not(test))]
2098 let DecodedOnionFailure {
2099 network_update, short_channel_id, payment_failed_permanently, failed_within_blinded_path
2100 } = onion_error.decode_onion_failure(secp_ctx, logger, &source);
2101
2102 let payment_is_probe = payment_is_probe(payment_hash, &payment_id, probing_cookie_secret);
2103 let mut session_priv_bytes = [0; 32];
2104 session_priv_bytes.copy_from_slice(&session_priv[..]);
2105 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
2106
2107 let already_awaiting_retry = outbounds.iter().any(|(_, pmt)| {
2110 let mut awaiting_retry = false;
2111 if pmt.is_auto_retryable_now() {
2112 if let PendingOutboundPayment::Retryable { pending_amt_msat, total_msat, .. } = pmt {
2113 if pending_amt_msat < total_msat {
2114 awaiting_retry = true;
2115 }
2116 }
2117 }
2118 awaiting_retry
2119 });
2120
2121 let mut full_failure_ev = None;
2122 let mut pending_retry_ev = false;
2123 let attempts_remaining = if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(*payment_id) {
2124 if !payment.get_mut().remove(&session_priv_bytes, Some(&path)) {
2125 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
2126 return false
2127 }
2128 if payment.get().is_fulfilled() {
2129 log_trace!(logger, "Received failure of HTLC with payment_hash {} after payment completion", &payment_hash);
2130 return false
2131 }
2132 let mut is_retryable_now = payment.get().is_auto_retryable_now();
2133 if let Some(scid) = short_channel_id {
2134 payment.get_mut().insert_previously_failed_scid(scid);
2138 }
2139 if failed_within_blinded_path {
2140 debug_assert!(short_channel_id.is_none());
2141 if let Some(bt) = &path.blinded_tail {
2142 payment.get_mut().insert_previously_failed_blinded_path(&bt);
2143 } else { debug_assert!(false); }
2144 }
2145
2146 if payment_is_probe || !is_retryable_now || payment_failed_permanently {
2147 let reason = if payment_failed_permanently {
2148 PaymentFailureReason::RecipientRejected
2149 } else {
2150 PaymentFailureReason::RetriesExhausted
2151 };
2152 payment.get_mut().mark_abandoned(reason);
2153 is_retryable_now = false;
2154 }
2155 if payment.get().remaining_parts() == 0 {
2156 if let PendingOutboundPayment::Abandoned { payment_hash, reason, .. } = payment.get() {
2157 if !payment_is_probe {
2158 full_failure_ev = Some(events::Event::PaymentFailed {
2159 payment_id: *payment_id,
2160 payment_hash: Some(*payment_hash),
2161 reason: *reason,
2162 });
2163 }
2164 payment.remove();
2165 }
2166 }
2167 is_retryable_now
2168 } else {
2169 log_trace!(logger, "Received duplicative fail for HTLC with payment_hash {}", &payment_hash);
2170 return false
2171 };
2172 core::mem::drop(outbounds);
2173 log_trace!(logger, "Failing outbound payment HTLC with payment_hash {}", &payment_hash);
2174
2175 let path_failure = {
2176 if payment_is_probe {
2177 if payment_failed_permanently {
2178 events::Event::ProbeSuccessful {
2179 payment_id: *payment_id,
2180 payment_hash: payment_hash.clone(),
2181 path: path.clone(),
2182 }
2183 } else {
2184 events::Event::ProbeFailed {
2185 payment_id: *payment_id,
2186 payment_hash: payment_hash.clone(),
2187 path: path.clone(),
2188 short_channel_id,
2189 }
2190 }
2191 } else {
2192 if attempts_remaining && !already_awaiting_retry {
2195 debug_assert!(full_failure_ev.is_none());
2196 pending_retry_ev = true;
2197 }
2198 events::Event::PaymentPathFailed {
2199 payment_id: Some(*payment_id),
2200 payment_hash: payment_hash.clone(),
2201 payment_failed_permanently,
2202 failure: events::PathFailure::OnPath { network_update },
2203 path: path.clone(),
2204 short_channel_id,
2205 #[cfg(test)]
2206 error_code: onion_error_code,
2207 #[cfg(test)]
2208 error_data: onion_error_data
2209 }
2210 }
2211 };
2212 let mut pending_events = pending_events.lock().unwrap();
2213 pending_events.push_back((path_failure, None));
2214 if let Some(ev) = full_failure_ev { pending_events.push_back((ev, None)); }
2215 pending_retry_ev
2216 }
2217
2218 pub(super) fn abandon_payment(
2219 &self, payment_id: PaymentId, reason: PaymentFailureReason,
2220 pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>
2221 ) {
2222 let mut outbounds = self.pending_outbound_payments.lock().unwrap();
2223 if let hash_map::Entry::Occupied(mut payment) = outbounds.entry(payment_id) {
2224 payment.get_mut().mark_abandoned(reason);
2225 match payment.get() {
2226 PendingOutboundPayment::Abandoned { payment_hash, reason, .. } => {
2227 if payment.get().remaining_parts() == 0 {
2228 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
2229 payment_id,
2230 payment_hash: Some(*payment_hash),
2231 reason: *reason,
2232 }, None));
2233 payment.remove();
2234 }
2235 },
2236 PendingOutboundPayment::AwaitingInvoice { .. }
2237 | PendingOutboundPayment::AwaitingOffer { .. } =>
2238 {
2239 pending_events.lock().unwrap().push_back((events::Event::PaymentFailed {
2240 payment_id,
2241 payment_hash: None,
2242 reason: Some(reason),
2243 }, None));
2244 payment.remove();
2245 },
2246 _ => {},
2247 }
2248 }
2249 }
2250
2251 #[cfg(test)]
2252 pub fn has_pending_payments(&self) -> bool {
2253 !self.pending_outbound_payments.lock().unwrap().is_empty()
2254 }
2255
2256 #[cfg(test)]
2257 pub fn clear_pending_payments(&self) {
2258 self.pending_outbound_payments.lock().unwrap().clear()
2259 }
2260
2261 pub fn release_invoice_requests_awaiting_invoice(&self) -> Vec<(PaymentId, RetryableInvoiceRequest)> {
2262 if !self.awaiting_invoice.load(Ordering::Acquire) {
2263 return vec![];
2264 }
2265
2266 let mut pending_outbound_payments = self.pending_outbound_payments.lock().unwrap();
2267 let invoice_requests = pending_outbound_payments
2268 .iter_mut()
2269 .filter_map(|(payment_id, payment)| {
2270 if let PendingOutboundPayment::AwaitingInvoice {
2271 retryable_invoice_request, ..
2272 } = payment {
2273 retryable_invoice_request.take().map(|retryable_invoice_request| {
2274 (*payment_id, retryable_invoice_request)
2275 })
2276 } else {
2277 None
2278 }
2279 })
2280 .collect();
2281
2282 self.awaiting_invoice.store(false, Ordering::Release);
2283 invoice_requests
2284 }
2285
2286 pub(super) fn insert_from_monitor_on_startup<L: Logger>(
2287 &self, payment_id: PaymentId, payment_hash: PaymentHash, session_priv_bytes: [u8; 32],
2288 path: &Path, best_block_height: u32, logger: L
2289 ) {
2290 let path_amt = path.final_value_msat();
2291 let path_fee = path.fee_msat();
2292
2293 macro_rules! new_retryable {
2294 () => {
2295 PendingOutboundPayment::Retryable {
2296 retry_strategy: None,
2297 attempts: PaymentAttempts::new(),
2298 payment_params: None,
2299 session_privs: hash_set_from_iter([session_priv_bytes]),
2300 payment_hash,
2301 payment_secret: None, payment_metadata: None, keysend_preimage: None, invoice_request: None, custom_tlvs: Vec::new(), pending_amt_msat: path_amt,
2307 pending_fee_msat: Some(path_fee),
2308 total_msat: path_amt,
2309 starting_block_height: best_block_height,
2310 remaining_max_total_routing_fee_msat: None, }
2312 }
2313 }
2314
2315 match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
2316 hash_map::Entry::Occupied(mut entry) => {
2317 let newly_added = match entry.get() {
2318 PendingOutboundPayment::AwaitingOffer { .. } |
2319 PendingOutboundPayment::AwaitingInvoice { .. } |
2320 PendingOutboundPayment::InvoiceReceived { .. } |
2321 PendingOutboundPayment::StaticInvoiceReceived { .. } =>
2322 {
2323 *entry.get_mut() = new_retryable!();
2329 true
2330 },
2331 PendingOutboundPayment::Legacy { .. } |
2332 PendingOutboundPayment::Retryable { .. } |
2333 PendingOutboundPayment::Fulfilled { .. } |
2334 PendingOutboundPayment::Abandoned { .. } =>
2335 {
2336 entry.get_mut().insert(session_priv_bytes, &path)
2337 }
2338 };
2339 log_info!(logger, "{} a pending payment path for {} msat for session priv {} on an existing pending payment with payment hash {}",
2340 if newly_added { "Added" } else { "Had" }, path_amt, log_bytes!(session_priv_bytes), payment_hash);
2341 },
2342 hash_map::Entry::Vacant(entry) => {
2343 entry.insert(new_retryable!());
2344 log_info!(logger, "Added a pending payment for {} msat with payment hash {} for path with session priv {}",
2345 path_amt, payment_hash, log_bytes!(session_priv_bytes));
2346 }
2347 }
2348 }
2349}
2350
2351pub(super) fn payment_is_probe(payment_hash: &PaymentHash, payment_id: &PaymentId,
2354 probing_cookie_secret: [u8; 32]) -> bool
2355{
2356 let target_payment_hash = probing_cookie_from_id(payment_id, probing_cookie_secret);
2357 target_payment_hash == *payment_hash
2358}
2359
2360fn probing_cookie_from_id(payment_id: &PaymentId, probing_cookie_secret: [u8; 32]) -> PaymentHash {
2362 let mut preimage = [0u8; 64];
2363 preimage[..32].copy_from_slice(&probing_cookie_secret);
2364 preimage[32..].copy_from_slice(&payment_id.0);
2365 PaymentHash(Sha256::hash(&preimage).to_byte_array())
2366}
2367
2368impl_writeable_tlv_based_enum_upgradable!(PendingOutboundPayment,
2369 (0, Legacy) => {
2370 (0, session_privs, required),
2371 },
2372 (1, Fulfilled) => {
2373 (0, session_privs, required),
2374 (1, payment_hash, option),
2375 (3, timer_ticks_without_htlcs, (default_value, 0)),
2376 },
2377 (2, Retryable) => {
2378 (0, session_privs, required),
2379 (1, pending_fee_msat, option),
2380 (2, payment_hash, required),
2381 (3, payment_params, (option: ReadableArgs, 0)),
2384 (4, payment_secret, option),
2385 (5, keysend_preimage, option),
2386 (6, total_msat, required),
2387 (7, payment_metadata, option),
2388 (8, pending_amt_msat, required),
2389 (9, custom_tlvs, optional_vec),
2390 (10, starting_block_height, required),
2391 (11, remaining_max_total_routing_fee_msat, option),
2392 (13, invoice_request, option),
2393 (not_written, retry_strategy, (static_value, None)),
2394 (not_written, attempts, (static_value, PaymentAttempts::new())),
2395 },
2396 (3, Abandoned) => {
2397 (0, session_privs, required),
2398 (1, reason, upgradable_option),
2399 (2, payment_hash, required),
2400 },
2401 (5, AwaitingInvoice) => {
2402 (0, expiration, required),
2403 (2, retry_strategy, required),
2404 (4, max_total_routing_fee_msat, option),
2405 (5, retryable_invoice_request, option),
2406 },
2407 (7, InvoiceReceived) => {
2408 (0, payment_hash, required),
2409 (2, retry_strategy, required),
2410 (4, max_total_routing_fee_msat, option),
2411 },
2412 (9, StaticInvoiceReceived) => {
2415 (0, payment_hash, required),
2416 (2, keysend_preimage, required),
2417 (4, retry_strategy, required),
2418 (6, route_params, required),
2419 (8, invoice_request, required),
2420 },
2421 (11, AwaitingOffer) => {
2424 (0, expiration, required),
2425 (2, retry_strategy, required),
2426 (4, max_total_routing_fee_msat, option),
2427 (6, amount_msats, required),
2428 },
2429);
2430
2431#[cfg(test)]
2432mod tests {
2433 use bitcoin::network::Network;
2434 use bitcoin::secp256k1::{PublicKey, Secp256k1, SecretKey};
2435
2436 use core::time::Duration;
2437
2438 use crate::blinded_path::EmptyNodeIdLookUp;
2439 use crate::events::{Event, PathFailure, PaymentFailureReason};
2440 use crate::types::payment::{PaymentHash, PaymentPreimage};
2441 use crate::ln::channelmanager::{PaymentId, RecipientOnionFields};
2442 use crate::ln::inbound_payment::ExpandedKey;
2443 use crate::types::features::{Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
2444 use crate::ln::msgs::{ErrorAction, LightningError};
2445 use crate::ln::outbound_payment::{Bolt12PaymentError, OutboundPayments, PendingOutboundPayment, Retry, RetryableSendFailure, StaleExpiration};
2446 #[cfg(feature = "std")]
2447 use crate::offers::invoice::DEFAULT_RELATIVE_EXPIRY;
2448 use crate::offers::invoice_request::InvoiceRequest;
2449 use crate::offers::nonce::Nonce;
2450 use crate::offers::offer::OfferBuilder;
2451 use crate::offers::test_utils::*;
2452 use crate::routing::gossip::NetworkGraph;
2453 use crate::routing::router::{InFlightHtlcs, Path, PaymentParameters, Route, RouteHop, RouteParameters};
2454 use crate::sync::{Arc, Mutex, RwLock};
2455 use crate::util::errors::APIError;
2456 use crate::util::hash_tables::new_hash_map;
2457 use crate::util::test_utils;
2458
2459 use alloc::collections::VecDeque;
2460
2461 #[test]
2462 fn test_recipient_onion_fields_with_custom_tlvs() {
2463 let onion_fields = RecipientOnionFields::spontaneous_empty();
2464
2465 let bad_type_range_tlvs = vec![
2466 (0, vec![42]),
2467 (1, vec![42; 32]),
2468 ];
2469 assert!(onion_fields.clone().with_custom_tlvs(bad_type_range_tlvs).is_err());
2470
2471 let keysend_tlv = vec![
2472 (5482373484, vec![42; 32]),
2473 ];
2474 assert!(onion_fields.clone().with_custom_tlvs(keysend_tlv).is_err());
2475
2476 let good_tlvs = vec![
2477 ((1 << 16) + 1, vec![42]),
2478 ((1 << 16) + 3, vec![42; 32]),
2479 ];
2480 assert!(onion_fields.with_custom_tlvs(good_tlvs).is_ok());
2481 }
2482
2483 #[test]
2484 #[cfg(feature = "std")]
2485 fn fails_paying_after_expiration() {
2486 do_fails_paying_after_expiration(false);
2487 do_fails_paying_after_expiration(true);
2488 }
2489 #[cfg(feature = "std")]
2490 fn do_fails_paying_after_expiration(on_retry: bool) {
2491 let outbound_payments = OutboundPayments::new(new_hash_map());
2492 let logger = test_utils::TestLogger::new();
2493 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2494 let scorer = RwLock::new(test_utils::TestScorer::new());
2495 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2496 let secp_ctx = Secp256k1::new();
2497 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2498
2499 let past_expiry_time = std::time::SystemTime::UNIX_EPOCH.elapsed().unwrap().as_secs() - 2;
2500 let payment_params = PaymentParameters::from_node_id(
2501 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()),
2502 0
2503 ).with_expiry_time(past_expiry_time);
2504 let expired_route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
2505 let pending_events = Mutex::new(VecDeque::new());
2506 if on_retry {
2507 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
2508 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
2509 Some(Retry::Attempts(1)), Some(expired_route_params.payment_params.clone()),
2510 &&keys_manager, 0).unwrap();
2511 outbound_payments.find_route_and_send_payment(
2512 PaymentHash([0; 32]), PaymentId([0; 32]), expired_route_params, &&router, vec![],
2513 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2514 &|_| Ok(()));
2515 let events = pending_events.lock().unwrap();
2516 assert_eq!(events.len(), 1);
2517 if let Event::PaymentFailed { ref reason, .. } = events[0].0 {
2518 assert_eq!(reason.unwrap(), PaymentFailureReason::PaymentExpired);
2519 } else { panic!("Unexpected event"); }
2520 } else {
2521 let err = outbound_payments.send_payment(
2522 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2523 Retry::Attempts(0), expired_route_params, &&router, vec![], || InFlightHtlcs::new(),
2524 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
2525 if let RetryableSendFailure::PaymentExpired = err { } else { panic!("Unexpected error"); }
2526 }
2527 }
2528
2529 #[test]
2530 fn find_route_error() {
2531 do_find_route_error(false);
2532 do_find_route_error(true);
2533 }
2534 fn do_find_route_error(on_retry: bool) {
2535 let outbound_payments = OutboundPayments::new(new_hash_map());
2536 let logger = test_utils::TestLogger::new();
2537 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2538 let scorer = RwLock::new(test_utils::TestScorer::new());
2539 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2540 let secp_ctx = Secp256k1::new();
2541 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2542
2543 let payment_params = PaymentParameters::from_node_id(
2544 PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap()), 0);
2545 let route_params = RouteParameters::from_payment_params_and_value(payment_params, 0);
2546 router.expect_find_route(route_params.clone(),
2547 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }));
2548
2549 let pending_events = Mutex::new(VecDeque::new());
2550 if on_retry {
2551 outbound_payments.add_new_pending_payment(PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(),
2552 PaymentId([0; 32]), None, &Route { paths: vec![], route_params: None },
2553 Some(Retry::Attempts(1)), Some(route_params.payment_params.clone()),
2554 &&keys_manager, 0).unwrap();
2555 outbound_payments.find_route_and_send_payment(
2556 PaymentHash([0; 32]), PaymentId([0; 32]), route_params, &&router, vec![],
2557 &|| InFlightHtlcs::new(), &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2558 &|_| Ok(()));
2559 let events = pending_events.lock().unwrap();
2560 assert_eq!(events.len(), 1);
2561 if let Event::PaymentFailed { .. } = events[0].0 { } else { panic!("Unexpected event"); }
2562 } else {
2563 let err = outbound_payments.send_payment(
2564 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2565 Retry::Attempts(0), route_params, &&router, vec![], || InFlightHtlcs::new(),
2566 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events, |_| Ok(())).unwrap_err();
2567 if let RetryableSendFailure::RouteNotFound = err {
2568 } else { panic!("Unexpected error"); }
2569 }
2570 }
2571
2572 #[test]
2573 fn initial_send_payment_path_failed_evs() {
2574 let outbound_payments = OutboundPayments::new(new_hash_map());
2575 let logger = test_utils::TestLogger::new();
2576 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2577 let scorer = RwLock::new(test_utils::TestScorer::new());
2578 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2579 let secp_ctx = Secp256k1::new();
2580 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2581
2582 let sender_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[42; 32]).unwrap());
2583 let receiver_pk = PublicKey::from_secret_key(&secp_ctx, &SecretKey::from_slice(&[43; 32]).unwrap());
2584 let payment_params = PaymentParameters::from_node_id(sender_pk, 0);
2585 let route_params = RouteParameters::from_payment_params_and_value(payment_params.clone(), 0);
2586 let failed_scid = 42;
2587 let route = Route {
2588 paths: vec![Path { hops: vec![RouteHop {
2589 pubkey: receiver_pk,
2590 node_features: NodeFeatures::empty(),
2591 short_channel_id: failed_scid,
2592 channel_features: ChannelFeatures::empty(),
2593 fee_msat: 0,
2594 cltv_expiry_delta: 0,
2595 maybe_announced_channel: true,
2596 }], blinded_tail: None }],
2597 route_params: Some(route_params.clone()),
2598 };
2599 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2600 let mut route_params_w_failed_scid = route_params.clone();
2601 route_params_w_failed_scid.payment_params.previously_failed_channels.push(failed_scid);
2602 let mut route_w_failed_scid = route.clone();
2603 route_w_failed_scid.route_params = Some(route_params_w_failed_scid.clone());
2604 router.expect_find_route(route_params_w_failed_scid, Ok(route_w_failed_scid));
2605 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2606 router.expect_find_route(route_params.clone(), Ok(route.clone()));
2607
2608 let pending_events = Mutex::new(VecDeque::new());
2611 outbound_payments.send_payment(
2612 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2613 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2614 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2615 |_| Err(APIError::ChannelUnavailable { err: "test".to_owned() })).unwrap();
2616 let mut events = pending_events.lock().unwrap();
2617 assert_eq!(events.len(), 2);
2618 if let Event::PaymentPathFailed {
2619 short_channel_id,
2620 failure: PathFailure::InitialSend { err: APIError::ChannelUnavailable { .. }}, .. } = events[0].0
2621 {
2622 assert_eq!(short_channel_id, Some(failed_scid));
2623 } else { panic!("Unexpected event"); }
2624 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2625 events.clear();
2626 core::mem::drop(events);
2627
2628 outbound_payments.send_payment(
2630 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([0; 32]),
2631 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2632 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2633 |_| Err(APIError::MonitorUpdateInProgress)).unwrap();
2634 assert_eq!(pending_events.lock().unwrap().len(), 0);
2635
2636 outbound_payments.send_payment(
2638 PaymentHash([0; 32]), RecipientOnionFields::spontaneous_empty(), PaymentId([1; 32]),
2639 Retry::Attempts(0), route_params.clone(), &&router, vec![], || InFlightHtlcs::new(),
2640 &&keys_manager, &&keys_manager, 0, &&logger, &pending_events,
2641 |_| Err(APIError::APIMisuseError { err: "test".to_owned() })).unwrap();
2642 let events = pending_events.lock().unwrap();
2643 assert_eq!(events.len(), 2);
2644 if let Event::PaymentPathFailed {
2645 short_channel_id,
2646 failure: PathFailure::InitialSend { err: APIError::APIMisuseError { .. }}, .. } = events[0].0
2647 {
2648 assert_eq!(short_channel_id, None);
2649 } else { panic!("Unexpected event"); }
2650 if let Event::PaymentFailed { .. } = events[1].0 { } else { panic!("Unexpected event"); }
2651 }
2652
2653 #[test]
2654 fn removes_stale_awaiting_invoice_using_absolute_timeout() {
2655 let pending_events = Mutex::new(VecDeque::new());
2656 let outbound_payments = OutboundPayments::new(new_hash_map());
2657 let payment_id = PaymentId([0; 32]);
2658 let absolute_expiry = 100;
2659 let tick_interval = 10;
2660 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(absolute_expiry));
2661
2662 assert!(!outbound_payments.has_pending_payments());
2663 assert!(
2664 outbound_payments.add_new_awaiting_invoice(
2665 payment_id, expiration, Retry::Attempts(0), None, None,
2666 ).is_ok()
2667 );
2668 assert!(outbound_payments.has_pending_payments());
2669
2670 for seconds_since_epoch in (0..absolute_expiry).step_by(tick_interval) {
2671 let duration_since_epoch = Duration::from_secs(seconds_since_epoch);
2672 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2673
2674 assert!(outbound_payments.has_pending_payments());
2675 assert!(pending_events.lock().unwrap().is_empty());
2676 }
2677
2678 let duration_since_epoch = Duration::from_secs(absolute_expiry);
2679 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2680
2681 assert!(!outbound_payments.has_pending_payments());
2682 assert!(!pending_events.lock().unwrap().is_empty());
2683 assert_eq!(
2684 pending_events.lock().unwrap().pop_front(),
2685 Some((Event::PaymentFailed {
2686 payment_id,
2687 payment_hash: None,
2688 reason: Some(PaymentFailureReason::InvoiceRequestExpired),
2689 }, None)),
2690 );
2691 assert!(pending_events.lock().unwrap().is_empty());
2692
2693 assert!(
2694 outbound_payments.add_new_awaiting_invoice(
2695 payment_id, expiration, Retry::Attempts(0), None, None,
2696 ).is_ok()
2697 );
2698 assert!(outbound_payments.has_pending_payments());
2699
2700 assert!(
2701 outbound_payments.add_new_awaiting_invoice(
2702 payment_id, expiration, Retry::Attempts(0), None, None,
2703 ).is_err()
2704 );
2705 }
2706
2707 #[test]
2708 fn removes_stale_awaiting_invoice_using_timer_ticks() {
2709 let pending_events = Mutex::new(VecDeque::new());
2710 let outbound_payments = OutboundPayments::new(new_hash_map());
2711 let payment_id = PaymentId([0; 32]);
2712 let timer_ticks = 3;
2713 let expiration = StaleExpiration::TimerTicks(timer_ticks);
2714
2715 assert!(!outbound_payments.has_pending_payments());
2716 assert!(
2717 outbound_payments.add_new_awaiting_invoice(
2718 payment_id, expiration, Retry::Attempts(0), None, None,
2719 ).is_ok()
2720 );
2721 assert!(outbound_payments.has_pending_payments());
2722
2723 for i in 0..timer_ticks {
2724 let duration_since_epoch = Duration::from_secs(i * 60);
2725 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2726
2727 assert!(outbound_payments.has_pending_payments());
2728 assert!(pending_events.lock().unwrap().is_empty());
2729 }
2730
2731 let duration_since_epoch = Duration::from_secs(timer_ticks * 60);
2732 outbound_payments.remove_stale_payments(duration_since_epoch, &pending_events);
2733
2734 assert!(!outbound_payments.has_pending_payments());
2735 assert!(!pending_events.lock().unwrap().is_empty());
2736 assert_eq!(
2737 pending_events.lock().unwrap().pop_front(),
2738 Some((Event::PaymentFailed {
2739 payment_id,
2740 payment_hash: None,
2741 reason: Some(PaymentFailureReason::InvoiceRequestExpired),
2742 }, None)),
2743 );
2744 assert!(pending_events.lock().unwrap().is_empty());
2745
2746 assert!(
2747 outbound_payments.add_new_awaiting_invoice(
2748 payment_id, expiration, Retry::Attempts(0), None, None,
2749 ).is_ok()
2750 );
2751 assert!(outbound_payments.has_pending_payments());
2752
2753 assert!(
2754 outbound_payments.add_new_awaiting_invoice(
2755 payment_id, expiration, Retry::Attempts(0), None, None,
2756 ).is_err()
2757 );
2758 }
2759
2760 #[test]
2761 fn removes_abandoned_awaiting_invoice() {
2762 let pending_events = Mutex::new(VecDeque::new());
2763 let outbound_payments = OutboundPayments::new(new_hash_map());
2764 let payment_id = PaymentId([0; 32]);
2765 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2766
2767 assert!(!outbound_payments.has_pending_payments());
2768 assert!(
2769 outbound_payments.add_new_awaiting_invoice(
2770 payment_id, expiration, Retry::Attempts(0), None, None,
2771 ).is_ok()
2772 );
2773 assert!(outbound_payments.has_pending_payments());
2774
2775 outbound_payments.abandon_payment(
2776 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
2777 );
2778 assert!(!outbound_payments.has_pending_payments());
2779 assert!(!pending_events.lock().unwrap().is_empty());
2780 assert_eq!(
2781 pending_events.lock().unwrap().pop_front(),
2782 Some((Event::PaymentFailed {
2783 payment_id, payment_hash: None, reason: Some(PaymentFailureReason::UserAbandoned),
2784 }, None)),
2785 );
2786 assert!(pending_events.lock().unwrap().is_empty());
2787 }
2788
2789 #[cfg(feature = "std")]
2790 #[test]
2791 fn fails_sending_payment_for_expired_bolt12_invoice() {
2792 let logger = test_utils::TestLogger::new();
2793 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2794 let scorer = RwLock::new(test_utils::TestScorer::new());
2795 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2796 let secp_ctx = Secp256k1::new();
2797 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2798 let expanded_key = ExpandedKey::new([42; 32]);
2799 let nonce = Nonce([0; 16]);
2800
2801 let pending_events = Mutex::new(VecDeque::new());
2802 let outbound_payments = OutboundPayments::new(new_hash_map());
2803 let payment_id = PaymentId([0; 32]);
2804 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2805
2806 assert!(
2807 outbound_payments.add_new_awaiting_invoice(
2808 payment_id, expiration, Retry::Attempts(0), None, None,
2809 ).is_ok()
2810 );
2811 assert!(outbound_payments.has_pending_payments());
2812
2813 let created_at = now() - DEFAULT_RELATIVE_EXPIRY;
2814 let invoice = OfferBuilder::new(recipient_pubkey())
2815 .amount_msats(1000)
2816 .build().unwrap()
2817 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2818 .build_and_sign().unwrap()
2819 .respond_with_no_std(payment_paths(), payment_hash(), created_at).unwrap()
2820 .build().unwrap()
2821 .sign(recipient_sign).unwrap();
2822
2823 assert_eq!(
2824 outbound_payments.send_payment_for_bolt12_invoice(
2825 &invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
2826 || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
2827 &secp_ctx, 0, &&logger, &pending_events, |_| panic!()
2828 ),
2829 Err(Bolt12PaymentError::SendingFailed(RetryableSendFailure::PaymentExpired)),
2830 );
2831 assert!(!outbound_payments.has_pending_payments());
2832
2833 let payment_hash = Some(invoice.payment_hash());
2834 let reason = Some(PaymentFailureReason::PaymentExpired);
2835
2836 assert!(!pending_events.lock().unwrap().is_empty());
2837 assert_eq!(
2838 pending_events.lock().unwrap().pop_front(),
2839 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2840 );
2841 assert!(pending_events.lock().unwrap().is_empty());
2842 }
2843
2844 #[test]
2845 fn fails_finding_route_for_bolt12_invoice() {
2846 let logger = test_utils::TestLogger::new();
2847 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2848 let scorer = RwLock::new(test_utils::TestScorer::new());
2849 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2850 let secp_ctx = Secp256k1::new();
2851 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2852
2853 let pending_events = Mutex::new(VecDeque::new());
2854 let outbound_payments = OutboundPayments::new(new_hash_map());
2855 let expanded_key = ExpandedKey::new([42; 32]);
2856 let nonce = Nonce([0; 16]);
2857 let payment_id = PaymentId([0; 32]);
2858 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2859
2860 let invoice = OfferBuilder::new(recipient_pubkey())
2861 .amount_msats(1000)
2862 .build().unwrap()
2863 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2864 .build_and_sign().unwrap()
2865 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2866 .build().unwrap()
2867 .sign(recipient_sign).unwrap();
2868
2869 assert!(
2870 outbound_payments.add_new_awaiting_invoice(
2871 payment_id, expiration, Retry::Attempts(0),
2872 Some(invoice.amount_msats() / 100 + 50_000), None,
2873 ).is_ok()
2874 );
2875 assert!(outbound_payments.has_pending_payments());
2876
2877 router.expect_find_route(
2878 RouteParameters::from_payment_params_and_value(
2879 PaymentParameters::from_bolt12_invoice(&invoice),
2880 invoice.amount_msats(),
2881 ),
2882 Err(LightningError { err: String::new(), action: ErrorAction::IgnoreError }),
2883 );
2884
2885 assert_eq!(
2886 outbound_payments.send_payment_for_bolt12_invoice(
2887 &invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
2888 || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
2889 &secp_ctx, 0, &&logger, &pending_events, |_| panic!()
2890 ),
2891 Err(Bolt12PaymentError::SendingFailed(RetryableSendFailure::RouteNotFound)),
2892 );
2893 assert!(!outbound_payments.has_pending_payments());
2894
2895 let payment_hash = Some(invoice.payment_hash());
2896 let reason = Some(PaymentFailureReason::RouteNotFound);
2897
2898 assert!(!pending_events.lock().unwrap().is_empty());
2899 assert_eq!(
2900 pending_events.lock().unwrap().pop_front(),
2901 Some((Event::PaymentFailed { payment_id, payment_hash, reason }, None)),
2902 );
2903 assert!(pending_events.lock().unwrap().is_empty());
2904 }
2905
2906 #[test]
2907 fn sends_payment_for_bolt12_invoice() {
2908 let logger = test_utils::TestLogger::new();
2909 let network_graph = Arc::new(NetworkGraph::new(Network::Testnet, &logger));
2910 let scorer = RwLock::new(test_utils::TestScorer::new());
2911 let router = test_utils::TestRouter::new(network_graph, &logger, &scorer);
2912 let secp_ctx = Secp256k1::new();
2913 let keys_manager = test_utils::TestKeysInterface::new(&[0; 32], Network::Testnet);
2914
2915 let pending_events = Mutex::new(VecDeque::new());
2916 let outbound_payments = OutboundPayments::new(new_hash_map());
2917 let expanded_key = ExpandedKey::new([42; 32]);
2918 let nonce = Nonce([0; 16]);
2919 let payment_id = PaymentId([0; 32]);
2920 let expiration = StaleExpiration::AbsoluteTimeout(Duration::from_secs(100));
2921
2922 let invoice = OfferBuilder::new(recipient_pubkey())
2923 .amount_msats(1000)
2924 .build().unwrap()
2925 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id).unwrap()
2926 .build_and_sign().unwrap()
2927 .respond_with_no_std(payment_paths(), payment_hash(), now()).unwrap()
2928 .build().unwrap()
2929 .sign(recipient_sign).unwrap();
2930
2931 let route_params = RouteParameters {
2932 payment_params: PaymentParameters::from_bolt12_invoice(&invoice),
2933 final_value_msat: invoice.amount_msats(),
2934 max_total_routing_fee_msat: Some(1234),
2935 };
2936 router.expect_find_route(
2937 route_params.clone(),
2938 Ok(Route {
2939 paths: vec![
2940 Path {
2941 hops: vec![
2942 RouteHop {
2943 pubkey: recipient_pubkey(),
2944 node_features: NodeFeatures::empty(),
2945 short_channel_id: 42,
2946 channel_features: ChannelFeatures::empty(),
2947 fee_msat: invoice.amount_msats(),
2948 cltv_expiry_delta: 0,
2949 maybe_announced_channel: true,
2950 }
2951 ],
2952 blinded_tail: None,
2953 }
2954 ],
2955 route_params: Some(route_params),
2956 })
2957 );
2958
2959 assert!(!outbound_payments.has_pending_payments());
2960 assert_eq!(
2961 outbound_payments.send_payment_for_bolt12_invoice(
2962 &invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
2963 || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
2964 &secp_ctx, 0, &&logger, &pending_events, |_| panic!()
2965 ),
2966 Err(Bolt12PaymentError::UnexpectedInvoice),
2967 );
2968 assert!(!outbound_payments.has_pending_payments());
2969 assert!(pending_events.lock().unwrap().is_empty());
2970
2971 assert!(
2972 outbound_payments.add_new_awaiting_invoice(
2973 payment_id, expiration, Retry::Attempts(0), Some(1234), None,
2974 ).is_ok()
2975 );
2976 assert!(outbound_payments.has_pending_payments());
2977
2978 assert_eq!(
2979 outbound_payments.send_payment_for_bolt12_invoice(
2980 &invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
2981 || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
2982 &secp_ctx, 0, &&logger, &pending_events, |_| Ok(())
2983 ),
2984 Ok(()),
2985 );
2986 assert!(outbound_payments.has_pending_payments());
2987 assert!(pending_events.lock().unwrap().is_empty());
2988
2989 assert_eq!(
2990 outbound_payments.send_payment_for_bolt12_invoice(
2991 &invoice, payment_id, &&router, vec![], Bolt12InvoiceFeatures::empty(),
2992 || InFlightHtlcs::new(), &&keys_manager, &&keys_manager, &EmptyNodeIdLookUp {},
2993 &secp_ctx, 0, &&logger, &pending_events, |_| panic!()
2994 ),
2995 Err(Bolt12PaymentError::DuplicateInvoice),
2996 );
2997 assert!(outbound_payments.has_pending_payments());
2998 assert!(pending_events.lock().unwrap().is_empty());
2999 }
3000
3001 fn dummy_invoice_request() -> InvoiceRequest {
3002 let expanded_key = ExpandedKey::new([42; 32]);
3003 let entropy = FixedEntropy {};
3004 let nonce = Nonce::from_entropy_source(&entropy);
3005 let secp_ctx = Secp256k1::new();
3006 let payment_id = PaymentId([1; 32]);
3007
3008 OfferBuilder::new(recipient_pubkey())
3009 .amount_msats(1000)
3010 .build().unwrap()
3011 .request_invoice(&expanded_key, nonce, &secp_ctx, payment_id)
3012 .unwrap()
3013 .build_and_sign()
3014 .unwrap()
3015 }
3016
3017 #[test]
3018 fn time_out_unreleased_async_payments() {
3019 let pending_events = Mutex::new(VecDeque::new());
3020 let outbound_payments = OutboundPayments::new(new_hash_map());
3021 let payment_id = PaymentId([0; 32]);
3022 let absolute_expiry = 60;
3023
3024 let mut outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3025 let payment_params = PaymentParameters::from_node_id(test_utils::pubkey(42), 0)
3026 .with_expiry_time(absolute_expiry);
3027 let route_params = RouteParameters {
3028 payment_params,
3029 final_value_msat: 0,
3030 max_total_routing_fee_msat: None,
3031 };
3032 let payment_hash = PaymentHash([0; 32]);
3033 let outbound = PendingOutboundPayment::StaticInvoiceReceived {
3034 payment_hash,
3035 keysend_preimage: PaymentPreimage([0; 32]),
3036 retry_strategy: Retry::Attempts(0),
3037 route_params,
3038 invoice_request: dummy_invoice_request(),
3039 };
3040 outbounds.insert(payment_id, outbound);
3041 core::mem::drop(outbounds);
3042
3043 outbound_payments.remove_stale_payments(Duration::from_secs(absolute_expiry), &pending_events);
3045 let outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3046 assert_eq!(outbounds.len(), 1);
3047 let events = pending_events.lock().unwrap();
3048 assert_eq!(events.len(), 0);
3049 core::mem::drop(outbounds);
3050 core::mem::drop(events);
3051
3052 outbound_payments.remove_stale_payments(Duration::from_secs(absolute_expiry + 1), &pending_events);
3053 let outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3054 assert_eq!(outbounds.len(), 0);
3055 let events = pending_events.lock().unwrap();
3056 assert_eq!(events.len(), 1);
3057 assert_eq!(events[0], (Event::PaymentFailed {
3058 payment_hash: Some(payment_hash),
3059 payment_id,
3060 reason: Some(PaymentFailureReason::PaymentExpired),
3061 }, None));
3062 }
3063
3064 #[test]
3065 fn abandon_unreleased_async_payment() {
3066 let pending_events = Mutex::new(VecDeque::new());
3067 let outbound_payments = OutboundPayments::new(new_hash_map());
3068 let payment_id = PaymentId([0; 32]);
3069 let absolute_expiry = 60;
3070
3071 let mut outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3072 let payment_params = PaymentParameters::from_node_id(test_utils::pubkey(42), 0)
3073 .with_expiry_time(absolute_expiry);
3074 let route_params = RouteParameters {
3075 payment_params,
3076 final_value_msat: 0,
3077 max_total_routing_fee_msat: None,
3078 };
3079 let payment_hash = PaymentHash([0; 32]);
3080 let outbound = PendingOutboundPayment::StaticInvoiceReceived {
3081 payment_hash,
3082 keysend_preimage: PaymentPreimage([0; 32]),
3083 retry_strategy: Retry::Attempts(0),
3084 route_params,
3085 invoice_request: dummy_invoice_request(),
3086 };
3087 outbounds.insert(payment_id, outbound);
3088 core::mem::drop(outbounds);
3089
3090 outbound_payments.abandon_payment(
3091 payment_id, PaymentFailureReason::UserAbandoned, &pending_events
3092 );
3093 let outbounds = outbound_payments.pending_outbound_payments.lock().unwrap();
3094 assert_eq!(outbounds.len(), 0);
3095 let events = pending_events.lock().unwrap();
3096 assert_eq!(events.len(), 1);
3097 assert_eq!(events[0], (Event::PaymentFailed {
3098 payment_hash: Some(payment_hash),
3099 payment_id,
3100 reason: Some(PaymentFailureReason::UserAbandoned),
3101 }, None));
3102 }
3103}