-
Notifications
You must be signed in to change notification settings - Fork 375
/
scoring.rs
3519 lines (3149 loc) · 148 KB
/
scoring.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Utilities for scoring payment channels.
//!
//! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path
//! finding when a custom [`ScoreLookUp`] implementation is not needed.
//!
//! # Example
//!
//! ```
//! # extern crate bitcoin;
//! #
//! # use lightning::routing::gossip::NetworkGraph;
//! # use lightning::routing::router::{RouteParameters, find_route};
//! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
//! # use lightning::sign::KeysManager;
//! # use lightning::util::logger::{Logger, Record};
//! # use bitcoin::secp256k1::PublicKey;
//! #
//! # struct FakeLogger {};
//! # impl Logger for FakeLogger {
//! # fn log(&self, record: Record) { unimplemented!() }
//! # }
//! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph<&FakeLogger>) {
//! # let logger = FakeLogger {};
//! #
//! // Use the default channel penalties.
//! let params = ProbabilisticScoringFeeParameters::default();
//! let decay_params = ProbabilisticScoringDecayParameters::default();
//! let scorer = ProbabilisticScorer::new(decay_params, &network_graph, &logger);
//!
//! // Or use custom channel penalties.
//! let params = ProbabilisticScoringFeeParameters {
//! liquidity_penalty_multiplier_msat: 2 * 1000,
//! ..ProbabilisticScoringFeeParameters::default()
//! };
//! let decay_params = ProbabilisticScoringDecayParameters::default();
//! let scorer = ProbabilisticScorer::new(decay_params, &network_graph, &logger);
//! # let random_seed_bytes = [42u8; 32];
//!
//! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer, ¶ms, &random_seed_bytes);
//! # }
//! ```
//!
//! [`find_route`]: crate::routing::router::find_route
use crate::ln::msgs::DecodeError;
use crate::routing::gossip::{EffectiveCapacity, NetworkGraph, NodeId};
use crate::routing::router::{Path, CandidateRouteHop, PublicHopCandidate};
use crate::routing::log_approx;
use crate::util::ser::{Readable, ReadableArgs, Writeable, Writer};
use crate::util::logger::Logger;
use crate::prelude::*;
use core::{cmp, fmt};
use core::ops::{Deref, DerefMut};
use core::time::Duration;
use crate::io::{self, Read};
use crate::sync::{RwLock, RwLockReadGuard, RwLockWriteGuard};
#[cfg(not(c_bindings))]
use {
core::cell::{RefCell, RefMut, Ref},
crate::sync::{Mutex, MutexGuard},
};
/// We define Score ever-so-slightly differently based on whether we are being built for C bindings
/// or not. For users, `LockableScore` must somehow be writeable to disk. For Rust users, this is
/// no problem - you move a `Score` that implements `Writeable` into a `Mutex`, lock it, and now
/// you have the original, concrete, `Score` type, which presumably implements `Writeable`.
///
/// For C users, once you've moved the `Score` into a `LockableScore` all you have after locking it
/// is an opaque trait object with an opaque pointer with no type info. Users could take the unsafe
/// approach of blindly casting that opaque pointer to a concrete type and calling `Writeable` from
/// there, but other languages downstream of the C bindings (e.g. Java) can't even do that.
/// Instead, we really want `Score` and `LockableScore` to implement `Writeable` directly, which we
/// do here by defining `Score` differently for `cfg(c_bindings)`.
macro_rules! define_score { ($($supertrait: path)*) => {
/// An interface used to score payment channels for path finding.
///
/// `ScoreLookUp` is used to determine the penalty for a given channel.
///
/// Scoring is in terms of fees willing to be paid in order to avoid routing through a channel.
pub trait ScoreLookUp {
/// A configurable type which should contain various passed-in parameters for configuring the scorer,
/// on a per-routefinding-call basis through to the scorer methods,
/// which are used to determine the parameters for the suitability of channels for use.
type ScoreParams;
/// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
/// given channel in the direction from `source` to `target`.
///
/// The channel's capacity (less any other MPP parts that are also being considered for use in
/// the same payment) is given by `capacity_msat`. It may be determined from various sources
/// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near
/// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount.
/// Thus, implementations should be overflow-safe.
fn channel_penalty_msat(
&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams
) -> u64;
}
/// `ScoreUpdate` is used to update the scorer's internal state after a payment attempt.
pub trait ScoreUpdate {
/// Handles updating channel penalties after failing to route through a channel.
fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration);
/// Handles updating channel penalties after successfully routing along a path.
fn payment_path_successful(&mut self, path: &Path, duration_since_epoch: Duration);
/// Handles updating channel penalties after a probe over the given path failed.
fn probe_failed(&mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration);
/// Handles updating channel penalties after a probe over the given path succeeded.
fn probe_successful(&mut self, path: &Path, duration_since_epoch: Duration);
/// Scorers may wish to reduce their certainty of channel liquidity information over time.
/// Thus, this method is provided to allow scorers to observe the passage of time - the holder
/// of this object should call this method regularly (generally via the
/// `lightning-background-processor` crate).
fn time_passed(&mut self, duration_since_epoch: Duration);
}
/// A trait which can both lookup and update routing channel penalty scores.
///
/// This is used in places where both bounds are required and implemented for all types which
/// implement [`ScoreLookUp`] and [`ScoreUpdate`].
///
/// Bindings users may need to manually implement this for their custom scoring implementations.
pub trait Score : ScoreLookUp + ScoreUpdate $(+ $supertrait)* {}
#[cfg(not(c_bindings))]
impl<T: ScoreLookUp + ScoreUpdate $(+ $supertrait)*> Score for T {}
#[cfg(not(c_bindings))]
impl<S: ScoreLookUp, T: Deref<Target=S>> ScoreLookUp for T {
type ScoreParams = S::ScoreParams;
fn channel_penalty_msat(
&self, candidate: &CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams
) -> u64 {
self.deref().channel_penalty_msat(candidate, usage, score_params)
}
}
#[cfg(not(c_bindings))]
impl<S: ScoreUpdate, T: DerefMut<Target=S>> ScoreUpdate for T {
fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration) {
self.deref_mut().payment_path_failed(path, short_channel_id, duration_since_epoch)
}
fn payment_path_successful(&mut self, path: &Path, duration_since_epoch: Duration) {
self.deref_mut().payment_path_successful(path, duration_since_epoch)
}
fn probe_failed(&mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration) {
self.deref_mut().probe_failed(path, short_channel_id, duration_since_epoch)
}
fn probe_successful(&mut self, path: &Path, duration_since_epoch: Duration) {
self.deref_mut().probe_successful(path, duration_since_epoch)
}
fn time_passed(&mut self, duration_since_epoch: Duration) {
self.deref_mut().time_passed(duration_since_epoch)
}
}
} }
#[cfg(c_bindings)]
define_score!(Writeable);
#[cfg(not(c_bindings))]
define_score!();
/// A scorer that is accessed under a lock.
///
/// Needed so that calls to [`ScoreLookUp::channel_penalty_msat`] in [`find_route`] can be made while
/// having shared ownership of a scorer but without requiring internal locking in [`ScoreUpdate`]
/// implementations. Internal locking would be detrimental to route finding performance and could
/// result in [`ScoreLookUp::channel_penalty_msat`] returning a different value for the same channel.
///
/// [`find_route`]: crate::routing::router::find_route
pub trait LockableScore<'a> {
/// The [`ScoreUpdate`] type.
type ScoreUpdate: 'a + ScoreUpdate;
/// The [`ScoreLookUp`] type.
type ScoreLookUp: 'a + ScoreLookUp;
/// The write locked [`ScoreUpdate`] type.
type WriteLocked: DerefMut<Target = Self::ScoreUpdate> + Sized;
/// The read locked [`ScoreLookUp`] type.
type ReadLocked: Deref<Target = Self::ScoreLookUp> + Sized;
/// Returns read locked scorer.
fn read_lock(&'a self) -> Self::ReadLocked;
/// Returns write locked scorer.
fn write_lock(&'a self) -> Self::WriteLocked;
}
/// Refers to a scorer that is accessible under lock and also writeable to disk
///
/// We need this trait to be able to pass in a scorer to `lightning-background-processor` that will enable us to
/// use the Persister to persist it.
pub trait WriteableScore<'a>: LockableScore<'a> + Writeable {}
#[cfg(not(c_bindings))]
impl<'a, T> WriteableScore<'a> for T where T: LockableScore<'a> + Writeable {}
#[cfg(not(c_bindings))]
impl<'a, T: Score + 'a> LockableScore<'a> for Mutex<T> {
type ScoreUpdate = T;
type ScoreLookUp = T;
type WriteLocked = MutexGuard<'a, Self::ScoreUpdate>;
type ReadLocked = MutexGuard<'a, Self::ScoreLookUp>;
fn read_lock(&'a self) -> Self::ReadLocked {
Mutex::lock(self).unwrap()
}
fn write_lock(&'a self) -> Self::WriteLocked {
Mutex::lock(self).unwrap()
}
}
#[cfg(not(c_bindings))]
impl<'a, T: Score + 'a> LockableScore<'a> for RefCell<T> {
type ScoreUpdate = T;
type ScoreLookUp = T;
type WriteLocked = RefMut<'a, Self::ScoreUpdate>;
type ReadLocked = Ref<'a, Self::ScoreLookUp>;
fn write_lock(&'a self) -> Self::WriteLocked {
self.borrow_mut()
}
fn read_lock(&'a self) -> Self::ReadLocked {
self.borrow()
}
}
#[cfg(any(not(c_bindings), feature = "_test_utils", test))]
impl<'a, T: Score + 'a> LockableScore<'a> for RwLock<T> {
type ScoreUpdate = T;
type ScoreLookUp = T;
type WriteLocked = RwLockWriteGuard<'a, Self::ScoreLookUp>;
type ReadLocked = RwLockReadGuard<'a, Self::ScoreUpdate>;
fn read_lock(&'a self) -> Self::ReadLocked {
RwLock::read(self).unwrap()
}
fn write_lock(&'a self) -> Self::WriteLocked {
RwLock::write(self).unwrap()
}
}
#[cfg(c_bindings)]
/// A concrete implementation of [`LockableScore`] which supports multi-threading.
pub struct MultiThreadedLockableScore<T: Score> {
score: RwLock<T>,
}
#[cfg(c_bindings)]
impl<'a, T: Score + 'a> LockableScore<'a> for MultiThreadedLockableScore<T> {
type ScoreUpdate = T;
type ScoreLookUp = T;
type WriteLocked = MultiThreadedScoreLockWrite<'a, Self::ScoreUpdate>;
type ReadLocked = MultiThreadedScoreLockRead<'a, Self::ScoreLookUp>;
fn read_lock(&'a self) -> Self::ReadLocked {
MultiThreadedScoreLockRead(self.score.read().unwrap())
}
fn write_lock(&'a self) -> Self::WriteLocked {
MultiThreadedScoreLockWrite(self.score.write().unwrap())
}
}
#[cfg(c_bindings)]
impl<T: Score> Writeable for MultiThreadedLockableScore<T> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
self.score.read().unwrap().write(writer)
}
}
#[cfg(c_bindings)]
impl<'a, T: Score + 'a> WriteableScore<'a> for MultiThreadedLockableScore<T> {}
#[cfg(c_bindings)]
impl<T: Score> MultiThreadedLockableScore<T> {
/// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
pub fn new(score: T) -> Self {
MultiThreadedLockableScore { score: RwLock::new(score) }
}
}
#[cfg(c_bindings)]
/// A locked `MultiThreadedLockableScore`.
pub struct MultiThreadedScoreLockRead<'a, T: Score>(RwLockReadGuard<'a, T>);
#[cfg(c_bindings)]
/// A locked `MultiThreadedLockableScore`.
pub struct MultiThreadedScoreLockWrite<'a, T: Score>(RwLockWriteGuard<'a, T>);
#[cfg(c_bindings)]
impl<'a, T: 'a + Score> Deref for MultiThreadedScoreLockRead<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
#[cfg(c_bindings)]
impl<'a, T: Score> ScoreLookUp for MultiThreadedScoreLockRead<'a, T> {
type ScoreParams = T::ScoreParams;
fn channel_penalty_msat(&self, candidate:&CandidateRouteHop, usage: ChannelUsage, score_params: &Self::ScoreParams
) -> u64 {
self.0.channel_penalty_msat(candidate, usage, score_params)
}
}
#[cfg(c_bindings)]
impl<'a, T: Score> Writeable for MultiThreadedScoreLockWrite<'a, T> {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
self.0.write(writer)
}
}
#[cfg(c_bindings)]
impl<'a, T: 'a + Score> Deref for MultiThreadedScoreLockWrite<'a, T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.0.deref()
}
}
#[cfg(c_bindings)]
impl<'a, T: 'a + Score> DerefMut for MultiThreadedScoreLockWrite<'a, T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.0.deref_mut()
}
}
#[cfg(c_bindings)]
impl<'a, T: Score> ScoreUpdate for MultiThreadedScoreLockWrite<'a, T> {
fn payment_path_failed(&mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration) {
self.0.payment_path_failed(path, short_channel_id, duration_since_epoch)
}
fn payment_path_successful(&mut self, path: &Path, duration_since_epoch: Duration) {
self.0.payment_path_successful(path, duration_since_epoch)
}
fn probe_failed(&mut self, path: &Path, short_channel_id: u64, duration_since_epoch: Duration) {
self.0.probe_failed(path, short_channel_id, duration_since_epoch)
}
fn probe_successful(&mut self, path: &Path, duration_since_epoch: Duration) {
self.0.probe_successful(path, duration_since_epoch)
}
fn time_passed(&mut self, duration_since_epoch: Duration) {
self.0.time_passed(duration_since_epoch)
}
}
/// Proposed use of a channel passed as a parameter to [`ScoreLookUp::channel_penalty_msat`].
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ChannelUsage {
/// The amount to send through the channel, denominated in millisatoshis.
pub amount_msat: u64,
/// Total amount, denominated in millisatoshis, already allocated to send through the channel
/// as part of a multi-path payment.
pub inflight_htlc_msat: u64,
/// The effective capacity of the channel.
pub effective_capacity: EffectiveCapacity,
}
#[derive(Clone)]
/// [`ScoreLookUp`] implementation that uses a fixed penalty.
pub struct FixedPenaltyScorer {
penalty_msat: u64,
}
impl FixedPenaltyScorer {
/// Creates a new scorer using `penalty_msat`.
pub fn with_penalty(penalty_msat: u64) -> Self {
Self { penalty_msat }
}
}
impl ScoreLookUp for FixedPenaltyScorer {
type ScoreParams = ();
fn channel_penalty_msat(&self, _: &CandidateRouteHop, _: ChannelUsage, _score_params: &Self::ScoreParams) -> u64 {
self.penalty_msat
}
}
impl ScoreUpdate for FixedPenaltyScorer {
fn payment_path_failed(&mut self, _path: &Path, _short_channel_id: u64, _duration_since_epoch: Duration) {}
fn payment_path_successful(&mut self, _path: &Path, _duration_since_epoch: Duration) {}
fn probe_failed(&mut self, _path: &Path, _short_channel_id: u64, _duration_since_epoch: Duration) {}
fn probe_successful(&mut self, _path: &Path, _duration_since_epoch: Duration) {}
fn time_passed(&mut self, _duration_since_epoch: Duration) {}
}
impl Writeable for FixedPenaltyScorer {
#[inline]
fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
write_tlv_fields!(w, {});
Ok(())
}
}
impl ReadableArgs<u64> for FixedPenaltyScorer {
#[inline]
fn read<R: Read>(r: &mut R, penalty_msat: u64) -> Result<Self, DecodeError> {
read_tlv_fields!(r, {});
Ok(Self { penalty_msat })
}
}
/// [`ScoreLookUp`] implementation using channel success probability distributions.
///
/// Channels are tracked with upper and lower liquidity bounds - when an HTLC fails at a channel,
/// we learn that the upper-bound on the available liquidity is lower than the amount of the HTLC.
/// When a payment is forwarded through a channel (but fails later in the route), we learn the
/// lower-bound on the channel's available liquidity must be at least the value of the HTLC.
///
/// These bounds are then used to determine a success probability using the formula from
/// *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
/// and Stefan Richter [[1]] (i.e. `(upper_bound - payment_amount) / (upper_bound - lower_bound)`).
///
/// This probability is combined with the [`liquidity_penalty_multiplier_msat`] and
/// [`liquidity_penalty_amount_multiplier_msat`] parameters to calculate a concrete penalty in
/// milli-satoshis. The penalties, when added across all hops, have the property of being linear in
/// terms of the entire path's success probability. This allows the router to directly compare
/// penalties for different paths. See the documentation of those parameters for the exact formulas.
///
/// The liquidity bounds are decayed by halving them every [`liquidity_offset_half_life`].
///
/// Further, we track the history of our upper and lower liquidity bounds for each channel,
/// allowing us to assign a second penalty (using [`historical_liquidity_penalty_multiplier_msat`]
/// and [`historical_liquidity_penalty_amount_multiplier_msat`]) based on the same probability
/// formula, but using the history of a channel rather than our latest estimates for the liquidity
/// bounds.
///
/// [1]: https://arxiv.org/abs/2107.05322
/// [`liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_multiplier_msat
/// [`liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_amount_multiplier_msat
/// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
/// [`historical_liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_multiplier_msat
/// [`historical_liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_amount_multiplier_msat
pub struct ProbabilisticScorer<G: Deref<Target = NetworkGraph<L>>, L: Deref>
where L::Target: Logger {
decay_params: ProbabilisticScoringDecayParameters,
network_graph: G,
logger: L,
channel_liquidities: HashMap<u64, ChannelLiquidity>,
}
/// Parameters for configuring [`ProbabilisticScorer`].
///
/// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
/// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
///
/// The penalty applied to any channel by the [`ProbabilisticScorer`] is the sum of each of the
/// parameters here.
#[derive(Clone)]
pub struct ProbabilisticScoringFeeParameters {
/// A fixed penalty in msats to apply to each channel.
///
/// Default value: 500 msat
pub base_penalty_msat: u64,
/// A multiplier used with the payment amount to calculate a fixed penalty applied to each
/// channel, in excess of the [`base_penalty_msat`].
///
/// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
/// fees plus penalty) for large payments. The penalty is computed as the product of this
/// multiplier and `2^30`ths of the payment amount.
///
/// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
///
/// Default value: 8,192 msat
///
/// [`base_penalty_msat`]: Self::base_penalty_msat
pub base_penalty_amount_multiplier_msat: u64,
/// A multiplier used in conjunction with the negative `log10` of the channel's success
/// probability for a payment, as determined by our latest estimates of the channel's
/// liquidity, to determine the liquidity penalty.
///
/// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
/// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
/// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
/// lower bounding the success probability to `0.01`) when the amount falls within the
/// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
/// result in a `u64::max_value` penalty, however.
///
/// `-log10(success_probability) * liquidity_penalty_multiplier_msat`
///
/// Default value: 30,000 msat
///
/// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
pub liquidity_penalty_multiplier_msat: u64,
/// A multiplier used in conjunction with the payment amount and the negative `log10` of the
/// channel's success probability for the total amount flowing over a channel, as determined by
/// our latest estimates of the channel's liquidity, to determine the amount penalty.
///
/// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
/// fees plus penalty) for large payments. The penalty is computed as the product of this
/// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
/// success probability.
///
/// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
///
/// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
/// the amount will result in a penalty of the multiplier. And, as the success probability
/// decreases, the negative `log10` weighting will increase dramatically. For higher success
/// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
/// fall below `1`.
///
/// Default value: 192 msat
pub liquidity_penalty_amount_multiplier_msat: u64,
/// A multiplier used in conjunction with the negative `log10` of the channel's success
/// probability for the payment, as determined based on the history of our estimates of the
/// channel's available liquidity, to determine a penalty.
///
/// This penalty is similar to [`liquidity_penalty_multiplier_msat`], however, instead of using
/// only our latest estimate for the current liquidity available in the channel, it estimates
/// success probability based on the estimated liquidity available in the channel through
/// history. Specifically, every time we update our liquidity bounds on a given channel, we
/// track which of several buckets those bounds fall into, exponentially decaying the
/// probability of each bucket as new samples are added.
///
/// Default value: 10,000 msat
///
/// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
pub historical_liquidity_penalty_multiplier_msat: u64,
/// A multiplier used in conjunction with the payment amount and the negative `log10` of the
/// channel's success probability for the total amount flowing over a channel, as determined
/// based on the history of our estimates of the channel's available liquidity, to determine a
/// penalty.
///
/// The purpose of the amount penalty is to avoid having fees dominate the channel cost for
/// large payments. The penalty is computed as the product of this multiplier and `2^20`ths
/// of the payment amount, weighted by the negative `log10` of the success probability.
///
/// This penalty is similar to [`liquidity_penalty_amount_multiplier_msat`], however, instead
/// of using only our latest estimate for the current liquidity available in the channel, it
/// estimates success probability based on the estimated liquidity available in the channel
/// through history. Specifically, every time we update our liquidity bounds on a given
/// channel, we track which of several buckets those bounds fall into, exponentially decaying
/// the probability of each bucket as new samples are added.
///
/// Default value: 64 msat
///
/// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
pub historical_liquidity_penalty_amount_multiplier_msat: u64,
/// Manual penalties used for the given nodes. Allows to set a particular penalty for a given
/// node. Note that a manual penalty of `u64::max_value()` means the node would not ever be
/// considered during path finding.
///
/// This is not exported to bindings users
pub manual_node_penalties: HashMap<NodeId, u64>,
/// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
/// channel's capacity, (ie. htlc_maximum_msat >= 0.5 * channel_capacity) which makes us
/// prefer nodes with a smaller `htlc_maximum_msat`. We treat such nodes preferentially
/// as this makes balance discovery attacks harder to execute, thereby creating an incentive
/// to restrict `htlc_maximum_msat` and improve privacy.
///
/// Default value: 250 msat
pub anti_probing_penalty_msat: u64,
/// This penalty is applied when the total amount flowing over a channel exceeds our current
/// estimate of the channel's available liquidity. The total amount is the amount of the
/// current HTLC plus any HTLCs which we've sent over the same channel.
///
/// Note that in this case all other penalties, including the
/// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
/// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
/// applicable, are still included in the overall penalty.
///
/// If you wish to avoid creating paths with such channels entirely, setting this to a value of
/// `u64::max_value()` will guarantee that.
///
/// Default value: 1_0000_0000_000 msat (1 Bitcoin)
///
/// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
/// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
/// [`base_penalty_msat`]: Self::base_penalty_msat
/// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
pub considered_impossible_penalty_msat: u64,
/// In order to calculate most of the scores above, we must first convert a lower and upper
/// bound on the available liquidity in a channel into the probability that we think a payment
/// will succeed. That probability is derived from a Probability Density Function for where we
/// think the liquidity in a channel likely lies, given such bounds.
///
/// If this flag is set, that PDF is simply a constant - we assume that the actual available
/// liquidity in a channel is just as likely to be at any point between our lower and upper
/// bounds.
///
/// If this flag is *not* set, that PDF is `(x - 0.5*capacity) ^ 2`. That is, we use an
/// exponential curve which expects the liquidity of a channel to lie "at the edges". This
/// matches experimental results - most routing nodes do not aggressively rebalance their
/// channels and flows in the network are often unbalanced, leaving liquidity usually
/// unavailable.
///
/// Thus, for the "best" routes, leave this flag `false`. However, the flag does imply a number
/// of floating-point multiplications in the hottest routing code, which may lead to routing
/// performance degradation on some machines.
///
/// Default value: false
pub linear_success_probability: bool,
}
impl Default for ProbabilisticScoringFeeParameters {
fn default() -> Self {
Self {
base_penalty_msat: 500,
base_penalty_amount_multiplier_msat: 8192,
liquidity_penalty_multiplier_msat: 30_000,
liquidity_penalty_amount_multiplier_msat: 192,
manual_node_penalties: new_hash_map(),
anti_probing_penalty_msat: 250,
considered_impossible_penalty_msat: 1_0000_0000_000,
historical_liquidity_penalty_multiplier_msat: 10_000,
historical_liquidity_penalty_amount_multiplier_msat: 64,
linear_success_probability: false,
}
}
}
impl ProbabilisticScoringFeeParameters {
/// Marks the node with the given `node_id` as banned,
/// i.e it will be avoided during path finding.
pub fn add_banned(&mut self, node_id: &NodeId) {
self.manual_node_penalties.insert(*node_id, u64::max_value());
}
/// Marks all nodes in the given list as banned, i.e.,
/// they will be avoided during path finding.
pub fn add_banned_from_list(&mut self, node_ids: Vec<NodeId>) {
for id in node_ids {
self.manual_node_penalties.insert(id, u64::max_value());
}
}
/// Removes the node with the given `node_id` from the list of nodes to avoid.
pub fn remove_banned(&mut self, node_id: &NodeId) {
self.manual_node_penalties.remove(node_id);
}
/// Sets a manual penalty for the given node.
pub fn set_manual_penalty(&mut self, node_id: &NodeId, penalty: u64) {
self.manual_node_penalties.insert(*node_id, penalty);
}
/// Removes the node with the given `node_id` from the list of manual penalties.
pub fn remove_manual_penalty(&mut self, node_id: &NodeId) {
self.manual_node_penalties.remove(node_id);
}
/// Clears the list of manual penalties that are applied during path finding.
pub fn clear_manual_penalties(&mut self) {
self.manual_node_penalties = new_hash_map();
}
}
#[cfg(test)]
impl ProbabilisticScoringFeeParameters {
fn zero_penalty() -> Self {
Self {
base_penalty_msat: 0,
base_penalty_amount_multiplier_msat: 0,
liquidity_penalty_multiplier_msat: 0,
liquidity_penalty_amount_multiplier_msat: 0,
historical_liquidity_penalty_multiplier_msat: 0,
historical_liquidity_penalty_amount_multiplier_msat: 0,
manual_node_penalties: new_hash_map(),
anti_probing_penalty_msat: 0,
considered_impossible_penalty_msat: 0,
linear_success_probability: true,
}
}
}
/// Parameters for configuring [`ProbabilisticScorer`].
///
/// Used to configure decay parameters that are static throughout the lifetime of the scorer.
/// these decay parameters affect the score of the channel penalty and are not changed on a
/// per-route penalty cost call.
#[derive(Copy, Clone)]
pub struct ProbabilisticScoringDecayParameters {
/// If we aren't learning any new datapoints for a channel, the historical liquidity bounds
/// tracking can simply live on with increasingly stale data. Instead, when a channel has not
/// seen a liquidity estimate update for this amount of time, the historical datapoints are
/// decayed by half.
/// For an example of historical_no_updates_half_life being used see [`historical_estimated_channel_liquidity_probabilities`]
///
/// Note that after 16 or more half lives all historical data will be completely gone.
///
/// Default value: 14 days
///
/// [`historical_estimated_channel_liquidity_probabilities`]: ProbabilisticScorer::historical_estimated_channel_liquidity_probabilities
pub historical_no_updates_half_life: Duration,
/// Whenever this amount of time elapses since the last update to a channel's liquidity bounds,
/// the distance from the bounds to "zero" is cut in half. In other words, the lower-bound on
/// the available liquidity is halved and the upper-bound moves half-way to the channel's total
/// capacity.
///
/// Because halving the liquidity bounds grows the uncertainty on the channel's liquidity,
/// the penalty for an amount within the new bounds may change. See the [`ProbabilisticScorer`]
/// struct documentation for more info on the way the liquidity bounds are used.
///
/// For example, if the channel's capacity is 1 million sats, and the current upper and lower
/// liquidity bounds are 200,000 sats and 600,000 sats, after this amount of time the upper
/// and lower liquidity bounds will be decayed to 100,000 and 800,000 sats.
///
/// Default value: 6 hours
///
/// # Note
///
/// When not built with the `std` feature, time will never elapse. Therefore, the channel
/// liquidity knowledge will never decay except when the bounds cross.
pub liquidity_offset_half_life: Duration,
}
impl Default for ProbabilisticScoringDecayParameters {
fn default() -> Self {
Self {
liquidity_offset_half_life: Duration::from_secs(6 * 60 * 60),
historical_no_updates_half_life: Duration::from_secs(60 * 60 * 24 * 14),
}
}
}
#[cfg(test)]
impl ProbabilisticScoringDecayParameters {
fn zero_penalty() -> Self {
Self {
liquidity_offset_half_life: Duration::from_secs(6 * 60 * 60),
historical_no_updates_half_life: Duration::from_secs(60 * 60 * 24 * 14),
}
}
}
/// Accounting for channel liquidity balance uncertainty.
///
/// Direction is defined in terms of [`NodeId`] partial ordering, where the source node is the
/// first node in the ordering of the channel's counterparties. Thus, swapping the two liquidity
/// offset fields gives the opposite direction.
#[repr(C)] // Force the fields in memory to be in the order we specify
struct ChannelLiquidity {
/// Lower channel liquidity bound in terms of an offset from zero.
min_liquidity_offset_msat: u64,
/// Upper channel liquidity bound in terms of an offset from the effective capacity.
max_liquidity_offset_msat: u64,
liquidity_history: HistoricalLiquidityTracker,
/// Time when either liquidity bound was last modified as an offset since the unix epoch.
last_updated: Duration,
/// Time when the historical liquidity bounds were last modified as an offset against the unix
/// epoch.
offset_history_last_updated: Duration,
}
// Check that the liquidity HashMap's entries sit on round cache lines.
//
// Specifically, the first cache line will have the key, the liquidity offsets, and the total
// points tracked in the historical tracker.
//
// The next two cache lines will have the historical points, which we only access last during
// scoring, followed by the last_updated `Duration`s (which we do not need during scoring).
const _LIQUIDITY_MAP_SIZING_CHECK: usize = 192 - ::core::mem::size_of::<(u64, ChannelLiquidity)>();
const _LIQUIDITY_MAP_SIZING_CHECK_2: usize = ::core::mem::size_of::<(u64, ChannelLiquidity)>() - 192;
/// A snapshot of [`ChannelLiquidity`] in one direction assuming a certain channel capacity.
struct DirectedChannelLiquidity<L: Deref<Target = u64>, HT: Deref<Target = HistoricalLiquidityTracker>, T: Deref<Target = Duration>> {
min_liquidity_offset_msat: L,
max_liquidity_offset_msat: L,
liquidity_history: DirectedHistoricalLiquidityTracker<HT>,
capacity_msat: u64,
last_updated: T,
offset_history_last_updated: T,
}
impl<G: Deref<Target = NetworkGraph<L>>, L: Deref> ProbabilisticScorer<G, L> where L::Target: Logger {
/// Creates a new scorer using the given scoring parameters for sending payments from a node
/// through a network graph.
pub fn new(decay_params: ProbabilisticScoringDecayParameters, network_graph: G, logger: L) -> Self {
Self {
decay_params,
network_graph,
logger,
channel_liquidities: new_hash_map(),
}
}
#[cfg(test)]
fn with_channel(mut self, short_channel_id: u64, liquidity: ChannelLiquidity) -> Self {
assert!(self.channel_liquidities.insert(short_channel_id, liquidity).is_none());
self
}
/// Dump the contents of this scorer into the configured logger.
///
/// Note that this writes roughly one line per channel for which we have a liquidity estimate,
/// which may be a substantial amount of log output.
pub fn debug_log_liquidity_stats(&self) {
let graph = self.network_graph.read_only();
for (scid, liq) in self.channel_liquidities.iter() {
if let Some(chan_debug) = graph.channels().get(scid) {
let log_direction = |source, target| {
if let Some((directed_info, _)) = chan_debug.as_directed_to(target) {
let amt = directed_info.effective_capacity().as_msat();
let dir_liq = liq.as_directed(source, target, amt);
let min_buckets = &dir_liq.liquidity_history.min_liquidity_offset_history_buckets();
let max_buckets = &dir_liq.liquidity_history.max_liquidity_offset_history_buckets();
log_debug!(self.logger, core::concat!(
"Liquidity from {} to {} via {} is in the range ({}, {}).\n",
"\tHistorical min liquidity bucket relative probabilities:\n",
"\t\t{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}\n",
"\tHistorical max liquidity bucket relative probabilities:\n",
"\t\t{} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {} {}"),
source, target, scid, dir_liq.min_liquidity_msat(), dir_liq.max_liquidity_msat(),
min_buckets[ 0], min_buckets[ 1], min_buckets[ 2], min_buckets[ 3],
min_buckets[ 4], min_buckets[ 5], min_buckets[ 6], min_buckets[ 7],
min_buckets[ 8], min_buckets[ 9], min_buckets[10], min_buckets[11],
min_buckets[12], min_buckets[13], min_buckets[14], min_buckets[15],
min_buckets[16], min_buckets[17], min_buckets[18], min_buckets[19],
min_buckets[20], min_buckets[21], min_buckets[22], min_buckets[23],
min_buckets[24], min_buckets[25], min_buckets[26], min_buckets[27],
min_buckets[28], min_buckets[29], min_buckets[30], min_buckets[31],
// Note that the liquidity buckets are an offset from the edge, so we
// inverse the max order to get the probabilities from zero.
max_buckets[31], max_buckets[30], max_buckets[29], max_buckets[28],
max_buckets[27], max_buckets[26], max_buckets[25], max_buckets[24],
max_buckets[23], max_buckets[22], max_buckets[21], max_buckets[20],
max_buckets[19], max_buckets[18], max_buckets[17], max_buckets[16],
max_buckets[15], max_buckets[14], max_buckets[13], max_buckets[12],
max_buckets[11], max_buckets[10], max_buckets[ 9], max_buckets[ 8],
max_buckets[ 7], max_buckets[ 6], max_buckets[ 5], max_buckets[ 4],
max_buckets[ 3], max_buckets[ 2], max_buckets[ 1], max_buckets[ 0]);
} else {
log_debug!(self.logger, "No amount known for SCID {} from {:?} to {:?}", scid, source, target);
}
};
log_direction(&chan_debug.node_one, &chan_debug.node_two);
log_direction(&chan_debug.node_two, &chan_debug.node_one);
} else {
log_debug!(self.logger, "No network graph entry for SCID {}", scid);
}
}
}
/// Query the estimated minimum and maximum liquidity available for sending a payment over the
/// channel with `scid` towards the given `target` node.
pub fn estimated_channel_liquidity_range(&self, scid: u64, target: &NodeId) -> Option<(u64, u64)> {
let graph = self.network_graph.read_only();
if let Some(chan) = graph.channels().get(&scid) {
if let Some(liq) = self.channel_liquidities.get(&scid) {
if let Some((directed_info, source)) = chan.as_directed_to(target) {
let amt = directed_info.effective_capacity().as_msat();
let dir_liq = liq.as_directed(source, target, amt);
return Some((dir_liq.min_liquidity_msat(), dir_liq.max_liquidity_msat()));
}
}
}
None
}
/// Query the historical estimated minimum and maximum liquidity available for sending a
/// payment over the channel with `scid` towards the given `target` node.
///
/// Returns two sets of 32 buckets. The first set describes the lower-bound liquidity history,
/// the second set describes the upper-bound liquidity history. Each bucket describes the
/// relative frequency at which we've seen a liquidity bound in the bucket's range relative to
/// the channel's total capacity, on an arbitrary scale. Because the values are slowly decayed,
/// more recent data points are weighted more heavily than older datapoints.
///
/// Note that the range of each bucket varies by its location to provide more granular results
/// at the edges of a channel's capacity, where it is more likely to sit.
///
/// When scoring, the estimated probability that an upper-/lower-bound lies in a given bucket
/// is calculated by dividing that bucket's value with the total value of all buckets.
///
/// For example, using a lower bucket count for illustrative purposes, a value of
/// `[0, 0, 0, ..., 0, 32]` indicates that we believe the probability of a bound being very
/// close to the channel's capacity to be 100%, and have never (recently) seen it in any other
/// bucket. A value of `[31, 0, 0, ..., 0, 0, 32]` indicates we've seen the bound being both
/// in the top and bottom bucket, and roughly with similar (recent) frequency.
///
/// Because the datapoints are decayed slowly over time, values will eventually return to
/// `Some(([0; 32], [0; 32]))` or `None` if no data remains for a channel.
///
/// In order to fetch a single success probability from the buckets provided here, as used in
/// the scoring model, see [`Self::historical_estimated_payment_success_probability`].
pub fn historical_estimated_channel_liquidity_probabilities(&self, scid: u64, target: &NodeId)
-> Option<([u16; 32], [u16; 32])> {
let graph = self.network_graph.read_only();
if let Some(chan) = graph.channels().get(&scid) {
if let Some(liq) = self.channel_liquidities.get(&scid) {
if let Some((directed_info, source)) = chan.as_directed_to(target) {
let amt = directed_info.effective_capacity().as_msat();
let dir_liq = liq.as_directed(source, target, amt);
let min_buckets = *dir_liq.liquidity_history.min_liquidity_offset_history_buckets();
let mut max_buckets = *dir_liq.liquidity_history.max_liquidity_offset_history_buckets();
// Note that the liquidity buckets are an offset from the edge, so we inverse
// the max order to get the probabilities from zero.
max_buckets.reverse();
return Some((min_buckets, max_buckets));
}
}
}
None
}
/// Query the probability of payment success sending the given `amount_msat` over the channel
/// with `scid` towards the given `target` node, based on the historical estimated liquidity
/// bounds.
///
/// These are the same bounds as returned by
/// [`Self::historical_estimated_channel_liquidity_probabilities`] (but not those returned by
/// [`Self::estimated_channel_liquidity_range`]).
pub fn historical_estimated_payment_success_probability(
&self, scid: u64, target: &NodeId, amount_msat: u64, params: &ProbabilisticScoringFeeParameters)
-> Option<f64> {
let graph = self.network_graph.read_only();
if let Some(chan) = graph.channels().get(&scid) {
if let Some(liq) = self.channel_liquidities.get(&scid) {
if let Some((directed_info, source)) = chan.as_directed_to(target) {
let capacity_msat = directed_info.effective_capacity().as_msat();
let dir_liq = liq.as_directed(source, target, capacity_msat);
return dir_liq.liquidity_history.calculate_success_probability_times_billion(
¶ms, amount_msat, capacity_msat
).map(|p| p as f64 / (1024 * 1024 * 1024) as f64);
}
}
}
None
}
}
impl ChannelLiquidity {
fn new(last_updated: Duration) -> Self {
Self {
min_liquidity_offset_msat: 0,
max_liquidity_offset_msat: 0,
liquidity_history: HistoricalLiquidityTracker::new(),
last_updated,
offset_history_last_updated: last_updated,
}
}
/// Returns a view of the channel liquidity directed from `source` to `target` assuming
/// `capacity_msat`.
fn as_directed(
&self, source: &NodeId, target: &NodeId, capacity_msat: u64,
) -> DirectedChannelLiquidity<&u64, &HistoricalLiquidityTracker, &Duration> {
let source_less_than_target = source < target;
let (min_liquidity_offset_msat, max_liquidity_offset_msat) =