-
Notifications
You must be signed in to change notification settings - Fork 385
/
Copy pathrouter.rs
8964 lines (8210 loc) · 379 KB
/
router.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.
//! The router finds paths within a [`NetworkGraph`] for a payment.
use bitcoin::secp256k1::{PublicKey, Secp256k1, self};
use crate::blinded_path::{BlindedHop, Direction, IntroductionNode};
use crate::blinded_path::payment::{BlindedPaymentPath, ForwardTlvs, PaymentConstraints, PaymentForwardNode, PaymentRelay, ReceiveTlvs};
use crate::types::payment::{PaymentHash, PaymentPreimage};
use crate::ln::channel_state::ChannelDetails;
use crate::ln::channelmanager::{PaymentId, MIN_FINAL_CLTV_EXPIRY_DELTA, RecipientOnionFields};
use crate::types::features::{BlindedHopFeatures, Bolt11InvoiceFeatures, Bolt12InvoiceFeatures, ChannelFeatures, NodeFeatures};
use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
use crate::ln::onion_utils;
#[cfg(async_payments)]
use crate::offers::static_invoice::StaticInvoice;
use crate::offers::invoice::Bolt12Invoice;
use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId};
use crate::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp};
use crate::sign::EntropySource;
use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
use crate::util::logger::{Level, Logger};
use crate::crypto::chacha20::ChaCha20;
use crate::io;
use crate::prelude::*;
use alloc::collections::BinaryHeap;
use core::{cmp, fmt};
use core::ops::Deref;
use lightning_types::routing::RoutingFees;
pub use lightning_types::routing::{RouteHint, RouteHintHop};
/// A [`Router`] implemented using [`find_route`].
///
/// # Privacy
///
/// Creating [`BlindedPaymentPath`]s may affect privacy since, if a suitable path cannot be found,
/// it will create a one-hop path using the recipient as the introduction node if it is a announced
/// node. Otherwise, there is no way to find a path to the introduction node in order to send a
/// payment, and thus an `Err` is returned.
pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
ES::Target: EntropySource,
{
network_graph: G,
logger: L,
entropy_source: ES,
scorer: S,
score_params: SP,
}
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> DefaultRouter<G, L, ES, S, SP, Sc> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
ES::Target: EntropySource,
{
/// Creates a new router.
pub fn new(network_graph: G, logger: L, entropy_source: ES, scorer: S, score_params: SP) -> Self {
Self { network_graph, logger, entropy_source, scorer, score_params }
}
}
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, ES: Deref, S: Deref, SP: Sized, Sc: ScoreLookUp<ScoreParams = SP>> Router for DefaultRouter<G, L, ES, S, SP, Sc> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a, ScoreLookUp = Sc>,
ES::Target: EntropySource,
{
fn find_route(
&self,
payer: &PublicKey,
params: &RouteParameters,
first_hops: Option<&[&ChannelDetails]>,
inflight_htlcs: InFlightHtlcs
) -> Result<Route, LightningError> {
let random_seed_bytes = self.entropy_source.get_secure_random_bytes();
find_route(
payer, params, &self.network_graph, first_hops, &*self.logger,
&ScorerAccountingForInFlightHtlcs::new(self.scorer.read_lock(), &inflight_htlcs),
&self.score_params,
&random_seed_bytes
)
}
fn create_blinded_payment_paths<
T: secp256k1::Signing + secp256k1::Verification
> (
&self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
amount_msats: u64, secp_ctx: &Secp256k1<T>
) -> Result<Vec<BlindedPaymentPath>, ()> {
// Limit the number of blinded paths that are computed.
const MAX_PAYMENT_PATHS: usize = 3;
// Ensure peers have at least three channels so that it is more difficult to infer the
// recipient's node_id.
const MIN_PEER_CHANNELS: usize = 3;
let has_one_peer = first_hops
.first()
.map(|details| details.counterparty.node_id)
.map(|node_id| first_hops
.iter()
.skip(1)
.all(|details| details.counterparty.node_id == node_id)
)
.unwrap_or(false);
let network_graph = self.network_graph.deref().read_only();
let is_recipient_announced =
network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient));
let paths = first_hops.into_iter()
.filter(|details| details.counterparty.features.supports_route_blinding())
.filter(|details| amount_msats <= details.inbound_capacity_msat)
.filter(|details| amount_msats >= details.inbound_htlc_minimum_msat.unwrap_or(0))
.filter(|details| amount_msats <= details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX))
// Limit to peers with announced channels unless the recipient is unannounced.
.filter(|details| network_graph
.node(&NodeId::from_pubkey(&details.counterparty.node_id))
.map(|node| !is_recipient_announced || node.channels.len() >= MIN_PEER_CHANNELS)
// Allow payments directly with the only peer when unannounced.
.unwrap_or(!is_recipient_announced && has_one_peer)
)
.filter_map(|details| {
let short_channel_id = match details.get_inbound_payment_scid() {
Some(short_channel_id) => short_channel_id,
None => return None,
};
let payment_relay: PaymentRelay = match details.counterparty.forwarding_info {
Some(forwarding_info) => match forwarding_info.try_into() {
Ok(payment_relay) => payment_relay,
Err(()) => return None,
},
None => return None,
};
let cltv_expiry_delta = payment_relay.cltv_expiry_delta as u32;
let payment_constraints = PaymentConstraints {
max_cltv_expiry: tlvs.tlvs().payment_constraints.max_cltv_expiry + cltv_expiry_delta,
htlc_minimum_msat: details.inbound_htlc_minimum_msat.unwrap_or(0),
};
Some(PaymentForwardNode {
tlvs: ForwardTlvs {
short_channel_id,
payment_relay,
payment_constraints,
next_blinding_override: None,
features: BlindedHopFeatures::empty(),
},
node_id: details.counterparty.node_id,
htlc_maximum_msat: details.inbound_htlc_maximum_msat.unwrap_or(u64::MAX),
})
})
.map(|forward_node| {
BlindedPaymentPath::new(
&[forward_node], recipient, tlvs.clone(), u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA,
&*self.entropy_source, secp_ctx
)
})
.take(MAX_PAYMENT_PATHS)
.collect::<Result<Vec<_>, _>>();
match paths {
Ok(paths) if !paths.is_empty() => Ok(paths),
_ => {
if network_graph.nodes().contains_key(&NodeId::from_pubkey(&recipient)) {
BlindedPaymentPath::new(
&[], recipient, tlvs, u64::MAX, MIN_FINAL_CLTV_EXPIRY_DELTA, &*self.entropy_source,
secp_ctx
).map(|path| vec![path])
} else {
Err(())
}
},
}
}
}
/// A trait defining behavior for routing a payment.
pub trait Router {
/// Finds a [`Route`] for a payment between the given `payer` and a payee.
///
/// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
/// and [`RouteParameters::final_value_msat`], respectively.
fn find_route(
&self, payer: &PublicKey, route_params: &RouteParameters,
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
) -> Result<Route, LightningError>;
/// Finds a [`Route`] for a payment between the given `payer` and a payee.
///
/// The `payee` and the payment's value are given in [`RouteParameters::payment_params`]
/// and [`RouteParameters::final_value_msat`], respectively.
///
/// Includes a [`PaymentHash`] and a [`PaymentId`] to be able to correlate the request with a specific
/// payment.
fn find_route_with_id(
&self, payer: &PublicKey, route_params: &RouteParameters,
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs,
_payment_hash: PaymentHash, _payment_id: PaymentId
) -> Result<Route, LightningError> {
self.find_route(payer, route_params, first_hops, inflight_htlcs)
}
/// Creates [`BlindedPaymentPath`]s for payment to the `recipient` node. The channels in `first_hops`
/// are assumed to be with the `recipient`'s peers. The payment secret and any constraints are
/// given in `tlvs`.
fn create_blinded_payment_paths<
T: secp256k1::Signing + secp256k1::Verification
> (
&self, recipient: PublicKey, first_hops: Vec<ChannelDetails>, tlvs: ReceiveTlvs,
amount_msats: u64, secp_ctx: &Secp256k1<T>
) -> Result<Vec<BlindedPaymentPath>, ()>;
}
/// [`ScoreLookUp`] implementation that factors in in-flight HTLC liquidity.
///
/// Useful for custom [`Router`] implementations to wrap their [`ScoreLookUp`] on-the-fly when calling
/// [`find_route`].
///
/// [`ScoreLookUp`]: crate::routing::scoring::ScoreLookUp
pub struct ScorerAccountingForInFlightHtlcs<'a, S: Deref> where S::Target: ScoreLookUp {
scorer: S,
// Maps a channel's short channel id and its direction to the liquidity used up.
inflight_htlcs: &'a InFlightHtlcs,
}
impl<'a, S: Deref> ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
/// Initialize a new `ScorerAccountingForInFlightHtlcs`.
pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
ScorerAccountingForInFlightHtlcs {
scorer,
inflight_htlcs
}
}
}
impl<'a, S: Deref> ScoreLookUp for ScorerAccountingForInFlightHtlcs<'a, S> where S::Target: ScoreLookUp {
type ScoreParams = <S::Target as ScoreLookUp>::ScoreParams;
fn channel_penalty_msat(&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams) -> u64 {
let target = match candidate.target() {
Some(target) => target,
None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
};
let short_channel_id = match candidate.short_channel_id() {
Some(short_channel_id) => short_channel_id,
None => return self.scorer.channel_penalty_msat(candidate, usage, score_params),
};
let source = candidate.source();
if let Some(used_liquidity) = self.inflight_htlcs.used_liquidity_msat(
&source, &target, short_channel_id
) {
let usage = ChannelUsage {
inflight_htlc_msat: usage.inflight_htlc_msat.saturating_add(used_liquidity),
..usage
};
self.scorer.channel_penalty_msat(candidate, usage, score_params)
} else {
self.scorer.channel_penalty_msat(candidate, usage, score_params)
}
}
}
/// A data structure for tracking in-flight HTLCs. May be used during pathfinding to account for
/// in-use channel liquidity.
#[derive(Clone)]
pub struct InFlightHtlcs(
// A map with liquidity value (in msat) keyed by a short channel id and the direction the HTLC
// is traveling in. The direction boolean is determined by checking if the HTLC source's public
// key is less than its destination. See `InFlightHtlcs::used_liquidity_msat` for more
// details.
HashMap<(u64, bool), u64>
);
impl InFlightHtlcs {
/// Constructs an empty `InFlightHtlcs`.
pub fn new() -> Self { InFlightHtlcs(new_hash_map()) }
/// Takes in a path with payer's node id and adds the path's details to `InFlightHtlcs`.
pub fn process_path(&mut self, path: &Path, payer_node_id: PublicKey) {
if path.hops.is_empty() { return };
let mut cumulative_msat = 0;
if let Some(tail) = &path.blinded_tail {
cumulative_msat += tail.final_value_msat;
}
// total_inflight_map needs to be direction-sensitive when keeping track of the HTLC value
// that is held up. However, the `hops` array, which is a path returned by `find_route` in
// the router excludes the payer node. In the following lines, the payer's information is
// hardcoded with an inflight value of 0 so that we can correctly represent the first hop
// in our sliding window of two.
let reversed_hops_with_payer = path.hops.iter().rev().skip(1)
.map(|hop| hop.pubkey)
.chain(core::iter::once(payer_node_id));
// Taking the reversed vector from above, we zip it with just the reversed hops list to
// work "backwards" of the given path, since the last hop's `fee_msat` actually represents
// the total amount sent.
for (next_hop, prev_hop) in path.hops.iter().rev().zip(reversed_hops_with_payer) {
cumulative_msat += next_hop.fee_msat;
self.0
.entry((next_hop.short_channel_id, NodeId::from_pubkey(&prev_hop) < NodeId::from_pubkey(&next_hop.pubkey)))
.and_modify(|used_liquidity_msat| *used_liquidity_msat += cumulative_msat)
.or_insert(cumulative_msat);
}
}
/// Adds a known HTLC given the public key of the HTLC source, target, and short channel
/// id.
pub fn add_inflight_htlc(&mut self, source: &NodeId, target: &NodeId, channel_scid: u64, used_msat: u64){
self.0
.entry((channel_scid, source < target))
.and_modify(|used_liquidity_msat| *used_liquidity_msat += used_msat)
.or_insert(used_msat);
}
/// Returns liquidity in msat given the public key of the HTLC source, target, and short channel
/// id.
pub fn used_liquidity_msat(&self, source: &NodeId, target: &NodeId, channel_scid: u64) -> Option<u64> {
self.0.get(&(channel_scid, source < target)).map(|v| *v)
}
}
impl Writeable for InFlightHtlcs {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.0.write(writer) }
}
impl Readable for InFlightHtlcs {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let infight_map: HashMap<(u64, bool), u64> = Readable::read(reader)?;
Ok(Self(infight_map))
}
}
/// A hop in a route, and additional metadata about it. "Hop" is defined as a node and the channel
/// that leads to it.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct RouteHop {
/// The node_id of the node at this hop.
pub pubkey: PublicKey,
/// The node_announcement features of the node at this hop. For the last hop, these may be
/// amended to match the features present in the invoice this node generated.
pub node_features: NodeFeatures,
/// The channel that should be used from the previous hop to reach this node.
pub short_channel_id: u64,
/// The channel_announcement features of the channel that should be used from the previous hop
/// to reach this node.
pub channel_features: ChannelFeatures,
/// The fee taken on this hop (for paying for the use of the *next* channel in the path).
/// If this is the last hop in [`Path::hops`]:
/// * if we're sending to a [`BlindedPaymentPath`], this is the fee paid for use of the entire
/// blinded path
/// * otherwise, this is the full value of this [`Path`]'s part of the payment
pub fee_msat: u64,
/// The CLTV delta added for this hop.
/// If this is the last hop in [`Path::hops`]:
/// * if we're sending to a [`BlindedPaymentPath`], this is the CLTV delta for the entire blinded
/// path
/// * otherwise, this is the CLTV delta expected at the destination
pub cltv_expiry_delta: u32,
/// Indicates whether this hop is possibly announced in the public network graph.
///
/// Will be `true` if there is a possibility that the channel is publicly known, i.e., if we
/// either know for sure it's announced in the public graph, or if any public channels exist
/// for which the given `short_channel_id` could be an alias for. Will be `false` if we believe
/// the channel to be unannounced.
///
/// Will be `true` for objects serialized with LDK version 0.0.116 and before.
pub maybe_announced_channel: bool,
}
impl_writeable_tlv_based!(RouteHop, {
(0, pubkey, required),
(1, maybe_announced_channel, (default_value, true)),
(2, node_features, required),
(4, short_channel_id, required),
(6, channel_features, required),
(8, fee_msat, required),
(10, cltv_expiry_delta, required),
});
/// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
/// their [`Bolt12Invoice`].
///
/// [`Bolt12Invoice`]: crate::offers::invoice::Bolt12Invoice
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct BlindedTail {
/// The hops of the [`BlindedPaymentPath`] provided by the recipient.
pub hops: Vec<BlindedHop>,
/// The blinding point of the [`BlindedPaymentPath`] provided by the recipient.
pub blinding_point: PublicKey,
/// Excess CLTV delta added to the recipient's CLTV expiry to deter intermediate nodes from
/// inferring the destination. May be 0.
pub excess_final_cltv_expiry_delta: u32,
/// The total amount paid on this [`Path`], excluding the fees.
pub final_value_msat: u64,
}
impl_writeable_tlv_based!(BlindedTail, {
(0, hops, required_vec),
(2, blinding_point, required),
(4, excess_final_cltv_expiry_delta, required),
(6, final_value_msat, required),
});
/// A path in a [`Route`] to the payment recipient. Must always be at least length one.
/// If no [`Path::blinded_tail`] is present, then [`Path::hops`] length may be up to 19.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Path {
/// The list of unblinded hops in this [`Path`]. Must be at least length one.
pub hops: Vec<RouteHop>,
/// The blinded path at which this path terminates, if we're sending to one, and its metadata.
pub blinded_tail: Option<BlindedTail>,
}
impl Path {
/// Gets the fees for a given path, excluding any excess paid to the recipient.
pub fn fee_msat(&self) -> u64 {
match &self.blinded_tail {
Some(_) => self.hops.iter().map(|hop| hop.fee_msat).sum::<u64>(),
None => {
// Do not count last hop of each path since that's the full value of the payment
self.hops.split_last().map_or(0,
|(_, path_prefix)| path_prefix.iter().map(|hop| hop.fee_msat).sum())
}
}
}
/// Gets the total amount paid on this [`Path`], excluding the fees.
pub fn final_value_msat(&self) -> u64 {
match &self.blinded_tail {
Some(blinded_tail) => blinded_tail.final_value_msat,
None => self.hops.last().map_or(0, |hop| hop.fee_msat)
}
}
/// Gets the final hop's CLTV expiry delta.
pub fn final_cltv_expiry_delta(&self) -> Option<u32> {
match &self.blinded_tail {
Some(_) => None,
None => self.hops.last().map(|hop| hop.cltv_expiry_delta)
}
}
}
/// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
/// it can take multiple paths. Each path is composed of one or more hops through the network.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct Route {
/// The list of [`Path`]s taken for a single (potentially-)multi-part payment. If no
/// [`BlindedTail`]s are present, then the pubkey of the last [`RouteHop`] in each path must be
/// the same.
pub paths: Vec<Path>,
/// The `route_params` parameter passed to [`find_route`].
///
/// This is used by `ChannelManager` to track information which may be required for retries.
///
/// Will be `None` for objects serialized with LDK versions prior to 0.0.117.
pub route_params: Option<RouteParameters>,
}
impl Route {
/// Returns the total amount of fees paid on this [`Route`].
///
/// For objects serialized with LDK 0.0.117 and after, this includes any extra payment made to
/// the recipient, which can happen in excess of the amount passed to [`find_route`] via
/// [`RouteParameters::final_value_msat`], if we had to reach the [`htlc_minimum_msat`] limits.
///
/// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
pub fn get_total_fees(&self) -> u64 {
let overpaid_value_msat = self.route_params.as_ref()
.map_or(0, |p| self.get_total_amount().saturating_sub(p.final_value_msat));
overpaid_value_msat + self.paths.iter().map(|path| path.fee_msat()).sum::<u64>()
}
/// Returns the total amount paid on this [`Route`], excluding the fees.
///
/// Might be more than requested as part of the given [`RouteParameters::final_value_msat`] if
/// we had to reach the [`htlc_minimum_msat`] limits.
///
/// [`htlc_minimum_msat`]: https://github.com/lightning/bolts/blob/master/07-routing-gossip.md#the-channel_update-message
pub fn get_total_amount(&self) -> u64 {
self.paths.iter().map(|path| path.final_value_msat()).sum()
}
}
impl fmt::Display for Route {
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
log_route!(self).fmt(f)
}
}
const SERIALIZATION_VERSION: u8 = 1;
const MIN_SERIALIZATION_VERSION: u8 = 1;
impl Writeable for Route {
fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_ver_prefix!(writer, SERIALIZATION_VERSION, MIN_SERIALIZATION_VERSION);
(self.paths.len() as u64).write(writer)?;
let mut blinded_tails = Vec::new();
for (idx, path) in self.paths.iter().enumerate() {
(path.hops.len() as u8).write(writer)?;
for hop in path.hops.iter() {
hop.write(writer)?;
}
if let Some(blinded_tail) = &path.blinded_tail {
if blinded_tails.is_empty() {
blinded_tails = Vec::with_capacity(path.hops.len());
for _ in 0..idx {
blinded_tails.push(None);
}
}
blinded_tails.push(Some(blinded_tail));
} else if !blinded_tails.is_empty() { blinded_tails.push(None); }
}
write_tlv_fields!(writer, {
// For compatibility with LDK versions prior to 0.0.117, we take the individual
// RouteParameters' fields and reconstruct them on read.
(1, self.route_params.as_ref().map(|p| &p.payment_params), option),
(2, blinded_tails, optional_vec),
(3, self.route_params.as_ref().map(|p| p.final_value_msat), option),
(5, self.route_params.as_ref().and_then(|p| p.max_total_routing_fee_msat), option),
});
Ok(())
}
}
impl Readable for Route {
fn read<R: io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
let _ver = read_ver_prefix!(reader, SERIALIZATION_VERSION);
let path_count: u64 = Readable::read(reader)?;
if path_count == 0 { return Err(DecodeError::InvalidValue); }
let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
let mut min_final_cltv_expiry_delta = u32::max_value();
for _ in 0..path_count {
let hop_count: u8 = Readable::read(reader)?;
let mut hops: Vec<RouteHop> = Vec::with_capacity(hop_count as usize);
for _ in 0..hop_count {
hops.push(Readable::read(reader)?);
}
if hops.is_empty() { return Err(DecodeError::InvalidValue); }
min_final_cltv_expiry_delta =
cmp::min(min_final_cltv_expiry_delta, hops.last().unwrap().cltv_expiry_delta);
paths.push(Path { hops, blinded_tail: None });
}
_init_and_read_len_prefixed_tlv_fields!(reader, {
(1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
(2, blinded_tails, optional_vec),
(3, final_value_msat, option),
(5, max_total_routing_fee_msat, option)
});
let blinded_tails = blinded_tails.unwrap_or(Vec::new());
if blinded_tails.len() != 0 {
if blinded_tails.len() != paths.len() { return Err(DecodeError::InvalidValue) }
for (path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
path.blinded_tail = blinded_tail_opt;
}
}
// If we previously wrote the corresponding fields, reconstruct RouteParameters.
let route_params = match (payment_params, final_value_msat) {
(Some(payment_params), Some(final_value_msat)) => {
Some(RouteParameters { payment_params, final_value_msat, max_total_routing_fee_msat })
}
_ => None,
};
Ok(Route { paths, route_params })
}
}
/// Parameters needed to find a [`Route`].
///
/// Passed to [`find_route`] and [`build_route_from_hops`].
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct RouteParameters {
/// The parameters of the failed payment path.
pub payment_params: PaymentParameters,
/// The amount in msats sent on the failed payment path.
pub final_value_msat: u64,
/// The maximum total fees, in millisatoshi, that may accrue during route finding.
///
/// This limit also applies to the total fees that may arise while retrying failed payment
/// paths.
///
/// Note that values below a few sats may result in some paths being spuriously ignored.
pub max_total_routing_fee_msat: Option<u64>,
}
impl RouteParameters {
/// Constructs [`RouteParameters`] from the given [`PaymentParameters`] and a payment amount.
///
/// [`Self::max_total_routing_fee_msat`] defaults to 1% of the payment amount + 50 sats
pub fn from_payment_params_and_value(payment_params: PaymentParameters, final_value_msat: u64) -> Self {
Self { payment_params, final_value_msat, max_total_routing_fee_msat: Some(final_value_msat / 100 + 50_000) }
}
/// Sets the maximum number of hops that can be included in a payment path, based on the provided
/// [`RecipientOnionFields`] and blinded paths.
pub fn set_max_path_length(
&mut self, recipient_onion: &RecipientOnionFields, is_keysend: bool, best_block_height: u32
) -> Result<(), ()> {
let keysend_preimage_opt = is_keysend.then(|| PaymentPreimage([42; 32]));
// TODO: no way to account for the invoice request here yet
onion_utils::set_max_path_length(
self, recipient_onion, keysend_preimage_opt, None, best_block_height
)
}
}
impl Writeable for RouteParameters {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_tlv_fields!(writer, {
(0, self.payment_params, required),
(1, self.max_total_routing_fee_msat, option),
(2, self.final_value_msat, required),
// LDK versions prior to 0.0.114 had the `final_cltv_expiry_delta` parameter in
// `RouteParameters` directly. For compatibility, we write it here.
(4, self.payment_params.payee.final_cltv_expiry_delta(), option),
});
Ok(())
}
}
impl Readable for RouteParameters {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
_init_and_read_len_prefixed_tlv_fields!(reader, {
(0, payment_params, (required: ReadableArgs, 0)),
(1, max_total_routing_fee_msat, option),
(2, final_value_msat, required),
(4, final_cltv_delta, option),
});
let mut payment_params: PaymentParameters = payment_params.0.unwrap();
if let Payee::Clear { ref mut final_cltv_expiry_delta, .. } = payment_params.payee {
if final_cltv_expiry_delta == &0 {
*final_cltv_expiry_delta = final_cltv_delta.ok_or(DecodeError::InvalidValue)?;
}
}
Ok(Self {
payment_params,
final_value_msat: final_value_msat.0.unwrap(),
max_total_routing_fee_msat,
})
}
}
/// Maximum total CTLV difference we allow for a full payment path.
pub const DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA: u32 = 1008;
/// Maximum number of paths we allow an (MPP) payment to have.
// The default limit is currently set rather arbitrary - there aren't any real fundamental path-count
// limits, but for now more than 10 paths likely carries too much one-path failure.
pub const DEFAULT_MAX_PATH_COUNT: u8 = 10;
const DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF: u8 = 2;
// The median hop CLTV expiry delta currently seen in the network.
const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
/// Estimated maximum number of hops that can be included in a payment path. May be inaccurate if
/// payment metadata, custom TLVs, or blinded paths are included in the payment.
// During routing, we only consider paths shorter than our maximum length estimate.
// In the TLV onion format, there is no fixed maximum length, but the `hop_payloads`
// field is always 1300 bytes. As the `tlv_payload` for each hop may vary in length, we have to
// estimate how many hops the route may have so that it actually fits the `hop_payloads` field.
//
// We estimate 3+32 (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) +
// 2+8 (short_channel_id) = 61 bytes for each intermediate hop and 3+32
// (payload length and HMAC) + 2+8 (amt_to_forward) + 2+4 (outgoing_cltv_value) + 2+32+8
// (payment_secret and total_msat) = 93 bytes for the final hop.
// Since the length of the potentially included `payment_metadata` is unknown to us, we round
// down from (1300-93) / 61 = 19.78... to arrive at a conservative estimate of 19.
pub const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
/// Information used to route a payment.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct PaymentParameters {
/// Information about the payee, such as their features and route hints for their channels.
pub payee: Payee,
/// Expiration of a payment to the payee, in seconds relative to the UNIX epoch.
pub expiry_time: Option<u64>,
/// The maximum total CLTV delta we accept for the route.
/// Defaults to [`DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA`].
pub max_total_cltv_expiry_delta: u32,
/// The maximum number of paths that may be used by (MPP) payments.
/// Defaults to [`DEFAULT_MAX_PATH_COUNT`].
pub max_path_count: u8,
/// The maximum number of [`Path::hops`] in any returned path.
/// Defaults to [`MAX_PATH_LENGTH_ESTIMATE`].
pub max_path_length: u8,
/// Selects the maximum share of a channel's total capacity which will be sent over a channel,
/// as a power of 1/2. A higher value prefers to send the payment using more MPP parts whereas
/// a lower value prefers to send larger MPP parts, potentially saturating channels and
/// increasing failure probability for those paths.
///
/// Note that this restriction will be relaxed during pathfinding after paths which meet this
/// restriction have been found. While paths which meet this criteria will be searched for, it
/// is ultimately up to the scorer to select them over other paths.
///
/// A value of 0 will allow payments up to and including a channel's total announced usable
/// capacity, a value of one will only use up to half its capacity, two 1/4, etc.
///
/// Default value: 2
pub max_channel_saturation_power_of_half: u8,
/// A list of SCIDs which this payment was previously attempted over and which caused the
/// payment to fail. Future attempts for the same payment shouldn't be relayed through any of
/// these SCIDs.
pub previously_failed_channels: Vec<u64>,
/// A list of indices corresponding to blinded paths in [`Payee::Blinded::route_hints`] which this
/// payment was previously attempted over and which caused the payment to fail. Future attempts
/// for the same payment shouldn't be relayed through any of these blinded paths.
pub previously_failed_blinded_path_idxs: Vec<u64>,
}
impl Writeable for PaymentParameters {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
let mut clear_hints = &vec![];
let mut blinded_hints = None;
match &self.payee {
Payee::Clear { route_hints, .. } => clear_hints = route_hints,
Payee::Blinded { route_hints, .. } => {
let hints_iter = route_hints.iter().map(|path| (&path.payinfo, path.inner_blinded_path()));
blinded_hints = Some(crate::util::ser::IterableOwned(hints_iter));
}
}
write_tlv_fields!(writer, {
(0, self.payee.node_id(), option),
(1, self.max_total_cltv_expiry_delta, required),
(2, self.payee.features(), option),
(3, self.max_path_count, required),
(4, *clear_hints, required_vec),
(5, self.max_channel_saturation_power_of_half, required),
(6, self.expiry_time, option),
(7, self.previously_failed_channels, required_vec),
(8, blinded_hints, option),
(9, self.payee.final_cltv_expiry_delta(), option),
(11, self.previously_failed_blinded_path_idxs, required_vec),
(13, self.max_path_length, required),
});
Ok(())
}
}
impl ReadableArgs<u32> for PaymentParameters {
fn read<R: io::Read>(reader: &mut R, default_final_cltv_expiry_delta: u32) -> Result<Self, DecodeError> {
_init_and_read_len_prefixed_tlv_fields!(reader, {
(0, payee_pubkey, option),
(1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
(2, features, (option: ReadableArgs, payee_pubkey.is_some())),
(3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
(4, clear_route_hints, required_vec),
(5, max_channel_saturation_power_of_half, (default_value, DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF)),
(6, expiry_time, option),
(7, previously_failed_channels, optional_vec),
(8, blinded_route_hints, optional_vec),
(9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
(11, previously_failed_blinded_path_idxs, optional_vec),
(13, max_path_length, (default_value, MAX_PATH_LENGTH_ESTIMATE)),
});
let blinded_route_hints = blinded_route_hints.unwrap_or(vec![]);
let payee = if blinded_route_hints.len() != 0 {
if clear_route_hints.len() != 0 || payee_pubkey.is_some() { return Err(DecodeError::InvalidValue) }
Payee::Blinded {
route_hints: blinded_route_hints
.into_iter()
.map(|(payinfo, path)| BlindedPaymentPath::from_parts(path, payinfo))
.collect(),
features: features.and_then(|f: Features| f.bolt12()),
}
} else {
Payee::Clear {
route_hints: clear_route_hints,
node_id: payee_pubkey.ok_or(DecodeError::InvalidValue)?,
features: features.and_then(|f| f.bolt11()),
final_cltv_expiry_delta: final_cltv_expiry_delta.0.unwrap(),
}
};
Ok(Self {
max_total_cltv_expiry_delta: _init_tlv_based_struct_field!(max_total_cltv_expiry_delta, (default_value, unused)),
max_path_count: _init_tlv_based_struct_field!(max_path_count, (default_value, unused)),
payee,
max_channel_saturation_power_of_half: _init_tlv_based_struct_field!(max_channel_saturation_power_of_half, (default_value, unused)),
expiry_time,
previously_failed_channels: previously_failed_channels.unwrap_or(Vec::new()),
previously_failed_blinded_path_idxs: previously_failed_blinded_path_idxs.unwrap_or(Vec::new()),
max_path_length: _init_tlv_based_struct_field!(max_path_length, (default_value, unused)),
})
}
}
impl PaymentParameters {
/// Creates a payee with the node id of the given `pubkey`.
///
/// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
/// provided.
pub fn from_node_id(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
Self {
payee: Payee::Clear { node_id: payee_pubkey, route_hints: vec![], features: None, final_cltv_expiry_delta },
expiry_time: None,
max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
max_path_count: DEFAULT_MAX_PATH_COUNT,
max_path_length: MAX_PATH_LENGTH_ESTIMATE,
max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
previously_failed_channels: Vec::new(),
previously_failed_blinded_path_idxs: Vec::new(),
}
}
/// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
///
/// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
/// provided.
///
/// Note that MPP keysend is not widely supported yet. The `allow_mpp` lets you choose
/// whether your router will be allowed to find a multi-part route for this payment. If you
/// set `allow_mpp` to true, you should ensure a payment secret is set on send, likely via
/// [`RecipientOnionFields::secret_only`].
///
/// [`RecipientOnionFields::secret_only`]: crate::ln::channelmanager::RecipientOnionFields::secret_only
pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32, allow_mpp: bool) -> Self {
Self::from_node_id(payee_pubkey, final_cltv_expiry_delta)
.with_bolt11_features(Bolt11InvoiceFeatures::for_keysend(allow_mpp))
.expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
}
/// Creates parameters for paying to a blinded payee from the provided invoice. Sets
/// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
/// [`PaymentParameters::expiry_time`].
pub fn from_bolt12_invoice(invoice: &Bolt12Invoice) -> Self {
Self::blinded(invoice.payment_paths().to_vec())
.with_bolt12_features(invoice.invoice_features().clone()).unwrap()
.with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
}
/// Creates parameters for paying to a blinded payee from the provided invoice. Sets
/// [`Payee::Blinded::route_hints`], [`Payee::Blinded::features`], and
/// [`PaymentParameters::expiry_time`].
#[cfg(async_payments)]
pub fn from_static_invoice(invoice: &StaticInvoice) -> Self {
Self::blinded(invoice.payment_paths().to_vec())
.with_bolt12_features(invoice.invoice_features().clone()).unwrap()
.with_expiry_time(invoice.created_at().as_secs().saturating_add(invoice.relative_expiry().as_secs()))
}
/// Creates parameters for paying to a blinded payee from the provided blinded route hints.
pub fn blinded(blinded_route_hints: Vec<BlindedPaymentPath>) -> Self {
Self {
payee: Payee::Blinded { route_hints: blinded_route_hints, features: None },
expiry_time: None,
max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
max_path_count: DEFAULT_MAX_PATH_COUNT,
max_path_length: MAX_PATH_LENGTH_ESTIMATE,
max_channel_saturation_power_of_half: DEFAULT_MAX_CHANNEL_SATURATION_POW_HALF,
previously_failed_channels: Vec::new(),
previously_failed_blinded_path_idxs: Vec::new(),
}
}
/// Includes the payee's features. Errors if the parameters were not initialized with
/// [`PaymentParameters::from_bolt12_invoice`].
///
/// This is not exported to bindings users since bindings don't support move semantics
pub fn with_bolt12_features(self, features: Bolt12InvoiceFeatures) -> Result<Self, ()> {
match self.payee {
Payee::Clear { .. } => Err(()),
Payee::Blinded { route_hints, .. } =>
Ok(Self { payee: Payee::Blinded { route_hints, features: Some(features) }, ..self })
}
}
/// Includes the payee's features. Errors if the parameters were initialized with
/// [`PaymentParameters::from_bolt12_invoice`].
///
/// This is not exported to bindings users since bindings don't support move semantics
pub fn with_bolt11_features(self, features: Bolt11InvoiceFeatures) -> Result<Self, ()> {
match self.payee {
Payee::Blinded { .. } => Err(()),
Payee::Clear { route_hints, node_id, final_cltv_expiry_delta, .. } =>
Ok(Self {
payee: Payee::Clear {
route_hints, node_id, features: Some(features), final_cltv_expiry_delta
}, ..self
})
}
}
/// Includes hints for routing to the payee. Errors if the parameters were initialized with
/// [`PaymentParameters::from_bolt12_invoice`].
///
/// This is not exported to bindings users since bindings don't support move semantics
pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Result<Self, ()> {
match self.payee {
Payee::Blinded { .. } => Err(()),
Payee::Clear { node_id, features, final_cltv_expiry_delta, .. } =>
Ok(Self {
payee: Payee::Clear {
route_hints, node_id, features, final_cltv_expiry_delta,
}, ..self
})
}
}
/// Includes a payment expiration in seconds relative to the UNIX epoch.
///
/// This is not exported to bindings users since bindings don't support move semantics
pub fn with_expiry_time(self, expiry_time: u64) -> Self {
Self { expiry_time: Some(expiry_time), ..self }
}
/// Includes a limit for the total CLTV expiry delta which is considered during routing
///
/// This is not exported to bindings users since bindings don't support move semantics
pub fn with_max_total_cltv_expiry_delta(self, max_total_cltv_expiry_delta: u32) -> Self {
Self { max_total_cltv_expiry_delta, ..self }
}
/// Includes a limit for the maximum number of payment paths that may be used.
///
/// This is not exported to bindings users since bindings don't support move semantics
pub fn with_max_path_count(self, max_path_count: u8) -> Self {
Self { max_path_count, ..self }
}
/// Includes a limit for the maximum share of a channel's total capacity that can be sent over, as
/// a power of 1/2. See [`PaymentParameters::max_channel_saturation_power_of_half`].
///
/// This is not exported to bindings users since bindings don't support move semantics
pub fn with_max_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
Self { max_channel_saturation_power_of_half, ..self }
}
pub(crate) fn insert_previously_failed_blinded_path(&mut self, failed_blinded_tail: &BlindedTail) {
let mut found_blinded_tail = false;
for (idx, path) in self.payee.blinded_route_hints().iter().enumerate() {
if &failed_blinded_tail.hops == path.blinded_hops() &&
failed_blinded_tail.blinding_point == path.blinding_point()
{
self.previously_failed_blinded_path_idxs.push(idx as u64);
found_blinded_tail = true;
}
}
debug_assert!(found_blinded_tail);
}
}
/// The recipient of a payment, differing based on whether they've hidden their identity with route
/// blinding.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub enum Payee {
/// The recipient provided blinded paths and payinfo to reach them. The blinded paths themselves
/// will be included in the final [`Route`].
Blinded {
/// Aggregated routing info and blinded paths, for routing to the payee without knowing their
/// node id.
route_hints: Vec<BlindedPaymentPath>,
/// Features supported by the payee.
///
/// May be set from the payee's invoice. May be `None` if the invoice does not contain any
/// features.
features: Option<Bolt12InvoiceFeatures>,
},
/// The recipient included these route hints in their BOLT11 invoice.
Clear {
/// The node id of the payee.
node_id: PublicKey,
/// Hints for routing to the payee, containing channels connecting the payee to public nodes.
route_hints: Vec<RouteHint>,
/// Features supported by the payee.
///
/// May be set from the payee's invoice or via [`for_keysend`]. May be `None` if the invoice
/// does not contain any features.
///
/// [`for_keysend`]: PaymentParameters::for_keysend
features: Option<Bolt11InvoiceFeatures>,
/// The minimum CLTV delta at the end of the route. This value must not be zero.
final_cltv_expiry_delta: u32,
},
}
impl Payee {