b317cd238390736d48a81c284551e8443fa8201e
[ldk-java] / src / main / java / org / ldk / structs / ProbabilisticScorer.java
1 package org.ldk.structs;
2
3 import org.ldk.impl.bindings;
4 import org.ldk.enums.*;
5 import org.ldk.util.*;
6 import java.util.Arrays;
7 import java.lang.ref.Reference;
8 import javax.annotation.Nullable;
9
10
11 /**
12  * [`ScoreLookUp`] implementation using channel success probability distributions.
13  * 
14  * Channels are tracked with upper and lower liquidity bounds - when an HTLC fails at a channel,
15  * we learn that the upper-bound on the available liquidity is lower than the amount of the HTLC.
16  * When a payment is forwarded through a channel (but fails later in the route), we learn the
17  * lower-bound on the channel's available liquidity must be at least the value of the HTLC.
18  * 
19  * These bounds are then used to determine a success probability using the formula from
20  * Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
21  * and Stefan Richter [[1]] (i.e. `(upper_bound - payment_amount) / (upper_bound - lower_bound)`).
22  * 6762, 1070
23  * This probability is combined with the [`liquidity_penalty_multiplier_msat`] and
24  * [`liquidity_penalty_amount_multiplier_msat`] parameters to calculate a concrete penalty in
25  * milli-satoshis. The penalties, when added across all hops, have the property of being linear in
26  * terms of the entire path's success probability. This allows the router to directly compare
27  * penalties for different paths. See the documentation of those parameters for the exact formulas.
28  * 
29  * The liquidity bounds are decayed by halving them every [`liquidity_offset_half_life`].
30  * 
31  * Further, we track the history of our upper and lower liquidity bounds for each channel,
32  * allowing us to assign a second penalty (using [`historical_liquidity_penalty_multiplier_msat`]
33  * and [`historical_liquidity_penalty_amount_multiplier_msat`]) based on the same probability
34  * formula, but using the history of a channel rather than our latest estimates for the liquidity
35  * bounds.
36  * 
37  * # Note
38  * 
39  * Mixing the `no-std` feature between serialization and deserialization results in undefined
40  * behavior.
41  * 
42  * [1]: https://arxiv.org/abs/2107.05322
43  * [`liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_multiplier_msat
44  * [`liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_amount_multiplier_msat
45  * [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
46  * [`historical_liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_multiplier_msat
47  * [`historical_liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_amount_multiplier_msat
48  */
49 @SuppressWarnings("unchecked") // We correctly assign various generic arrays
50 public class ProbabilisticScorer extends CommonBase {
51         ProbabilisticScorer(Object _dummy, long ptr) { super(ptr); }
52         @Override @SuppressWarnings("deprecation")
53         protected void finalize() throws Throwable {
54                 super.finalize();
55                 if (ptr != 0) { bindings.ProbabilisticScorer_free(ptr); }
56         }
57
58         /**
59          * Creates a new scorer using the given scoring parameters for sending payments from a node
60          * through a network graph.
61          */
62         public static ProbabilisticScorer of(org.ldk.structs.ProbabilisticScoringDecayParameters decay_params, org.ldk.structs.NetworkGraph network_graph, org.ldk.structs.Logger logger) {
63                 long ret = bindings.ProbabilisticScorer_new(decay_params == null ? 0 : decay_params.ptr, network_graph == null ? 0 : network_graph.ptr, logger.ptr);
64                 Reference.reachabilityFence(decay_params);
65                 Reference.reachabilityFence(network_graph);
66                 Reference.reachabilityFence(logger);
67                 if (ret >= 0 && ret <= 4096) { return null; }
68                 org.ldk.structs.ProbabilisticScorer ret_hu_conv = null; if (ret < 0 || ret > 4096) { ret_hu_conv = new org.ldk.structs.ProbabilisticScorer(null, ret); }
69                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(ret_hu_conv); };
70                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(decay_params); };
71                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(network_graph); };
72                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(logger); };
73                 return ret_hu_conv;
74         }
75
76         /**
77          * Dump the contents of this scorer into the configured logger.
78          * 
79          * Note that this writes roughly one line per channel for which we have a liquidity estimate,
80          * which may be a substantial amount of log output.
81          */
82         public void debug_log_liquidity_stats() {
83                 bindings.ProbabilisticScorer_debug_log_liquidity_stats(this.ptr);
84                 Reference.reachabilityFence(this);
85         }
86
87         /**
88          * Query the estimated minimum and maximum liquidity available for sending a payment over the
89          * channel with `scid` towards the given `target` node.
90          */
91         public Option_C2Tuple_u64u64ZZ estimated_channel_liquidity_range(long scid, org.ldk.structs.NodeId target) {
92                 long ret = bindings.ProbabilisticScorer_estimated_channel_liquidity_range(this.ptr, scid, target == null ? 0 : target.ptr);
93                 Reference.reachabilityFence(this);
94                 Reference.reachabilityFence(scid);
95                 Reference.reachabilityFence(target);
96                 if (ret >= 0 && ret <= 4096) { return null; }
97                 org.ldk.structs.Option_C2Tuple_u64u64ZZ ret_hu_conv = org.ldk.structs.Option_C2Tuple_u64u64ZZ.constr_from_ptr(ret);
98                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(this); };
99                 if (this != null) { this.ptrs_to.add(target); };
100                 return ret_hu_conv;
101         }
102
103         /**
104          * Query the historical estimated minimum and maximum liquidity available for sending a
105          * payment over the channel with `scid` towards the given `target` node.
106          * 
107          * Returns two sets of 32 buckets. The first set describes the lower-bound liquidity history,
108          * the second set describes the upper-bound liquidity history. Each bucket describes the
109          * relative frequency at which we've seen a liquidity bound in the bucket's range relative to
110          * the channel's total capacity, on an arbitrary scale. Because the values are slowly decayed,
111          * more recent data points are weighted more heavily than older datapoints.
112          * 
113          * Note that the range of each bucket varies by its location to provide more granular results
114          * at the edges of a channel's capacity, where it is more likely to sit.
115          * 
116          * When scoring, the estimated probability that an upper-/lower-bound lies in a given bucket
117          * is calculated by dividing that bucket's value with the total value of all buckets.
118          * 
119          * For example, using a lower bucket count for illustrative purposes, a value of
120          * `[0, 0, 0, ..., 0, 32]` indicates that we believe the probability of a bound being very
121          * close to the channel's capacity to be 100%, and have never (recently) seen it in any other
122          * bucket. A value of `[31, 0, 0, ..., 0, 0, 32]` indicates we've seen the bound being both
123          * in the top and bottom bucket, and roughly with similar (recent) frequency.
124          * 
125          * Because the datapoints are decayed slowly over time, values will eventually return to
126          * `Some(([1; 32], [1; 32]))` and then to `None` once no datapoints remain.
127          * 
128          * In order to fetch a single success probability from the buckets provided here, as used in
129          * the scoring model, see [`Self::historical_estimated_payment_success_probability`].
130          */
131         public Option_C2Tuple_ThirtyTwoU16sThirtyTwoU16sZZ historical_estimated_channel_liquidity_probabilities(long scid, org.ldk.structs.NodeId target) {
132                 long ret = bindings.ProbabilisticScorer_historical_estimated_channel_liquidity_probabilities(this.ptr, scid, target == null ? 0 : target.ptr);
133                 Reference.reachabilityFence(this);
134                 Reference.reachabilityFence(scid);
135                 Reference.reachabilityFence(target);
136                 if (ret >= 0 && ret <= 4096) { return null; }
137                 org.ldk.structs.Option_C2Tuple_ThirtyTwoU16sThirtyTwoU16sZZ ret_hu_conv = org.ldk.structs.Option_C2Tuple_ThirtyTwoU16sThirtyTwoU16sZZ.constr_from_ptr(ret);
138                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(this); };
139                 if (this != null) { this.ptrs_to.add(target); };
140                 return ret_hu_conv;
141         }
142
143         /**
144          * Query the probability of payment success sending the given `amount_msat` over the channel
145          * with `scid` towards the given `target` node, based on the historical estimated liquidity
146          * bounds.
147          * 
148          * These are the same bounds as returned by
149          * [`Self::historical_estimated_channel_liquidity_probabilities`] (but not those returned by
150          * [`Self::estimated_channel_liquidity_range`]).
151          */
152         public Option_f64Z historical_estimated_payment_success_probability(long scid, org.ldk.structs.NodeId target, long amount_msat, org.ldk.structs.ProbabilisticScoringFeeParameters params) {
153                 long ret = bindings.ProbabilisticScorer_historical_estimated_payment_success_probability(this.ptr, scid, target == null ? 0 : target.ptr, amount_msat, params == null ? 0 : params.ptr);
154                 Reference.reachabilityFence(this);
155                 Reference.reachabilityFence(scid);
156                 Reference.reachabilityFence(target);
157                 Reference.reachabilityFence(amount_msat);
158                 Reference.reachabilityFence(params);
159                 if (ret >= 0 && ret <= 4096) { return null; }
160                 org.ldk.structs.Option_f64Z ret_hu_conv = org.ldk.structs.Option_f64Z.constr_from_ptr(ret);
161                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(this); };
162                 if (this != null) { this.ptrs_to.add(target); };
163                 if (this != null) { this.ptrs_to.add(params); };
164                 return ret_hu_conv;
165         }
166
167         /**
168          * Constructs a new ScoreLookUp which calls the relevant methods on this_arg.
169          * This copies the `inner` pointer in this_arg and thus the returned ScoreLookUp must be freed before this_arg is
170          */
171         public ScoreLookUp as_ScoreLookUp() {
172                 long ret = bindings.ProbabilisticScorer_as_ScoreLookUp(this.ptr);
173                 Reference.reachabilityFence(this);
174                 if (ret >= 0 && ret <= 4096) { return null; }
175                 ScoreLookUp ret_hu_conv = new ScoreLookUp(null, ret);
176                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(this); };
177                 return ret_hu_conv;
178         }
179
180         /**
181          * Constructs a new ScoreUpdate which calls the relevant methods on this_arg.
182          * This copies the `inner` pointer in this_arg and thus the returned ScoreUpdate must be freed before this_arg is
183          */
184         public ScoreUpdate as_ScoreUpdate() {
185                 long ret = bindings.ProbabilisticScorer_as_ScoreUpdate(this.ptr);
186                 Reference.reachabilityFence(this);
187                 if (ret >= 0 && ret <= 4096) { return null; }
188                 ScoreUpdate ret_hu_conv = new ScoreUpdate(null, ret);
189                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(this); };
190                 return ret_hu_conv;
191         }
192
193         /**
194          * Constructs a new Score which calls the relevant methods on this_arg.
195          * This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
196          */
197         public Score as_Score() {
198                 long ret = bindings.ProbabilisticScorer_as_Score(this.ptr);
199                 Reference.reachabilityFence(this);
200                 if (ret >= 0 && ret <= 4096) { return null; }
201                 Score ret_hu_conv = new Score(null, ret);
202                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(this); };
203                 return ret_hu_conv;
204         }
205
206         /**
207          * Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
208          */
209         public byte[] write() {
210                 byte[] ret = bindings.ProbabilisticScorer_write(this.ptr);
211                 Reference.reachabilityFence(this);
212                 return ret;
213         }
214
215         /**
216          * Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
217          */
218         public static Result_ProbabilisticScorerDecodeErrorZ read(byte[] ser, org.ldk.structs.ProbabilisticScoringDecayParameters arg_a, org.ldk.structs.NetworkGraph arg_b, org.ldk.structs.Logger arg_c) {
219                 long ret = bindings.ProbabilisticScorer_read(ser, arg_a == null ? 0 : arg_a.ptr, arg_b == null ? 0 : arg_b.ptr, arg_c.ptr);
220                 Reference.reachabilityFence(ser);
221                 Reference.reachabilityFence(arg_a);
222                 Reference.reachabilityFence(arg_b);
223                 Reference.reachabilityFence(arg_c);
224                 if (ret >= 0 && ret <= 4096) { return null; }
225                 Result_ProbabilisticScorerDecodeErrorZ ret_hu_conv = Result_ProbabilisticScorerDecodeErrorZ.constr_from_ptr(ret);
226                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(arg_a); };
227                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(arg_b); };
228                 if (ret_hu_conv != null) { ret_hu_conv.ptrs_to.add(arg_c); };
229                 return ret_hu_conv;
230         }
231
232 }