-
Notifications
You must be signed in to change notification settings - Fork 371
/
outbound_payment.rs
3063 lines (2860 loc) · 122 KB
/
outbound_payment.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Utilities to send payments and manage outbound payment information.
use bitcoin::hashes::Hash;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::secp256k1::{self, Secp256k1, SecretKey};
use crate::blinded_path::{IntroductionNode, NodeIdLookUp};
use crate::events::{self, PaymentFailureReason};
use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::channelmanager::{EventCompletionAction, HTLCSource, PaymentId};
use crate::types::features::Bolt12InvoiceFeatures;
use crate::ln::onion_utils;
use crate::ln::onion_utils::{DecodedOnionFailure, HTLCFailReason};
use crate::offers::invoice::Bolt12Invoice;
use crate::offers::invoice_request::InvoiceRequest;
use crate::offers::nonce::Nonce;
use crate::routing::router::{BlindedTail, InFlightHtlcs, Path, PaymentParameters, Route, RouteParameters, Router};
use crate::sign::{EntropySource, NodeSigner, Recipient};
use crate::util::errors::APIError;
use crate::util::logger::Logger;
#[cfg(feature = "std")]
use crate::util::time::Instant;
use crate::util::ser::ReadableArgs;
#[cfg(async_payments)]
use {
crate::offers::invoice::{DerivedSigningPubkey, InvoiceBuilder},
crate::offers::static_invoice::StaticInvoice,
};
use core::fmt::{self, Display, Formatter};
use core::ops::Deref;
use core::sync::atomic::{AtomicBool, Ordering};
use core::time::Duration;
use crate::prelude::*;
use crate::sync::Mutex;
/// The number of ticks of [`ChannelManager::timer_tick_occurred`] until we time-out the idempotency
/// of payments by [`PaymentId`]. See [`OutboundPayments::remove_stale_payments`].
///
/// [`ChannelManager::timer_tick_occurred`]: crate::ln::channelmanager::ChannelManager::timer_tick_occurred
pub(crate) const IDEMPOTENCY_TIMEOUT_TICKS: u8 = 7;
/// Stores the session_priv for each part of a payment that is still pending. For versions 0.0.102
/// and later, also stores information for retrying the payment.
pub(crate) enum PendingOutboundPayment {
Legacy {
session_privs: HashSet<[u8; 32]>,
},
/// Used when we are waiting for an Offer to come back from a BIP 353 resolution
AwaitingOffer {
expiration: StaleExpiration,
retry_strategy: Retry,
max_total_routing_fee_msat: Option<u64>,
/// Human Readable Names-originated payments should always specify an explicit amount to
/// send up-front, which we track here and enforce once we receive the offer.
amount_msats: u64,
},
AwaitingInvoice {
expiration: StaleExpiration,
retry_strategy: Retry,
max_total_routing_fee_msat: Option<u64>,
retryable_invoice_request: Option<RetryableInvoiceRequest>
},
// This state will never be persisted to disk because we transition from `AwaitingInvoice` to
// `Retryable` atomically within the `ChannelManager::total_consistency_lock`. Useful to avoid
// holding the `OutboundPayments::pending_outbound_payments` lock during pathfinding.
InvoiceReceived {
payment_hash: PaymentHash,
retry_strategy: Retry,
// Note this field is currently just replicated from AwaitingInvoice but not actually
// used anywhere.
max_total_routing_fee_msat: Option<u64>,
},
// This state applies when we are paying an often-offline recipient and another node on the
// network served us a static invoice on the recipient's behalf in response to our invoice
// request. As a result, once a payment gets in this state it will remain here until the recipient
// comes back online, which may take hours or even days.
StaticInvoiceReceived {
payment_hash: PaymentHash,
keysend_preimage: PaymentPreimage,
retry_strategy: Retry,
route_params: RouteParameters,
invoice_request: InvoiceRequest,
},
Retryable {
retry_strategy: Option<Retry>,
attempts: PaymentAttempts,
payment_params: Option<PaymentParameters>,
session_privs: HashSet<[u8; 32]>,
payment_hash: PaymentHash,
payment_secret: Option<PaymentSecret>,
payment_metadata: Option<Vec<u8>>,
keysend_preimage: Option<PaymentPreimage>,
invoice_request: Option<InvoiceRequest>,
custom_tlvs: Vec<(u64, Vec<u8>)>,
pending_amt_msat: u64,
/// Used to track the fee paid. Present iff the payment was serialized on 0.0.103+.
pending_fee_msat: Option<u64>,
/// The total payment amount across all paths, used to verify that a retry is not overpaying.
total_msat: u64,
/// Our best known block height at the time this payment was initiated.
starting_block_height: u32,
remaining_max_total_routing_fee_msat: Option<u64>,
},
/// When a pending payment is fulfilled, we continue tracking it until all pending HTLCs have
/// been resolved. This ensures we don't look up pending payments in ChannelMonitors on restart
/// and add a pending payment that was already fulfilled.
Fulfilled {
session_privs: HashSet<[u8; 32]>,
/// Filled in for any payment which moved to `Fulfilled` on LDK 0.0.104 or later.
payment_hash: Option<PaymentHash>,
timer_ticks_without_htlcs: u8,
},
/// When we've decided to give up retrying a payment, we mark it as abandoned so we can eventually
/// generate a `PaymentFailed` event when all HTLCs have irrevocably failed.
Abandoned {
session_privs: HashSet<[u8; 32]>,
payment_hash: PaymentHash,
/// Will be `None` if the payment was serialized before 0.0.115 or if downgrading to 0.0.124
/// or later with a reason that was added after.
reason: Option<PaymentFailureReason>,
},
}
pub(crate) struct RetryableInvoiceRequest {
pub(crate) invoice_request: InvoiceRequest,
pub(crate) nonce: Nonce,
}
impl_writeable_tlv_based!(RetryableInvoiceRequest, {
(0, invoice_request, required),
(2, nonce, required),
});
impl PendingOutboundPayment {
fn increment_attempts(&mut self) {
if let PendingOutboundPayment::Retryable { attempts, .. } = self {
attempts.count += 1;
}
}
fn is_auto_retryable_now(&self) -> bool {
match self {
PendingOutboundPayment::Retryable {
retry_strategy: Some(strategy), attempts, payment_params: Some(_), ..
} => {
strategy.is_retryable_now(&attempts)
},
_ => false,
}
}
fn is_retryable_now(&self) -> bool {
match self {
PendingOutboundPayment::Retryable { retry_strategy: None, .. } => {
// We're handling retries manually, we can always retry.
true
},
PendingOutboundPayment::Retryable { retry_strategy: Some(strategy), attempts, .. } => {
strategy.is_retryable_now(&attempts)
},
_ => false,
}
}
pub fn insert_previously_failed_scid(&mut self, scid: u64) {
if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
params.previously_failed_channels.push(scid);
}
}
pub fn insert_previously_failed_blinded_path(&mut self, blinded_tail: &BlindedTail) {
if let PendingOutboundPayment::Retryable { payment_params: Some(params), .. } = self {
params.insert_previously_failed_blinded_path(blinded_tail);
}
}
fn is_awaiting_invoice(&self) -> bool {
match self {
PendingOutboundPayment::AwaitingInvoice { .. } => true,
_ => false,
}
}
pub(super) fn is_fulfilled(&self) -> bool {
match self {
PendingOutboundPayment::Fulfilled { .. } => true,
_ => false,
}
}
pub(super) fn abandoned(&self) -> bool {
match self {
PendingOutboundPayment::Abandoned { .. } => true,
_ => false,
}
}
fn get_pending_fee_msat(&self) -> Option<u64> {
match self {
PendingOutboundPayment::Retryable { pending_fee_msat, .. } => pending_fee_msat.clone(),
_ => None,
}
}
fn payment_hash(&self) -> Option<PaymentHash> {
match self {
PendingOutboundPayment::Legacy { .. } => None,
PendingOutboundPayment::AwaitingOffer { .. } => None,
PendingOutboundPayment::AwaitingInvoice { .. } => None,
PendingOutboundPayment::InvoiceReceived { payment_hash, .. } => Some(*payment_hash),
PendingOutboundPayment::StaticInvoiceReceived { payment_hash, .. } => Some(*payment_hash),
PendingOutboundPayment::Retryable { payment_hash, .. } => Some(*payment_hash),
PendingOutboundPayment::Fulfilled { payment_hash, .. } => *payment_hash,
PendingOutboundPayment::Abandoned { payment_hash, .. } => Some(*payment_hash),
}
}
fn mark_fulfilled(&mut self) {
let mut session_privs = new_hash_set();
core::mem::swap(&mut session_privs, match self {
PendingOutboundPayment::Legacy { session_privs } |
PendingOutboundPayment::Retryable { session_privs, .. } |
PendingOutboundPayment::Fulfilled { session_privs, .. } |
PendingOutboundPayment::Abandoned { session_privs, .. } => session_privs,
PendingOutboundPayment::AwaitingOffer { .. } |
PendingOutboundPayment::AwaitingInvoice { .. } |
PendingOutboundPayment::InvoiceReceived { .. } |
PendingOutboundPayment::StaticInvoiceReceived { .. } => { debug_assert!(false); return; },
});
let payment_hash = self.payment_hash();
*self = PendingOutboundPayment::Fulfilled { session_privs, payment_hash, timer_ticks_without_htlcs: 0 };
}
fn mark_abandoned(&mut self, reason: PaymentFailureReason) {
let session_privs = match self {
PendingOutboundPayment::Retryable { session_privs, .. } => {
let mut our_session_privs = new_hash_set();
core::mem::swap(&mut our_session_privs, session_privs);
our_session_privs
},
_ => new_hash_set(),
};
match self {
Self::Retryable { payment_hash, .. } |
Self::InvoiceReceived { payment_hash, .. } |
Self::StaticInvoiceReceived { payment_hash, .. } =>
{
*self = Self::Abandoned {
session_privs,
payment_hash: *payment_hash,
reason: Some(reason),
};
},
_ => {}
}
}
/// panics if path is None and !self.is_fulfilled
fn remove(&mut self, session_priv: &[u8; 32], path: Option<&Path>) -> bool {
let remove_res = match self {
PendingOutboundPayment::Legacy { session_privs } |
PendingOutboundPayment::Retryable { session_privs, .. } |
PendingOutboundPayment::Fulfilled { session_privs, .. } |
PendingOutboundPayment::Abandoned { session_privs, .. } => {
session_privs.remove(session_priv)
},
PendingOutboundPayment::AwaitingOffer { .. } |
PendingOutboundPayment::AwaitingInvoice { .. } |
PendingOutboundPayment::InvoiceReceived { .. } |
PendingOutboundPayment::StaticInvoiceReceived { .. } => { debug_assert!(false); false },
};
if remove_res {
if let PendingOutboundPayment::Retryable {
ref mut pending_amt_msat, ref mut pending_fee_msat,
ref mut remaining_max_total_routing_fee_msat, ..
} = self {
let path = path.expect("Removing a failed payment should always come with a path");
*pending_amt_msat -= path.final_value_msat();
let path_fee_msat = path.fee_msat();
if let Some(fee_msat) = pending_fee_msat.as_mut() {
*fee_msat -= path_fee_msat;
}
if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
*max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_add(path_fee_msat);
}
}
}
remove_res
}
pub(super) fn insert(&mut self, session_priv: [u8; 32], path: &Path) -> bool {
let insert_res = match self {
PendingOutboundPayment::Legacy { session_privs } |
PendingOutboundPayment::Retryable { session_privs, .. } => {
session_privs.insert(session_priv)
},
PendingOutboundPayment::AwaitingOffer { .. } |
PendingOutboundPayment::AwaitingInvoice { .. } |
PendingOutboundPayment::InvoiceReceived { .. } |
PendingOutboundPayment::StaticInvoiceReceived { .. } => { debug_assert!(false); false },
PendingOutboundPayment::Fulfilled { .. } => false,
PendingOutboundPayment::Abandoned { .. } => false,
};
if insert_res {
if let PendingOutboundPayment::Retryable {
ref mut pending_amt_msat, ref mut pending_fee_msat,
ref mut remaining_max_total_routing_fee_msat, ..
} = self {
*pending_amt_msat += path.final_value_msat();
let path_fee_msat = path.fee_msat();
if let Some(fee_msat) = pending_fee_msat.as_mut() {
*fee_msat += path_fee_msat;
}
if let Some(max_total_routing_fee_msat) = remaining_max_total_routing_fee_msat.as_mut() {
*max_total_routing_fee_msat = max_total_routing_fee_msat.saturating_sub(path_fee_msat);
}
}
}
insert_res
}
pub(super) fn remaining_parts(&self) -> usize {
match self {
PendingOutboundPayment::Legacy { session_privs } |
PendingOutboundPayment::Retryable { session_privs, .. } |
PendingOutboundPayment::Fulfilled { session_privs, .. } |
PendingOutboundPayment::Abandoned { session_privs, .. } => {
session_privs.len()
},
PendingOutboundPayment::AwaitingInvoice { .. } => 0,
PendingOutboundPayment::AwaitingOffer { .. } => 0,
PendingOutboundPayment::InvoiceReceived { .. } => 0,
PendingOutboundPayment::StaticInvoiceReceived { .. } => 0,
}
}
}
/// Strategies available to retry payment path failures.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub enum Retry {
/// Max number of attempts to retry payment.
///
/// Each attempt may be multiple HTLCs along multiple paths if the router decides to split up a
/// retry, and may retry multiple failed HTLCs at once if they failed around the same time and
/// were retried along a route from a single call to [`Router::find_route_with_id`].
Attempts(u32),
#[cfg(feature = "std")]
/// Time elapsed before abandoning retries for a payment. At least one attempt at payment is made;
/// see [`PaymentParameters::expiry_time`] to avoid any attempt at payment after a specific time.
///
/// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
Timeout(core::time::Duration),
}
#[cfg(not(feature = "std"))]
impl_writeable_tlv_based_enum_legacy!(Retry,
;
(0, Attempts)
);
#[cfg(feature = "std")]
impl_writeable_tlv_based_enum_legacy!(Retry,
;
(0, Attempts),
(2, Timeout)
);
impl Retry {
pub(crate) fn is_retryable_now(&self, attempts: &PaymentAttempts) -> bool {
match (self, attempts) {
(Retry::Attempts(max_retry_count), PaymentAttempts { count, .. }) => {
max_retry_count > count
},
#[cfg(feature = "std")]
(Retry::Timeout(max_duration), PaymentAttempts { first_attempted_at, .. }) =>
*max_duration >= Instant::now().duration_since(*first_attempted_at),
}
}
}
#[cfg(feature = "std")]
pub(super) fn has_expired(route_params: &RouteParameters) -> bool {
if let Some(expiry_time) = route_params.payment_params.expiry_time {
if let Ok(elapsed) = std::time::SystemTime::UNIX_EPOCH.elapsed() {
return elapsed > core::time::Duration::from_secs(expiry_time)
}
}
false
}
/// Storing minimal payment attempts information required for determining if a outbound payment can
/// be retried.
pub(crate) struct PaymentAttempts {
/// This count will be incremented only after the result of the attempt is known. When it's 0,
/// it means the result of the first attempt is not known yet.
pub(crate) count: u32,
/// This field is only used when retry is `Retry::Timeout` which is only build with feature std
#[cfg(feature = "std")]
first_attempted_at: Instant,
}
impl PaymentAttempts {
pub(crate) fn new() -> Self {
PaymentAttempts {
count: 0,
#[cfg(feature = "std")]
first_attempted_at: Instant::now(),
}
}
}
impl Display for PaymentAttempts {
fn fmt(&self, f: &mut Formatter) -> Result<(), fmt::Error> {
#[cfg(not(feature = "std"))]
return write!(f, "attempts: {}", self.count);
#[cfg(feature = "std")]
return write!(
f,
"attempts: {}, duration: {}s",
self.count,
Instant::now().duration_since(self.first_attempted_at).as_secs()
);
}
}
/// How long before a [`PendingOutboundPayment::AwaitingInvoice`] or
/// [`PendingOutboundPayment::AwaitingOffer`] should be considered stale and candidate for removal
/// in [`OutboundPayments::remove_stale_payments`].
#[derive(Clone, Copy)]
pub(crate) enum StaleExpiration {
/// Number of times [`OutboundPayments::remove_stale_payments`] is called.
TimerTicks(u64),
/// Duration since the Unix epoch.
AbsoluteTimeout(core::time::Duration),
}
impl_writeable_tlv_based_enum_legacy!(StaleExpiration,
;
(0, TimerTicks),
(2, AbsoluteTimeout)
);
/// Indicates an immediate error on [`ChannelManager::send_payment`]. Further errors may be
/// surfaced later via [`Event::PaymentPathFailed`] and [`Event::PaymentFailed`].
///
/// [`ChannelManager::send_payment`]: crate::ln::channelmanager::ChannelManager::send_payment
/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RetryableSendFailure {
/// The provided [`PaymentParameters::expiry_time`] indicated that the payment has expired.
#[cfg_attr(feature = "std", doc = "")]
#[cfg_attr(feature = "std", doc = "Note that this error is *not* caused by [`Retry::Timeout`].")]
///
/// [`PaymentParameters::expiry_time`]: crate::routing::router::PaymentParameters::expiry_time
PaymentExpired,
/// We were unable to find a route to the destination.
RouteNotFound,
/// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
/// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
///
/// [`PaymentId`]: crate::ln::channelmanager::PaymentId
/// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
DuplicatePayment,
/// The [`RecipientOnionFields::payment_metadata`], [`RecipientOnionFields::custom_tlvs`], or
/// [`BlindedPaymentPath`]s provided are too large and caused us to exceed the maximum onion
/// packet size of 1300 bytes.
///
/// [`BlindedPaymentPath`]: crate::blinded_path::payment::BlindedPaymentPath
OnionPacketSizeExceeded,
}
/// If a payment fails to send to a route, it can be in one of several states. This enum is returned
/// as the Err() type describing which state the payment is in, see the description of individual
/// enum states for more.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) enum PaymentSendFailure {
/// A parameter which was passed to send_payment was invalid, preventing us from attempting to
/// send the payment at all.
///
/// You can freely resend the payment in full (with the parameter error fixed).
///
/// Because the payment failed outright, no payment tracking is done and no
/// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
///
/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
ParameterError(APIError),
/// A parameter in a single path which was passed to send_payment was invalid, preventing us
/// from attempting to send the payment at all.
///
/// You can freely resend the payment in full (with the parameter error fixed).
///
/// Because the payment failed outright, no payment tracking is done and no
/// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
///
/// The results here are ordered the same as the paths in the route object which was passed to
/// send_payment.
///
/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
PathParameterError(Vec<Result<(), APIError>>),
/// All paths which were attempted failed to send, with no channel state change taking place.
/// You can freely resend the payment in full (though you probably want to do so over different
/// paths than the ones selected).
///
/// Because the payment failed outright, no payment tracking is done and no
/// [`Event::PaymentPathFailed`] or [`Event::PaymentFailed`] events will be generated.
///
/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
AllFailedResendSafe(Vec<APIError>),
/// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
/// yet completed (i.e. generated an [`Event::PaymentSent`] or [`Event::PaymentFailed`]).
///
/// [`PaymentId`]: crate::ln::channelmanager::PaymentId
/// [`Event::PaymentSent`]: crate::events::Event::PaymentSent
/// [`Event::PaymentFailed`]: crate::events::Event::PaymentFailed
DuplicatePayment,
/// Some paths that were attempted failed to send, though some paths may have succeeded. At least
/// some paths have irrevocably committed to the HTLC.
///
/// The results here are ordered the same as the paths in the route object that was passed to
/// send_payment.
///
/// Any entries that contain `Err(APIError::MonitorUpdateInprogress)` will send once a
/// [`MonitorEvent::Completed`] is provided for the next-hop channel with the latest update_id.
///
/// [`MonitorEvent::Completed`]: crate::chain::channelmonitor::MonitorEvent::Completed
PartialFailure {
/// The errors themselves, in the same order as the paths from the route.
results: Vec<Result<(), APIError>>,
/// If some paths failed without irrevocably committing to the new HTLC(s), this will
/// contain a [`RouteParameters`] object for the failing paths.
failed_paths_retry: Option<RouteParameters>,
/// The payment id for the payment, which is now at least partially pending.
payment_id: PaymentId,
},
}
/// An error when attempting to pay a [`Bolt12Invoice`].
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Bolt12PaymentError {
/// The invoice was not requested.
UnexpectedInvoice,
/// Payment for an invoice with the corresponding [`PaymentId`] was already initiated.
DuplicateInvoice,
/// The invoice was valid for the corresponding [`PaymentId`], but required unknown features.
UnknownRequiredFeatures,
/// The invoice was valid for the corresponding [`PaymentId`], but sending the payment failed.
SendingFailed(RetryableSendFailure),
#[cfg(async_payments)]
/// Failed to create a blinded path back to ourselves.
///
/// We attempted to initiate payment to a [`StaticInvoice`] but failed to create a reply path for
/// our [`HeldHtlcAvailable`] message.
///
/// [`StaticInvoice`]: crate::offers::static_invoice::StaticInvoice
/// [`HeldHtlcAvailable`]: crate::onion_message::async_payments::HeldHtlcAvailable
BlindedPathCreationFailed,
}
/// Indicates that we failed to send a payment probe. Further errors may be surfaced later via
/// [`Event::ProbeFailed`].
///
/// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum ProbeSendFailure {
/// We were unable to find a route to the destination.
RouteNotFound,
/// A parameter which was passed to [`ChannelManager::send_probe`] was invalid, preventing us from
/// attempting to send the probe at all.
///
/// You can freely resend the probe (with the parameter error fixed).
///
/// Because the probe failed outright, no payment tracking is done and no
/// [`Event::ProbeFailed`] events will be generated.
///
/// [`ChannelManager::send_probe`]: crate::ln::channelmanager::ChannelManager::send_probe
/// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
ParameterError(APIError),
/// Indicates that a payment for the provided [`PaymentId`] is already in-flight and has not
/// yet completed (i.e. generated an [`Event::ProbeSuccessful`] or [`Event::ProbeFailed`]).
///
/// [`PaymentId`]: crate::ln::channelmanager::PaymentId
/// [`Event::ProbeSuccessful`]: crate::events::Event::ProbeSuccessful
/// [`Event::ProbeFailed`]: crate::events::Event::ProbeFailed
DuplicateProbe,
}
/// Information which is provided, encrypted, to the payment recipient when sending HTLCs.
///
/// This should generally be constructed with data communicated to us from the recipient (via a
/// BOLT11 or BOLT12 invoice).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RecipientOnionFields {
/// The [`PaymentSecret`] is an arbitrary 32 bytes provided by the recipient for us to repeat
/// in the onion. It is unrelated to `payment_hash` (or [`PaymentPreimage`]) and exists to
/// authenticate the sender to the recipient and prevent payment-probing (deanonymization)
/// attacks.
///
/// If you do not have one, the [`Route`] you pay over must not contain multiple paths as
/// multi-path payments require a recipient-provided secret.
///
/// Some implementations may reject spontaneous payments with payment secrets, so you may only
/// want to provide a secret for a spontaneous payment if MPP is needed and you know your
/// recipient will not reject it.
pub payment_secret: Option<PaymentSecret>,
/// The payment metadata serves a similar purpose as [`Self::payment_secret`] but is of
/// arbitrary length. This gives recipients substantially more flexibility to receive
/// additional data.
///
/// In LDK, while the [`Self::payment_secret`] is fixed based on an internal authentication
/// scheme to authenticate received payments against expected payments and invoices, this field
/// is not used in LDK for received payments, and can be used to store arbitrary data in
/// invoices which will be received with the payment.
///
/// Note that this field was added to the lightning specification more recently than
/// [`Self::payment_secret`] and while nearly all lightning senders support secrets, metadata
/// may not be supported as universally.
pub payment_metadata: Option<Vec<u8>>,
/// See [`Self::custom_tlvs`] for more info.
pub(super) custom_tlvs: Vec<(u64, Vec<u8>)>,
}
impl_writeable_tlv_based!(RecipientOnionFields, {
(0, payment_secret, option),
(1, custom_tlvs, optional_vec),
(2, payment_metadata, option),
});
impl RecipientOnionFields {
/// Creates a [`RecipientOnionFields`] from only a [`PaymentSecret`]. This is the most common
/// set of onion fields for today's BOLT11 invoices - most nodes require a [`PaymentSecret`]
/// but do not require or provide any further data.
pub fn secret_only(payment_secret: PaymentSecret) -> Self {
Self { payment_secret: Some(payment_secret), payment_metadata: None, custom_tlvs: Vec::new() }
}
/// Creates a new [`RecipientOnionFields`] with no fields. This generally does not create
/// payable HTLCs except for single-path spontaneous payments, i.e. this should generally
/// only be used for calls to [`ChannelManager::send_spontaneous_payment`]. If you are sending
/// a spontaneous MPP this will not work as all MPP require payment secrets; you may
/// instead want to use [`RecipientOnionFields::secret_only`].
///
/// [`ChannelManager::send_spontaneous_payment`]: super::channelmanager::ChannelManager::send_spontaneous_payment
/// [`RecipientOnionFields::secret_only`]: RecipientOnionFields::secret_only
pub fn spontaneous_empty() -> Self {
Self { payment_secret: None, payment_metadata: None, custom_tlvs: Vec::new() }
}
/// Creates a new [`RecipientOnionFields`] from an existing one, adding custom TLVs. Each
/// TLV is provided as a `(u64, Vec<u8>)` for the type number and serialized value
/// respectively. TLV type numbers must be unique and within the range
/// reserved for custom types, i.e. >= 2^16, otherwise this method will return `Err(())`.
///
/// This method will also error for types in the experimental range which have been
/// standardized within the protocol, which only includes 5482373484 (keysend) for now.
///
/// See [`Self::custom_tlvs`] for more info.
pub fn with_custom_tlvs(mut self, mut custom_tlvs: Vec<(u64, Vec<u8>)>) -> Result<Self, ()> {
custom_tlvs.sort_unstable_by_key(|(typ, _)| *typ);
let mut prev_type = None;
for (typ, _) in custom_tlvs.iter() {
if *typ < 1 << 16 { return Err(()); }
if *typ == 5482373484 { return Err(()); } // keysend
if *typ == 77_777 { return Err(()); } // invoice requests for async payments
match prev_type {
Some(prev) if prev >= *typ => return Err(()),
_ => {},
}
prev_type = Some(*typ);
}
self.custom_tlvs = custom_tlvs;
Ok(self)
}
/// Gets the custom TLVs that will be sent or have been received.
///
/// Custom TLVs allow sending extra application-specific data with a payment. They provide
/// additional flexibility on top of payment metadata, as while other implementations may
/// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
/// do not have this restriction.
///
/// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
/// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
/// This is validated when setting this field using [`Self::with_custom_tlvs`].
#[cfg(not(c_bindings))]
pub fn custom_tlvs(&self) -> &Vec<(u64, Vec<u8>)> {
&self.custom_tlvs
}
/// Gets the custom TLVs that will be sent or have been received.
///
/// Custom TLVs allow sending extra application-specific data with a payment. They provide
/// additional flexibility on top of payment metadata, as while other implementations may
/// require `payment_metadata` to reflect metadata provided in an invoice, custom TLVs
/// do not have this restriction.
///
/// Note that if this field is non-empty, it will contain strictly increasing TLVs, each
/// represented by a `(u64, Vec<u8>)` for its type number and serialized value respectively.
/// This is validated when setting this field using [`Self::with_custom_tlvs`].
#[cfg(c_bindings)]
pub fn custom_tlvs(&self) -> Vec<(u64, Vec<u8>)> {
self.custom_tlvs.clone()
}
/// When we have received some HTLC(s) towards an MPP payment, as we receive further HTLC(s) we
/// have to make sure that some fields match exactly across the parts. For those that aren't
/// required to match, if they don't match we should remove them so as to not expose data
/// that's dependent on the HTLC receive order to users.
///
/// Here we implement this, first checking compatibility then mutating two objects and then
/// dropping any remaining non-matching fields from both.
pub(super) fn check_merge(&mut self, further_htlc_fields: &mut Self) -> Result<(), ()> {
if self.payment_secret != further_htlc_fields.payment_secret { return Err(()); }
if self.payment_metadata != further_htlc_fields.payment_metadata { return Err(()); }
let tlvs = &mut self.custom_tlvs;
let further_tlvs = &mut further_htlc_fields.custom_tlvs;
let even_tlvs = tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
let further_even_tlvs = further_tlvs.iter().filter(|(typ, _)| *typ % 2 == 0);
if even_tlvs.ne(further_even_tlvs) { return Err(()) }
tlvs.retain(|tlv| further_tlvs.iter().any(|further_tlv| tlv == further_tlv));
further_tlvs.retain(|further_tlv| tlvs.iter().any(|tlv| tlv == further_tlv));
Ok(())
}
}
/// Arguments for [`super::channelmanager::ChannelManager::send_payment_along_path`].
pub(super) struct SendAlongPathArgs<'a> {
pub path: &'a Path,
pub payment_hash: &'a PaymentHash,
pub recipient_onion: &'a RecipientOnionFields,
pub total_value: u64,
pub cur_height: u32,
pub payment_id: PaymentId,
pub keysend_preimage: &'a Option<PaymentPreimage>,
pub invoice_request: Option<&'a InvoiceRequest>,
pub session_priv_bytes: [u8; 32],
}
pub(super) struct OutboundPayments {
pub(super) pending_outbound_payments: Mutex<HashMap<PaymentId, PendingOutboundPayment>>,
awaiting_invoice: AtomicBool,
retry_lock: Mutex<()>,
}
impl OutboundPayments {
pub(super) fn new(pending_outbound_payments: HashMap<PaymentId, PendingOutboundPayment>) -> Self {
let has_invoice_requests = pending_outbound_payments.values().any(|payment| {
matches!(payment, PendingOutboundPayment::AwaitingInvoice { retryable_invoice_request: Some(_), .. })
});
Self {
pending_outbound_payments: Mutex::new(pending_outbound_payments),
awaiting_invoice: AtomicBool::new(has_invoice_requests),
retry_lock: Mutex::new(()),
}
}
pub(super) fn send_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
&self, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields, payment_id: PaymentId,
retry_strategy: Retry, route_params: RouteParameters, router: &R,
first_hops: Vec<ChannelDetails>, compute_inflight_htlcs: IH, entropy_source: &ES,
node_signer: &NS, best_block_height: u32, logger: &L,
pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP,
) -> Result<(), RetryableSendFailure>
where
R::Target: Router,
ES::Target: EntropySource,
NS::Target: NodeSigner,
L::Target: Logger,
IH: Fn() -> InFlightHtlcs,
SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
{
self.send_payment_internal(payment_id, payment_hash, recipient_onion, None, retry_strategy,
route_params, router, first_hops, &compute_inflight_htlcs, entropy_source, node_signer,
best_block_height, logger, pending_events, &send_payment_along_path)
}
#[cfg(test)]
pub(super) fn send_payment_with_route<ES: Deref, NS: Deref, F>(
&self, route: &Route, payment_hash: PaymentHash, recipient_onion: RecipientOnionFields,
payment_id: PaymentId, entropy_source: &ES, node_signer: &NS, best_block_height: u32,
send_payment_along_path: F
) -> Result<(), PaymentSendFailure>
where
ES::Target: EntropySource,
NS::Target: NodeSigner,
F: Fn(SendAlongPathArgs) -> Result<(), APIError>
{
let onion_session_privs = self.add_new_pending_payment(payment_hash, recipient_onion.clone(), payment_id, None, route, None, None, entropy_source, best_block_height)?;
self.pay_route_internal(route, payment_hash, &recipient_onion, None, None, payment_id, None,
onion_session_privs, node_signer, best_block_height, &send_payment_along_path)
.map_err(|e| { self.remove_outbound_if_all_failed(payment_id, &e); e })
}
pub(super) fn send_spontaneous_payment<R: Deref, ES: Deref, NS: Deref, IH, SP, L: Deref>(
&self, payment_preimage: Option<PaymentPreimage>, recipient_onion: RecipientOnionFields,
payment_id: PaymentId, retry_strategy: Retry, route_params: RouteParameters, router: &R,
first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES,
node_signer: &NS, best_block_height: u32, logger: &L,
pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>, send_payment_along_path: SP
) -> Result<PaymentHash, RetryableSendFailure>
where
R::Target: Router,
ES::Target: EntropySource,
NS::Target: NodeSigner,
L::Target: Logger,
IH: Fn() -> InFlightHtlcs,
SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
{
let preimage = payment_preimage
.unwrap_or_else(|| PaymentPreimage(entropy_source.get_secure_random_bytes()));
let payment_hash = PaymentHash(Sha256::hash(&preimage.0).to_byte_array());
self.send_payment_internal(payment_id, payment_hash, recipient_onion, Some(preimage),
retry_strategy, route_params, router, first_hops, inflight_htlcs, entropy_source,
node_signer, best_block_height, logger, pending_events, send_payment_along_path)
.map(|()| payment_hash)
}
pub(super) fn send_payment_for_bolt12_invoice<
R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref
>(
&self, invoice: &Bolt12Invoice, payment_id: PaymentId, router: &R,
first_hops: Vec<ChannelDetails>, features: Bolt12InvoiceFeatures, inflight_htlcs: IH,
entropy_source: &ES, node_signer: &NS, node_id_lookup: &NL,
secp_ctx: &Secp256k1<secp256k1::All>, best_block_height: u32, logger: &L,
pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
send_payment_along_path: SP,
) -> Result<(), Bolt12PaymentError>
where
R::Target: Router,
ES::Target: EntropySource,
NS::Target: NodeSigner,
NL::Target: NodeIdLookUp,
L::Target: Logger,
IH: Fn() -> InFlightHtlcs,
SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
{
let payment_hash = invoice.payment_hash();
let max_total_routing_fee_msat;
let retry_strategy;
match self.pending_outbound_payments.lock().unwrap().entry(payment_id) {
hash_map::Entry::Occupied(entry) => match entry.get() {
PendingOutboundPayment::AwaitingInvoice {
retry_strategy: retry, max_total_routing_fee_msat: max_total_fee, ..
} => {
retry_strategy = *retry;
max_total_routing_fee_msat = *max_total_fee;
*entry.into_mut() = PendingOutboundPayment::InvoiceReceived {
payment_hash,
retry_strategy: *retry,
max_total_routing_fee_msat,
};
},
_ => return Err(Bolt12PaymentError::DuplicateInvoice),
},
hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
}
if invoice.invoice_features().requires_unknown_bits_from(&features) {
self.abandon_payment(
payment_id, PaymentFailureReason::UnknownRequiredFeatures, pending_events,
);
return Err(Bolt12PaymentError::UnknownRequiredFeatures);
}
let mut route_params = RouteParameters::from_payment_params_and_value(
PaymentParameters::from_bolt12_invoice(&invoice), invoice.amount_msats()
);
if let Some(max_fee_msat) = max_total_routing_fee_msat {
route_params.max_total_routing_fee_msat = Some(max_fee_msat);
}
self.send_payment_for_bolt12_invoice_internal(
payment_id, payment_hash, None, None, route_params, retry_strategy, router, first_hops,
inflight_htlcs, entropy_source, node_signer, node_id_lookup, secp_ctx, best_block_height,
logger, pending_events, send_payment_along_path
)
}
fn send_payment_for_bolt12_invoice_internal<
R: Deref, ES: Deref, NS: Deref, NL: Deref, IH, SP, L: Deref
>(
&self, payment_id: PaymentId, payment_hash: PaymentHash,
keysend_preimage: Option<PaymentPreimage>, invoice_request: Option<&InvoiceRequest>,
mut route_params: RouteParameters, retry_strategy: Retry, router: &R,
first_hops: Vec<ChannelDetails>, inflight_htlcs: IH, entropy_source: &ES, node_signer: &NS,
node_id_lookup: &NL, secp_ctx: &Secp256k1<secp256k1::All>, best_block_height: u32, logger: &L,
pending_events: &Mutex<VecDeque<(events::Event, Option<EventCompletionAction>)>>,
send_payment_along_path: SP,
) -> Result<(), Bolt12PaymentError>
where
R::Target: Router,
ES::Target: EntropySource,
NS::Target: NodeSigner,
NL::Target: NodeIdLookUp,
L::Target: Logger,
IH: Fn() -> InFlightHtlcs,
SP: Fn(SendAlongPathArgs) -> Result<(), APIError>,
{
// Advance any blinded path where the introduction node is our node.
if let Ok(our_node_id) = node_signer.get_node_id(Recipient::Node) {
for path in route_params.payment_params.payee.blinded_route_hints_mut().iter_mut() {
let introduction_node_id = match path.introduction_node() {
IntroductionNode::NodeId(pubkey) => *pubkey,
IntroductionNode::DirectedShortChannelId(direction, scid) => {
match node_id_lookup.next_node_id(*scid) {
Some(next_node_id) => *direction.select_pubkey(&our_node_id, &next_node_id),
None => continue,
}
},
};
if introduction_node_id == our_node_id {
let _ = path.advance_path_by_one(node_signer, node_id_lookup, secp_ctx);
}
}
}
let recipient_onion = RecipientOnionFields {
payment_secret: None,
payment_metadata: None,
custom_tlvs: vec![],
};
let route = match self.find_initial_route(
payment_id, payment_hash, &recipient_onion, keysend_preimage, invoice_request,
&mut route_params, router, &first_hops, &inflight_htlcs, node_signer, best_block_height,
logger,
) {
Ok(route) => route,
Err(e) => {
let reason = match e {
RetryableSendFailure::PaymentExpired => PaymentFailureReason::PaymentExpired,
RetryableSendFailure::RouteNotFound => PaymentFailureReason::RouteNotFound,
RetryableSendFailure::DuplicatePayment => PaymentFailureReason::UnexpectedError,
RetryableSendFailure::OnionPacketSizeExceeded => PaymentFailureReason::UnexpectedError,
};
self.abandon_payment(payment_id, reason, pending_events);
return Err(Bolt12PaymentError::SendingFailed(e));
},
};
let payment_params = Some(route_params.payment_params.clone());
let mut outbounds = self.pending_outbound_payments.lock().unwrap();
let onion_session_privs = match outbounds.entry(payment_id) {
hash_map::Entry::Occupied(entry) => match entry.get() {
PendingOutboundPayment::InvoiceReceived { .. } => {
let (retryable_payment, onion_session_privs) = Self::create_pending_payment(
payment_hash, recipient_onion.clone(), keysend_preimage, None, &route,
Some(retry_strategy), payment_params, entropy_source, best_block_height
);
*entry.into_mut() = retryable_payment;
onion_session_privs
},
PendingOutboundPayment::StaticInvoiceReceived { .. } => {
let invreq = if let PendingOutboundPayment::StaticInvoiceReceived { invoice_request, .. } = entry.remove() {
invoice_request
} else { unreachable!() };
let (retryable_payment, onion_session_privs) = Self::create_pending_payment(
payment_hash, recipient_onion.clone(), keysend_preimage, Some(invreq), &route,
Some(retry_strategy), payment_params, entropy_source, best_block_height
);
outbounds.insert(payment_id, retryable_payment);
onion_session_privs
},
_ => return Err(Bolt12PaymentError::DuplicateInvoice),
},
hash_map::Entry::Vacant(_) => return Err(Bolt12PaymentError::UnexpectedInvoice),
};
core::mem::drop(outbounds);
let result = self.pay_route_internal(
&route, payment_hash, &recipient_onion, keysend_preimage, invoice_request, payment_id,
Some(route_params.final_value_msat), onion_session_privs, node_signer, best_block_height,
&send_payment_along_path
);
log_info!(
logger, "Sending payment with id {} and hash {} returned {:?}", payment_id,
payment_hash, result
);
if let Err(e) = result {
self.handle_pay_route_err(
e, payment_id, payment_hash, route, route_params, router, first_hops,
&inflight_htlcs, entropy_source, node_signer, best_block_height, logger,
pending_events, &send_payment_along_path
);
}
Ok(())