/
router.rs
6225 lines (5659 loc) · 266 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;
use bitcoin::hashes::Hash;
use bitcoin::hashes::sha256::Hash as Sha256;
use crate::blinded_path::{BlindedHop, BlindedPath};
use crate::ln::PaymentHash;
use crate::ln::channelmanager::{ChannelDetails, PaymentId};
use crate::ln::features::{Bolt12InvoiceFeatures, ChannelFeatures, InvoiceFeatures, NodeFeatures};
use crate::ln::msgs::{DecodeError, ErrorAction, LightningError, MAX_VALUE_MSAT};
use crate::offers::invoice::BlindedPayInfo;
use crate::routing::gossip::{DirectedChannelInfo, EffectiveCapacity, ReadOnlyNetworkGraph, NetworkGraph, NodeId, RoutingFees};
use crate::routing::scoring::{ChannelUsage, LockableScore, Score};
use crate::util::ser::{Writeable, Readable, ReadableArgs, Writer};
use crate::util::logger::{Level, Logger};
use crate::util::chacha20::ChaCha20;
use crate::io;
use crate::prelude::*;
use crate::sync::Mutex;
use alloc::collections::BinaryHeap;
use core::cmp;
use core::ops::Deref;
/// A [`Router`] implemented using [`find_route`].
pub struct DefaultRouter<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a>,
{
network_graph: G,
logger: L,
random_seed_bytes: Mutex<[u8; 32]>,
scorer: S
}
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> DefaultRouter<G, L, S> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a>,
{
/// Creates a new router.
pub fn new(network_graph: G, logger: L, random_seed_bytes: [u8; 32], scorer: S) -> Self {
let random_seed_bytes = Mutex::new(random_seed_bytes);
Self { network_graph, logger, random_seed_bytes, scorer }
}
}
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref, S: Deref> Router for DefaultRouter<G, L, S> where
L::Target: Logger,
S::Target: for <'a> LockableScore<'a>,
{
fn find_route(
&self, payer: &PublicKey, params: &RouteParameters, first_hops: Option<&[&ChannelDetails]>,
inflight_htlcs: &InFlightHtlcs
) -> Result<Route, LightningError> {
let random_seed_bytes = {
let mut locked_random_seed_bytes = self.random_seed_bytes.lock().unwrap();
*locked_random_seed_bytes = Sha256::hash(&*locked_random_seed_bytes).into_inner();
*locked_random_seed_bytes
};
find_route(
payer, params, &self.network_graph, first_hops, &*self.logger,
&ScorerAccountingForInFlightHtlcs::new(self.scorer.lock(), inflight_htlcs),
&random_seed_bytes
)
}
}
/// 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>;
/// Finds a [`Route`] between `payer` and `payee` for a payment with the given values. Includes
/// `PaymentHash` and `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)
}
}
/// [`Score`] implementation that factors in in-flight HTLC liquidity.
///
/// Useful for custom [`Router`] implementations to wrap their [`Score`] on-the-fly when calling
/// [`find_route`].
///
/// [`Score`]: crate::routing::scoring::Score
pub struct ScorerAccountingForInFlightHtlcs<'a, S: Score> {
scorer: S,
// Maps a channel's short channel id and its direction to the liquidity used up.
inflight_htlcs: &'a InFlightHtlcs,
}
impl<'a, S: Score> ScorerAccountingForInFlightHtlcs<'a, S> {
/// Initialize a new `ScorerAccountingForInFlightHtlcs`.
pub fn new(scorer: S, inflight_htlcs: &'a InFlightHtlcs) -> Self {
ScorerAccountingForInFlightHtlcs {
scorer,
inflight_htlcs
}
}
}
#[cfg(c_bindings)]
impl<'a, S: Score> Writeable for ScorerAccountingForInFlightHtlcs<'a, S> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> { self.scorer.write(writer) }
}
impl<'a, S: Score> Score for ScorerAccountingForInFlightHtlcs<'a, S> {
fn channel_penalty_msat(&self, short_channel_id: u64, source: &NodeId, target: &NodeId, usage: ChannelUsage) -> u64 {
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 + used_liquidity,
..usage
};
self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
} else {
self.scorer.channel_penalty_msat(short_channel_id, source, target, usage)
}
}
fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64) {
self.scorer.payment_path_failed(path, short_channel_id)
}
fn payment_path_successful(&mut self, path: &Path) {
self.scorer.payment_path_successful(path)
}
fn probe_failed(&mut self, path: &Path, short_channel_id: u64) {
self.scorer.probe_failed(path, short_channel_id)
}
fn probe_successful(&mut self, path: &Path) {
self.scorer.probe_successful(path)
}
}
/// 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(HashMap::new()) }
/// 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);
}
}
/// 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 [`BlindedPath`], 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
///
/// [`BlindedPath`]: crate::blinded_path::BlindedPath
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 [`BlindedPath`], this is the CLTV delta for the entire blinded path
/// * otherwise, this is the CLTV delta expected at the destination
///
/// [`BlindedPath`]: crate::blinded_path::BlindedPath
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),
});
/// The blinded portion of a [`Path`], if we're routing to a recipient who provided blinded paths in
/// their BOLT12 [`Invoice`].
///
/// [`Invoice`]: crate::offers::invoice::Invoice
#[derive(Clone, Debug, Hash, PartialEq, Eq)]
pub struct BlindedTail {
/// The hops of the [`BlindedPath`] provided by the recipient.
///
/// [`BlindedPath`]: crate::blinded_path::BlindedPath
pub hops: Vec<BlindedHop>,
/// The blinding point of the [`BlindedPath`] provided by the recipient.
///
/// [`BlindedPath`]: crate::blinded_path::BlindedPath
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, vec_type),
(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, 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 `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::events::Event::PaymentPathFailed
pub payment_params: Option<PaymentParameters>,
}
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.fee_msat()).sum()
}
/// Returns the total amount paid on this [`Route`], excluding the fees. Might be more than
/// requested if we had to reach htlc_minimum_msat.
pub fn get_total_amount(&self) -> u64 {
self.paths.iter().map(|path| path.final_value_msat()).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)?;
let mut blinded_tails = Vec::new();
for path in self.paths.iter() {
(path.hops.len() as u8).write(writer)?;
for (idx, hop) in path.hops.iter().enumerate() {
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, {
(1, self.payment_params, option),
(2, blinded_tails, optional_vec),
});
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_tlv_fields!(reader, {
(1, payment_params, (option: ReadableArgs, min_final_cltv_expiry_delta)),
(2, blinded_tails, optional_vec),
});
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 (mut path, blinded_tail_opt) in paths.iter_mut().zip(blinded_tails.into_iter()) {
path.blinded_tail = blinded_tail_opt;
}
}
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`].
///
/// [`Event::PaymentPathFailed`]: crate::events::Event::PaymentPathFailed
#[derive(Clone, Debug, 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,
}
impl Writeable for RouteParameters {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
write_tlv_fields!(writer, {
(0, self.payment_params, required),
(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_tlv_fields!(reader, {
(0, payment_params, (required: ReadableArgs, 0)),
(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(),
})
}
}
/// 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 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;
/// 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,
/// 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 for PaymentParameters {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
let mut clear_hints = &vec![];
let mut blinded_hints = &vec![];
match &self.payee {
Payee::Clear { route_hints, .. } => clear_hints = route_hints,
Payee::Blinded { route_hints, .. } => blinded_hints = route_hints,
}
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, vec_type),
(5, self.max_channel_saturation_power_of_half, required),
(6, self.expiry_time, option),
(7, self.previously_failed_channels, vec_type),
(8, *blinded_hints, optional_vec),
(9, self.payee.final_cltv_expiry_delta(), option),
});
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_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, route_hints, vec_type),
(5, max_channel_saturation_power_of_half, (default_value, 2)),
(6, expiry_time, option),
(7, previously_failed_channels, vec_type),
(8, blinded_route_hints, optional_vec),
(9, final_cltv_expiry_delta, (default_value, default_final_cltv_expiry_delta)),
});
let clear_route_hints = route_hints.unwrap_or(vec![]);
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,
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()),
})
}
}
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_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.
///
/// The `final_cltv_expiry_delta` should match the expected final CLTV delta the recipient has
/// provided.
pub fn for_keysend(payee_pubkey: PublicKey, final_cltv_expiry_delta: u32) -> Self {
Self::from_node_id(payee_pubkey, final_cltv_expiry_delta).with_bolt11_features(InvoiceFeatures::for_keysend()).expect("PaymentParameters::from_node_id should always initialize the payee as unblinded")
}
/// Includes the payee's features. Errors if the parameters were initialized with blinded payment
/// paths.
///
/// This is not exported to bindings users since bindings don't support move semantics
pub fn with_bolt11_features(self, features: InvoiceFeatures) -> 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
/// blinded payment paths.
///
/// 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 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_channel_saturation_power_of_half(self, max_channel_saturation_power_of_half: u8) -> Self {
Self { max_channel_saturation_power_of_half, ..self }
}
}
/// 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<(BlindedPayInfo, BlindedPath)>,
/// 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<InvoiceFeatures>,
/// The minimum CLTV delta at the end of the route. This value must not be zero.
final_cltv_expiry_delta: u32,
},
}
impl Payee {
fn node_id(&self) -> Option<PublicKey> {
match self {
Self::Clear { node_id, .. } => Some(*node_id),
_ => None,
}
}
fn node_features(&self) -> Option<NodeFeatures> {
match self {
Self::Clear { features, .. } => features.as_ref().map(|f| f.to_context()),
Self::Blinded { features, .. } => features.as_ref().map(|f| f.to_context()),
}
}
fn supports_basic_mpp(&self) -> bool {
match self {
Self::Clear { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
Self::Blinded { features, .. } => features.as_ref().map_or(false, |f| f.supports_basic_mpp()),
}
}
fn features(&self) -> Option<FeaturesRef> {
match self {
Self::Clear { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt11(f)),
Self::Blinded { features, .. } => features.as_ref().map(|f| FeaturesRef::Bolt12(f)),
}
}
fn final_cltv_expiry_delta(&self) -> Option<u32> {
match self {
Self::Clear { final_cltv_expiry_delta, .. } => Some(*final_cltv_expiry_delta),
_ => None,
}
}
}
enum FeaturesRef<'a> {
Bolt11(&'a InvoiceFeatures),
Bolt12(&'a Bolt12InvoiceFeatures),
}
enum Features {
Bolt11(InvoiceFeatures),
Bolt12(Bolt12InvoiceFeatures),
}
impl Features {
fn bolt12(self) -> Option<Bolt12InvoiceFeatures> {
match self {
Self::Bolt12(f) => Some(f),
_ => None,
}
}
fn bolt11(self) -> Option<InvoiceFeatures> {
match self {
Self::Bolt11(f) => Some(f),
_ => None,
}
}
}
impl<'a> Writeable for FeaturesRef<'a> {
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
match self {
Self::Bolt11(f) => Ok(f.write(w)?),
Self::Bolt12(f) => Ok(f.write(w)?),
}
}
}
impl ReadableArgs<bool> for Features {
fn read<R: io::Read>(reader: &mut R, bolt11: bool) -> Result<Self, DecodeError> {
if bolt11 { return Ok(Self::Bolt11(Readable::read(reader)?)) }
Ok(Self::Bolt12(Readable::read(reader)?))
}
}
/// 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_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_node, other.path_htlc_minimum_msat)
.saturating_add(other.path_penalty_msat);
let self_score = cmp::max(self.lowest_fee_to_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,
/// 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,