-
Notifications
You must be signed in to change notification settings - Fork 365
/
router.rs
5650 lines (5118 loc) · 243 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 top-level routing/network map tracking logic lives here.
//!
//! You probably want to create a P2PGossipSync and use that as your RoutingMessageHandler and then
//! interrogate it to get routes for your own payments.
use bitcoin::secp256k1::PublicKey;
use crate::ln::channelmanager::ChannelDetails;
use crate::ln::features::{ChannelFeatures, InvoiceFeatures, NodeFeatures};
use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
use crate::routing::scoring::{ChannelUsage, Score};
use crate::util::ser::{Writeable, Readable, Writer};
use crate::util::logger::{Level, Logger};
use crate::util::chacha20::ChaCha20;
use crate::io;
use crate::prelude::*;
use alloc::collections::BinaryHeap;
use core::cmp;
use core::ops::Deref;
/// A trait defining behavior for routing a payment.
pub trait Router {
/// Finds a [`Route`] between `payer` and `payee` for a payment with the given values.
fn find_route(
&self, payer: &PublicKey, route_params: &RouteParameters,
first_hops: Option<&[&ChannelDetails]>, inflight_htlcs: InFlightHtlcs
) -> Result<Route, LightningError>;
}
/// 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.
#[cfg(not(any(test, feature = "_test_utils")))]
pub struct InFlightHtlcs(HashMap<(u64, bool), u64>);
#[cfg(any(test, feature = "_test_utils"))]
pub struct InFlightHtlcs(pub HashMap<(u64, bool), u64>);
impl InFlightHtlcs {
/// Create a new `InFlightHtlcs` via a mapping from:
/// (short_channel_id, source_pubkey < target_pubkey) -> used_liquidity_msat
pub fn new(inflight_map: HashMap<(u64, bool), u64>) -> Self {
InFlightHtlcs(inflight_map)
}
/// 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
#[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).
/// For the last hop, this should be the full value of the payment (might be more than
/// requested if we had to match htlc_minimum_msat).
pub fee_msat: u64,
/// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
/// expected at the destination, in excess of the current block height.
pub cltv_expiry_delta: u32,
}
impl_writeable_tlv_based!(RouteHop, {
(0, pubkey, required),
(2, node_features, required),
(4, short_channel_id, required),
(6, channel_features, required),
(8, fee_msat, required),
(10, cltv_expiry_delta, required),
});
/// 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, Hash, PartialEq, Eq)]
pub struct Route {
/// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
/// last RouteHop in each path must be the same. Each entry represents a list of hops, NOT
/// INCLUDING our own, where the last hop is the destination. Thus, this must always be at
/// least length one. While the maximum length of any given path is variable, keeping the length
/// of any path less or equal to 19 should currently ensure it is viable.
pub paths: Vec<Vec<RouteHop>>,
/// The `payment_params` parameter passed to [`find_route`].
/// This is used by `ChannelManager` to track information which may be required for retries,
/// provided back to you via [`Event::PaymentPathFailed`].
///
/// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
pub payment_params: Option<PaymentParameters>,
}
pub(crate) trait RoutePath {
/// Gets the fees for a given path, excluding any excess paid to the recipient.
fn get_path_fees(&self) -> u64;
}
impl RoutePath for Vec<RouteHop> {
fn get_path_fees(&self) -> u64 {
// Do not count last hop of each path since that's the full value of the payment
self.split_last().map(|(_, path_prefix)| path_prefix).unwrap_or(&[])
.iter().map(|hop| &hop.fee_msat)
.sum()
}
}
impl Route {
/// Returns the total amount of fees paid on this [`Route`].
///
/// This doesn't include any extra payment made to the recipient, which can happen in excess of
/// the amount passed to [`find_route`]'s `params.final_value_msat`.
pub fn get_total_fees(&self) -> u64 {
self.paths.iter().map(|path| path.get_path_fees()).sum()
}
/// Returns the total amount paid on this [`Route`], excluding the fees.
pub fn get_total_amount(&self) -> u64 {
return self.paths.iter()
.map(|path| path.split_last().map(|(hop, _)| hop.fee_msat).unwrap_or(0))
.sum();
}
}
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)?;
for hops in self.paths.iter() {
(hops.len() as u8).write(writer)?;
for hop in hops.iter() {
hop.write(writer)?;
}
}
write_tlv_fields!(writer, {
(1, self.payment_params, 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)?;
let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
for _ in 0..path_count {
let hop_count: u8 = Readable::read(reader)?;
let mut hops = Vec::with_capacity(hop_count as usize);
for _ in 0..hop_count {
hops.push(Readable::read(reader)?);
}
paths.push(hops);
}
let mut payment_params = None;
read_tlv_fields!(reader, {
(1, payment_params, option),
});
Ok(Route { paths, payment_params })
}
}
/// Parameters needed to find a [`Route`].
///
/// Passed to [`find_route`] and [`build_route_from_hops`], but also provided in
/// [`Event::PaymentPathFailed`] for retrying a failed payment path.
///
/// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
#[derive(Clone, Debug)]
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 CLTV on the final hop of the failed payment path.
pub final_cltv_expiry_delta: u32,
}
impl_writeable_tlv_based!(RouteParameters, {
(0, payment_params, required),
(2, final_value_msat, required),
(4, final_cltv_expiry_delta, required),
});
/// 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;
// The median hop CLTV expiry delta currently seen in the network.
const MEDIAN_HOP_CLTV_EXPIRY_DELTA: u32 = 40;
// During routing, we only consider paths shorter than our maximum length estimate.
// In the legacy onion format, the maximum number of hops used to be a fixed value of 20.
// However, 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.
const MAX_PATH_LENGTH_ESTIMATE: u8 = 19;
/// The recipient of a payment.
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct PaymentParameters {
/// The node id of the payee.
pub payee_pubkey: PublicKey,
/// 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`]: Self::for_keysend
pub features: Option<InvoiceFeatures>,
/// Hints for routing to the payee, containing channels connecting the payee to public nodes.
pub route_hints: Vec<RouteHint>,
/// 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,
/// 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>,
}
impl_writeable_tlv_based!(PaymentParameters, {
(0, payee_pubkey, required),
(1, max_total_cltv_expiry_delta, (default_value, DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA)),
(2, features, option),
(3, max_path_count, (default_value, DEFAULT_MAX_PATH_COUNT)),
(4, route_hints, vec_type),
(5, max_channel_saturation_power_of_half, (default_value, 2)),
(6, expiry_time, option),
(7, previously_failed_channels, vec_type),
});
impl PaymentParameters {
/// Creates a payee with the node id of the given `pubkey`.
pub fn from_node_id(payee_pubkey: PublicKey) -> Self {
Self {
payee_pubkey,
features: None,
route_hints: vec![],
expiry_time: None,
max_total_cltv_expiry_delta: DEFAULT_MAX_TOTAL_CLTV_EXPIRY_DELTA,
max_path_count: DEFAULT_MAX_PATH_COUNT,
max_channel_saturation_power_of_half: 2,
previously_failed_channels: Vec::new(),
}
}
/// Creates a payee with the node id of the given `pubkey` to use for keysend payments.
pub fn for_keysend(payee_pubkey: PublicKey) -> Self {
Self::from_node_id(payee_pubkey).with_features(InvoiceFeatures::for_keysend())
}
/// Includes the payee's features.
///
/// (C-not exported) since bindings don't support move semantics
pub fn with_features(self, features: InvoiceFeatures) -> Self {
Self { features: Some(features), ..self }
}
/// Includes hints for routing to the payee.
///
/// (C-not exported) since bindings don't support move semantics
pub fn with_route_hints(self, route_hints: Vec<RouteHint>) -> Self {
Self { route_hints, ..self }
}
/// Includes a payment expiration in seconds relative to the UNIX epoch.
///
/// (C-not exported) 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
///
/// (C-not exported) 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.
///
/// (C-not exported) 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 number of payment paths that may be used.
///
/// (C-not exported) 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 }
}
}
/// A list of hops along a payment path terminating with a channel to the recipient.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct RouteHint(pub Vec<RouteHintHop>);
impl Writeable for RouteHint {
fn write<W: crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
(self.0.len() as u64).write(writer)?;
for hop in self.0.iter() {
hop.write(writer)?;
}
Ok(())
}
}
impl Readable for RouteHint {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let hop_count: u64 = Readable::read(reader)?;
let mut hops = Vec::with_capacity(cmp::min(hop_count, 16) as usize);
for _ in 0..hop_count {
hops.push(Readable::read(reader)?);
}
Ok(Self(hops))
}
}
/// A channel descriptor for a hop along a payment path.
#[derive(Clone, Debug, Hash, Eq, PartialEq)]
pub struct RouteHintHop {
/// The node_id of the non-target end of the route
pub src_node_id: PublicKey,
/// The short_channel_id of this channel
pub short_channel_id: u64,
/// The fees which must be paid to use this channel
pub fees: RoutingFees,
/// The difference in CLTV values between this node and the next node.
pub cltv_expiry_delta: u16,
/// The minimum value, in msat, which must be relayed to the next hop.
pub htlc_minimum_msat: Option<u64>,
/// The maximum value in msat available for routing with a single HTLC.
pub htlc_maximum_msat: Option<u64>,
}
impl_writeable_tlv_based!(RouteHintHop, {
(0, src_node_id, required),
(1, htlc_minimum_msat, option),
(2, short_channel_id, required),
(3, htlc_maximum_msat, option),
(4, fees, required),
(6, cltv_expiry_delta, required),
});
#[derive(Eq, PartialEq)]
struct RouteGraphNode {
node_id: NodeId,
lowest_fee_to_peer_through_node: u64,
lowest_fee_to_node: u64,
total_cltv_delta: u32,
// The maximum value a yet-to-be-constructed payment path might flow through this node.
// This value is upper-bounded by us by:
// - how much is needed for a path being constructed
// - how much value can channels following this node (up to the destination) can contribute,
// considering their capacity and fees
value_contribution_msat: u64,
/// The effective htlc_minimum_msat at this hop. If a later hop on the path had a higher HTLC
/// minimum, we use it, plus the fees required at each earlier hop to meet it.
path_htlc_minimum_msat: u64,
/// All penalties incurred from this hop on the way to the destination, as calculated using
/// channel scoring.
path_penalty_msat: u64,
/// The number of hops walked up to this node.
path_length_to_node: u8,
}
impl cmp::Ord for RouteGraphNode {
fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
let other_score = cmp::max(other.lowest_fee_to_peer_through_node, other.path_htlc_minimum_msat)
.saturating_add(other.path_penalty_msat);
let self_score = cmp::max(self.lowest_fee_to_peer_through_node, self.path_htlc_minimum_msat)
.saturating_add(self.path_penalty_msat);
other_score.cmp(&self_score).then_with(|| other.node_id.cmp(&self.node_id))
}
}
impl cmp::PartialOrd for RouteGraphNode {
fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
Some(self.cmp(other))
}
}
/// A wrapper around the various hop representations.
///
/// Used to construct a [`PathBuildingHop`] and to estimate [`EffectiveCapacity`].
#[derive(Clone, Debug)]
enum CandidateRouteHop<'a> {
/// A hop from the payer, where the outbound liquidity is known.
FirstHop {
details: &'a ChannelDetails,
},
/// A hop found in the [`ReadOnlyNetworkGraph`], where the channel capacity may be unknown.
PublicHop {
info: DirectedChannelInfo<'a>,
short_channel_id: u64,
},
/// A hop to the payee found in the payment invoice, though not necessarily a direct channel.
PrivateHop {
hint: &'a RouteHintHop,
}
}
impl<'a> CandidateRouteHop<'a> {
fn short_channel_id(&self) -> u64 {
match self {
CandidateRouteHop::FirstHop { details } => details.get_outbound_payment_scid().unwrap(),
CandidateRouteHop::PublicHop { short_channel_id, .. } => *short_channel_id,
CandidateRouteHop::PrivateHop { hint } => hint.short_channel_id,
}
}
// NOTE: This may alloc memory so avoid calling it in a hot code path.
fn features(&self) -> ChannelFeatures {
match self {
CandidateRouteHop::FirstHop { details } => details.counterparty.features.to_context(),
CandidateRouteHop::PublicHop { info, .. } => info.channel().features.clone(),
CandidateRouteHop::PrivateHop { .. } => ChannelFeatures::empty(),
}
}
fn cltv_expiry_delta(&self) -> u32 {
match self {
CandidateRouteHop::FirstHop { .. } => 0,
CandidateRouteHop::PublicHop { info, .. } => info.direction().cltv_expiry_delta as u32,
CandidateRouteHop::PrivateHop { hint } => hint.cltv_expiry_delta as u32,
}
}
fn htlc_minimum_msat(&self) -> u64 {
match self {
CandidateRouteHop::FirstHop { .. } => 0,
CandidateRouteHop::PublicHop { info, .. } => info.direction().htlc_minimum_msat,
CandidateRouteHop::PrivateHop { hint } => hint.htlc_minimum_msat.unwrap_or(0),
}
}
fn fees(&self) -> RoutingFees {
match self {
CandidateRouteHop::FirstHop { .. } => RoutingFees {
base_msat: 0, proportional_millionths: 0,
},
CandidateRouteHop::PublicHop { info, .. } => info.direction().fees,
CandidateRouteHop::PrivateHop { hint } => hint.fees,
}
}
fn effective_capacity(&self) -> EffectiveCapacity {
match self {
CandidateRouteHop::FirstHop { details } => EffectiveCapacity::ExactLiquidity {
liquidity_msat: details.next_outbound_htlc_limit_msat,
},
CandidateRouteHop::PublicHop { info, .. } => info.effective_capacity(),
CandidateRouteHop::PrivateHop { .. } => EffectiveCapacity::Infinite,
}
}
}
#[inline]
fn max_htlc_from_capacity(capacity: EffectiveCapacity, max_channel_saturation_power_of_half: u8) -> u64 {
let saturation_shift: u32 = max_channel_saturation_power_of_half as u32;
match capacity {
EffectiveCapacity::ExactLiquidity { liquidity_msat } => liquidity_msat,
EffectiveCapacity::Infinite => u64::max_value(),
EffectiveCapacity::Unknown => EffectiveCapacity::Unknown.as_msat(),
EffectiveCapacity::MaximumHTLC { amount_msat } =>
amount_msat.checked_shr(saturation_shift).unwrap_or(0),
EffectiveCapacity::Total { capacity_msat, htlc_maximum_msat } =>
cmp::min(capacity_msat.checked_shr(saturation_shift).unwrap_or(0), htlc_maximum_msat),
}
}
fn iter_equal<I1: Iterator, I2: Iterator>(mut iter_a: I1, mut iter_b: I2)
-> bool where I1::Item: PartialEq<I2::Item> {
loop {
let a = iter_a.next();
let b = iter_b.next();
if a.is_none() && b.is_none() { return true; }
if a.is_none() || b.is_none() { return false; }
if a.unwrap().ne(&b.unwrap()) { return false; }
}
}
/// It's useful to keep track of the hops associated with the fees required to use them,
/// so that we can choose cheaper paths (as per Dijkstra's algorithm).
/// Fee values should be updated only in the context of the whole path, see update_value_and_recompute_fees.
/// These fee values are useful to choose hops as we traverse the graph "payee-to-payer".
#[derive(Clone)]
struct PathBuildingHop<'a> {
// Note that this should be dropped in favor of loading it from CandidateRouteHop, but doing so
// is a larger refactor and will require careful performance analysis.
node_id: NodeId,
candidate: CandidateRouteHop<'a>,
fee_msat: u64,
/// Minimal fees required to route to the source node of the current hop via any of its inbound channels.
src_lowest_inbound_fees: RoutingFees,
/// All the fees paid *after* this channel on the way to the destination
next_hops_fee_msat: u64,
/// Fee paid for the use of the current channel (see candidate.fees()).
/// The value will be actually deducted from the counterparty balance on the previous link.
hop_use_fee_msat: u64,
/// Used to compare channels when choosing the for routing.
/// Includes paying for the use of a hop and the following hops, as well as
/// an estimated cost of reaching this hop.
/// Might get stale when fees are recomputed. Primarily for internal use.
total_fee_msat: u64,
/// A mirror of the same field in RouteGraphNode. Note that this is only used during the graph
/// walk and may be invalid thereafter.
path_htlc_minimum_msat: u64,
/// All penalties incurred from this channel on the way to the destination, as calculated using
/// channel scoring.
path_penalty_msat: u64,
/// If we've already processed a node as the best node, we shouldn't process it again. Normally
/// we'd just ignore it if we did as all channels would have a higher new fee, but because we
/// may decrease the amounts in use as we walk the graph, the actual calculated fee may
/// decrease as well. Thus, we have to explicitly track which nodes have been processed and
/// avoid processing them again.
was_processed: bool,
#[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
// In tests, we apply further sanity checks on cases where we skip nodes we already processed
// to ensure it is specifically in cases where the fee has gone down because of a decrease in
// value_contribution_msat, which requires tracking it here. See comments below where it is
// used for more info.
value_contribution_msat: u64,
}
impl<'a> core::fmt::Debug for PathBuildingHop<'a> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> {
let mut debug_struct = f.debug_struct("PathBuildingHop");
debug_struct
.field("node_id", &self.node_id)
.field("short_channel_id", &self.candidate.short_channel_id())
.field("total_fee_msat", &self.total_fee_msat)
.field("next_hops_fee_msat", &self.next_hops_fee_msat)
.field("hop_use_fee_msat", &self.hop_use_fee_msat)
.field("total_fee_msat - (next_hops_fee_msat + hop_use_fee_msat)", &(&self.total_fee_msat - (&self.next_hops_fee_msat + &self.hop_use_fee_msat)))
.field("path_penalty_msat", &self.path_penalty_msat)
.field("path_htlc_minimum_msat", &self.path_htlc_minimum_msat)
.field("cltv_expiry_delta", &self.candidate.cltv_expiry_delta());
#[cfg(all(not(feature = "_bench_unstable"), any(test, fuzzing)))]
let debug_struct = debug_struct
.field("value_contribution_msat", &self.value_contribution_msat);
debug_struct.finish()
}
}
// Instantiated with a list of hops with correct data in them collected during path finding,
// an instance of this struct should be further modified only via given methods.
#[derive(Clone)]
struct PaymentPath<'a> {
hops: Vec<(PathBuildingHop<'a>, NodeFeatures)>,
}
impl<'a> PaymentPath<'a> {
// TODO: Add a value_msat field to PaymentPath and use it instead of this function.
fn get_value_msat(&self) -> u64 {
self.hops.last().unwrap().0.fee_msat
}
fn get_path_penalty_msat(&self) -> u64 {
self.hops.first().map(|h| h.0.path_penalty_msat).unwrap_or(u64::max_value())
}
fn get_total_fee_paid_msat(&self) -> u64 {
if self.hops.len() < 1 {
return 0;
}
let mut result = 0;
// Can't use next_hops_fee_msat because it gets outdated.
for (i, (hop, _)) in self.hops.iter().enumerate() {
if i != self.hops.len() - 1 {
result += hop.fee_msat;
}
}
return result;
}
fn get_cost_msat(&self) -> u64 {
self.get_total_fee_paid_msat().saturating_add(self.get_path_penalty_msat())
}
// If the amount transferred by the path is updated, the fees should be adjusted. Any other way
// to change fees may result in an inconsistency.
//
// Sometimes we call this function right after constructing a path which is inconsistent in
// that it the value being transferred has decreased while we were doing path finding, leading
// to the fees being paid not lining up with the actual limits.
//
// Note that this function is not aware of the available_liquidity limit, and thus does not
// support increasing the value being transferred beyond what was selected during the initial
// routing passes.
fn update_value_and_recompute_fees(&mut self, value_msat: u64) {
let mut total_fee_paid_msat = 0 as u64;
for i in (0..self.hops.len()).rev() {
let last_hop = i == self.hops.len() - 1;
// For non-last-hop, this value will represent the fees paid on the current hop. It
// will consist of the fees for the use of the next hop, and extra fees to match
// htlc_minimum_msat of the current channel. Last hop is handled separately.
let mut cur_hop_fees_msat = 0;
if !last_hop {
cur_hop_fees_msat = self.hops.get(i + 1).unwrap().0.hop_use_fee_msat;
}
let mut cur_hop = &mut self.hops.get_mut(i).unwrap().0;
cur_hop.next_hops_fee_msat = total_fee_paid_msat;
// Overpay in fees if we can't save these funds due to htlc_minimum_msat.
// We try to account for htlc_minimum_msat in scoring (add_entry!), so that nodes don't
// set it too high just to maliciously take more fees by exploiting this
// match htlc_minimum_msat logic.
let mut cur_hop_transferred_amount_msat = total_fee_paid_msat + value_msat;
if let Some(extra_fees_msat) = cur_hop.candidate.htlc_minimum_msat().checked_sub(cur_hop_transferred_amount_msat) {
// Note that there is a risk that *previous hops* (those closer to us, as we go
// payee->our_node here) would exceed their htlc_maximum_msat or available balance.
//
// This might make us end up with a broken route, although this should be super-rare
// in practice, both because of how healthy channels look like, and how we pick
// channels in add_entry.
// Also, this can't be exploited more heavily than *announce a free path and fail
// all payments*.
cur_hop_transferred_amount_msat += extra_fees_msat;
total_fee_paid_msat += extra_fees_msat;
cur_hop_fees_msat += extra_fees_msat;
}
if last_hop {
// Final hop is a special case: it usually has just value_msat (by design), but also
// it still could overpay for the htlc_minimum_msat.
cur_hop.fee_msat = cur_hop_transferred_amount_msat;
} else {
// Propagate updated fees for the use of the channels to one hop back, where they
// will be actually paid (fee_msat). The last hop is handled above separately.
cur_hop.fee_msat = cur_hop_fees_msat;
}
// Fee for the use of the current hop which will be deducted on the previous hop.
// Irrelevant for the first hop, as it doesn't have the previous hop, and the use of
// this channel is free for us.
if i != 0 {
if let Some(new_fee) = compute_fees(cur_hop_transferred_amount_msat, cur_hop.candidate.fees()) {
cur_hop.hop_use_fee_msat = new_fee;
total_fee_paid_msat += new_fee;
} else {
// It should not be possible because this function is called only to reduce the
// value. In that case, compute_fee was already called with the same fees for
// larger amount and there was no overflow.
unreachable!();
}
}
}
}
}
fn compute_fees(amount_msat: u64, channel_fees: RoutingFees) -> Option<u64> {
let proportional_fee_millions =
amount_msat.checked_mul(channel_fees.proportional_millionths as u64);
if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
(channel_fees.base_msat as u64).checked_add(part / 1_000_000) }) {
Some(new_fee)
} else {
// This function may be (indirectly) called without any verification,
// with channel_fees provided by a caller. We should handle it gracefully.
None
}
}
/// The default `features` we assume for a node in a route, when no `features` are known about that
/// specific node.
///
/// Default features are:
/// * variable_length_onion_optional
fn default_node_features() -> NodeFeatures {
let mut features = NodeFeatures::empty();
features.set_variable_length_onion_optional();
features
}
/// Finds a route from us (payer) to the given target node (payee).
///
/// If the payee provided features in their invoice, they should be provided via `params.payee`.
/// Without this, MPP will only be used if the payee's features are available in the network graph.
///
/// Private routing paths between a public node and the target may be included in `params.payee`.
///
/// If some channels aren't announced, it may be useful to fill in `first_hops` with the results
/// from [`ChannelManager::list_usable_channels`]. If it is filled in, the view of these channels
/// from `network_graph` will be ignored, and only those in `first_hops` will be used.
///
/// The fees on channels from us to the next hop are ignored as they are assumed to all be equal.
/// However, the enabled/disabled bit on such channels as well as the `htlc_minimum_msat` /
/// `htlc_maximum_msat` *are* checked as they may change based on the receiving node.
///
/// # Note
///
/// May be used to re-compute a [`Route`] when handling a [`Event::PaymentPathFailed`]. Any
/// adjustments to the [`NetworkGraph`] and channel scores should be made prior to calling this
/// function.
///
/// # Panics
///
/// Panics if first_hops contains channels without short_channel_ids;
/// [`ChannelManager::list_usable_channels`] will never include such channels.
///
/// [`ChannelManager::list_usable_channels`]: crate::ln::channelmanager::ChannelManager::list_usable_channels
/// [`Event::PaymentPathFailed`]: crate::util::events::Event::PaymentPathFailed
/// [`NetworkGraph`]: crate::routing::gossip::NetworkGraph
pub fn find_route<L: Deref, GL: Deref, S: Score>(
our_node_pubkey: &PublicKey, route_params: &RouteParameters,
network_graph: &NetworkGraph<GL>, first_hops: Option<&[&ChannelDetails]>, logger: L,
scorer: &S, random_seed_bytes: &[u8; 32]
) -> Result<Route, LightningError>
where L::Target: Logger, GL::Target: Logger {
let graph_lock = network_graph.read_only();
let mut route = get_route(our_node_pubkey, &route_params.payment_params, &graph_lock, first_hops,
route_params.final_value_msat, route_params.final_cltv_expiry_delta, logger, scorer,
random_seed_bytes)?;
add_random_cltv_offset(&mut route, &route_params.payment_params, &graph_lock, random_seed_bytes);
Ok(route)
}
pub(crate) fn get_route<L: Deref, S: Score>(
our_node_pubkey: &PublicKey, payment_params: &PaymentParameters, network_graph: &ReadOnlyNetworkGraph,
first_hops: Option<&[&ChannelDetails]>, final_value_msat: u64, final_cltv_expiry_delta: u32,
logger: L, scorer: &S, _random_seed_bytes: &[u8; 32]
) -> Result<Route, LightningError>
where L::Target: Logger {
let payee_node_id = NodeId::from_pubkey(&payment_params.payee_pubkey);
let our_node_id = NodeId::from_pubkey(&our_node_pubkey);
if payee_node_id == our_node_id {
return Err(LightningError{err: "Cannot generate a route to ourselves".to_owned(), action: ErrorAction::IgnoreError});
}
if final_value_msat > MAX_VALUE_MSAT {
return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis".to_owned(), action: ErrorAction::IgnoreError});
}
if final_value_msat == 0 {
return Err(LightningError{err: "Cannot send a payment of 0 msat".to_owned(), action: ErrorAction::IgnoreError});
}
for route in payment_params.route_hints.iter() {
for hop in &route.0 {
if hop.src_node_id == payment_params.payee_pubkey {
return Err(LightningError{err: "Route hint cannot have the payee as the source.".to_owned(), action: ErrorAction::IgnoreError});
}
}
}
if payment_params.max_total_cltv_expiry_delta <= final_cltv_expiry_delta {
return Err(LightningError{err: "Can't find a route where the maximum total CLTV expiry delta is below the final CLTV expiry.".to_owned(), action: ErrorAction::IgnoreError});
}
// The general routing idea is the following:
// 1. Fill first/last hops communicated by the caller.
// 2. Attempt to construct a path from payer to payee for transferring
// any ~sufficient (described later) value.
// If succeed, remember which channels were used and how much liquidity they have available,
// so that future paths don't rely on the same liquidity.
// 3. Proceed to the next step if:
// - we hit the recommended target value;
// - OR if we could not construct a new path. Any next attempt will fail too.
// Otherwise, repeat step 2.
// 4. See if we managed to collect paths which aggregately are able to transfer target value
// (not recommended value).
// 5. If yes, proceed. If not, fail routing.
// 6. Select the paths which have the lowest cost (fee plus scorer penalty) per amount
// transferred up to the transfer target value.
// 7. Reduce the value of the last path until we are sending only the target value.
// 8. If our maximum channel saturation limit caused us to pick two identical paths, combine
// them so that we're not sending two HTLCs along the same path.
// As for the actual search algorithm,
// we do a payee-to-payer pseudo-Dijkstra's sorting by each node's distance from the payee
// plus the minimum per-HTLC fee to get from it to another node (aka "shitty pseudo-A*").
//
// We are not a faithful Dijkstra's implementation because we can change values which impact
// earlier nodes while processing later nodes. Specifically, if we reach a channel with a lower
// liquidity limit (via htlc_maximum_msat, on-chain capacity or assumed liquidity limits) than
// the value we are currently attempting to send over a path, we simply reduce the value being
// sent along the path for any hops after that channel. This may imply that later fees (which
// we've already tabulated) are lower because a smaller value is passing through the channels
// (and the proportional fee is thus lower). There isn't a trivial way to recalculate the
// channels which were selected earlier (and which may still be used for other paths without a
// lower liquidity limit), so we simply accept that some liquidity-limited paths may be
// de-preferenced.
//
// One potentially problematic case for this algorithm would be if there are many
// liquidity-limited paths which are liquidity-limited near the destination (ie early in our
// graph walking), we may never find a path which is not liquidity-limited and has lower
// proportional fee (and only lower absolute fee when considering the ultimate value sent).
// Because we only consider paths with at least 5% of the total value being sent, the damage
// from such a case should be limited, however this could be further reduced in the future by
// calculating fees on the amount we wish to route over a path, ie ignoring the liquidity
// limits for the purposes of fee calculation.
//
// Alternatively, we could store more detailed path information in the heap (targets, below)
// and index the best-path map (dist, below) by node *and* HTLC limits, however that would blow
// up the runtime significantly both algorithmically (as we'd traverse nodes multiple times)
// and practically (as we would need to store dynamically-allocated path information in heap
// objects, increasing malloc traffic and indirect memory access significantly). Further, the
// results of such an algorithm would likely be biased towards lower-value paths.
//
// Further, we could return to a faithful Dijkstra's algorithm by rejecting paths with limits
// outside of our current search value, running a path search more times to gather candidate
// paths at different values. While this may be acceptable, further path searches may increase
// runtime for little gain. Specifically, the current algorithm rather efficiently explores the
// graph for candidate paths, calculating the maximum value which can realistically be sent at
// the same time, remaining generic across different payment values.
//
// TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
// to use as the A* heuristic beyond just the cost to get one node further than the current
// one.
let network_channels = network_graph.channels();
let network_nodes = network_graph.nodes();
if payment_params.max_path_count == 0 {
return Err(LightningError{err: "Can't find a route with no paths allowed.".to_owned(), action: ErrorAction::IgnoreError});
}
// Allow MPP only if we have a features set from somewhere that indicates the payee supports
// it. If the payee supports it they're supposed to include it in the invoice, so that should
// work reliably.
let allow_mpp = if payment_params.max_path_count == 1 {
false
} else if let Some(features) = &payment_params.features {
features.supports_basic_mpp()
} else if let Some(node) = network_nodes.get(&payee_node_id) {
if let Some(node_info) = node.announcement_info.as_ref() {
node_info.features.supports_basic_mpp()
} else { false }
} else { false };
log_trace!(logger, "Searching for a route from payer {} to payee {} {} MPP and {} first hops {}overriding the network graph", our_node_pubkey,
payment_params.payee_pubkey, if allow_mpp { "with" } else { "without" },
first_hops.map(|hops| hops.len()).unwrap_or(0), if first_hops.is_some() { "" } else { "not " });
// Step (1).
// Prepare the data we'll use for payee-to-payer search by
// inserting first hops suggested by the caller as targets.
// Our search will then attempt to reach them while traversing from the payee node.
let mut first_hop_targets: HashMap<_, Vec<&ChannelDetails>> =
HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
if let Some(hops) = first_hops {
for chan in hops {
if chan.get_outbound_payment_scid().is_none() {
panic!("first_hops should be filled in with usable channels, not pending ones");
}
if chan.counterparty.node_id == *our_node_pubkey {
return Err(LightningError{err: "First hop cannot have our_node_pubkey as a destination.".to_owned(), action: ErrorAction::IgnoreError});
}
first_hop_targets
.entry(NodeId::from_pubkey(&chan.counterparty.node_id))
.or_insert(Vec::new())
.push(chan);
}
if first_hop_targets.is_empty() {
return Err(LightningError{err: "Cannot route when there are no outbound routes away from us".to_owned(), action: ErrorAction::IgnoreError});
}
}
// The main heap containing all candidate next-hops sorted by their score (max(A* fee,
// htlc_minimum)). Ideally this would be a heap which allowed cheap score reduction instead of
// adding duplicate entries when we find a better path to a given node.
let mut targets: BinaryHeap<RouteGraphNode> = BinaryHeap::new();
// Map from node_id to information about the best current path to that node, including feerate
// information.
let mut dist: HashMap<NodeId, PathBuildingHop> = HashMap::with_capacity(network_nodes.len());
// During routing, if we ignore a path due to an htlc_minimum_msat limit, we set this,
// indicating that we may wish to try again with a higher value, potentially paying to meet an
// htlc_minimum with extra fees while still finding a cheaper path.
let mut hit_minimum_limit;
// When arranging a route, we select multiple paths so that we can make a multi-path payment.
// We start with a path_value of the exact amount we want, and if that generates a route we may
// return it immediately. Otherwise, we don't stop searching for paths until we have 3x the
// amount we want in total across paths, selecting the best subset at the end.
const ROUTE_CAPACITY_PROVISION_FACTOR: u64 = 3;
let recommended_value_msat = final_value_msat * ROUTE_CAPACITY_PROVISION_FACTOR as u64;
let mut path_value_msat = final_value_msat;
// Routing Fragmentation Mitigation heuristic:
//
// Routing fragmentation across many payment paths increases the overall routing
// fees as you have irreducible routing fees per-link used (`fee_base_msat`).
// Taking too many smaller paths also increases the chance of payment failure.
// Thus to avoid this effect, we require from our collected links to provide
// at least a minimal contribution to the recommended value yet-to-be-fulfilled.
// This requirement is currently set to be 1/max_path_count of the payment
// value to ensure we only ever return routes that do not violate this limit.
let minimal_value_contribution_msat: u64 = if allow_mpp {
(final_value_msat + (payment_params.max_path_count as u64 - 1)) / payment_params.max_path_count as u64
} else {
final_value_msat
};
// When we start collecting routes we enforce the max_channel_saturation_power_of_half
// requirement strictly. After we've collected enough (or if we fail to find new routes) we
// drop the requirement by setting this to 0.
let mut channel_saturation_pow_half = payment_params.max_channel_saturation_power_of_half;
// Keep track of how much liquidity has been used in selected channels. Used to determine
// if the channel can be used by additional MPP paths or to inform path finding decisions. It is
// aware of direction *only* to ensure that the correct htlc_maximum_msat value is used. Hence,
// liquidity used in one direction will not offset any used in the opposite direction.
let mut used_channel_liquidities: HashMap<(u64, bool), u64> =
HashMap::with_capacity(network_nodes.len());
// Keeping track of how much value we already collected across other paths. Helps to decide
// when we want to stop looking for new paths.
let mut already_collected_value_msat = 0;
for (_, channels) in first_hop_targets.iter_mut() {
// Sort the first_hops channels to the same node(s) in priority order of which channel we'd
// most like to use.
//
// First, if channels are below `recommended_value_msat`, sort them in descending order,
// preferring larger channels to avoid splitting the payment into more MPP parts than is
// required.
//
// Second, because simply always sorting in descending order would always use our largest
// available outbound capacity, needlessly fragmenting our available channel capacities,
// sort channels above `recommended_value_msat` in ascending order, preferring channels
// which have enough, but not too much, capacity for the payment.