1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
9 //! Utilities for scoring payment channels.
11 //! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path
12 //! finding when a custom [`Score`] implementation is not needed.
17 //! # extern crate bitcoin;
19 //! # use lightning::routing::gossip::NetworkGraph;
20 //! # use lightning::routing::router::{RouteParameters, find_route};
21 //! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringFeeParameters, ProbabilisticScoringDecayParameters};
22 //! # use lightning::sign::KeysManager;
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use bitcoin::secp256k1::PublicKey;
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! # fn log(&self, record: &Record) { unimplemented!() }
30 //! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph<&FakeLogger>) {
31 //! # let logger = FakeLogger {};
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringFeeParameters::default();
35 //! let decay_params = ProbabilisticScoringDecayParameters::default();
36 //! let scorer = ProbabilisticScorer::new(decay_params, &network_graph, &logger);
38 //! // Or use custom channel penalties.
39 //! let params = ProbabilisticScoringFeeParameters {
40 //! \tliquidity_penalty_multiplier_msat: 2 * 1000,
41 //! \t..ProbabilisticScoringFeeParameters::default()
43 //! let decay_params = ProbabilisticScoringDecayParameters::default();
44 //! let scorer = ProbabilisticScorer::new(decay_params, &network_graph, &logger);
45 //! # let random_seed_bytes = [42u8; 32];
47 //! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer, ¶ms, &random_seed_bytes);
53 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
54 //! different types and thus is undefined.
56 //! [`find_route`]: crate::routing::router::find_route
58 use alloc::str::FromStr;
59 use core::ffi::c_void;
60 use core::convert::Infallible;
61 use bitcoin::hashes::Hash;
62 use crate::c_types::*;
63 #[cfg(feature="no-std")]
64 use alloc::{vec::Vec, boxed::Box};
66 /// An interface used to score payment channels for path finding.
68 ///\tScoring is in terms of fees willing to be paid in order to avoid routing through a channel.
71 /// An opaque pointer which is passed to your function implementations as an argument.
72 /// This has no meaning in the LDK, and can be NULL or any other value.
73 pub this_arg: *mut c_void,
74 /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
75 /// given channel in the direction from `source` to `target`.
77 /// The channel's capacity (less any other MPP parts that are also being considered for use in
78 /// the same payment) is given by `capacity_msat`. It may be determined from various sources
79 /// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near
80 /// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount.
81 /// Thus, implementations should be overflow-safe.
82 pub channel_penalty_msat: extern "C" fn (this_arg: *const c_void, short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64,
83 /// Handles updating channel penalties after failing to route through a channel.
84 pub payment_path_failed: extern "C" fn (this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, short_channel_id: u64),
85 /// Handles updating channel penalties after successfully routing along a path.
86 pub payment_path_successful: extern "C" fn (this_arg: *mut c_void, path: &crate::lightning::routing::router::Path),
87 /// Handles updating channel penalties after a probe over the given path failed.
88 pub probe_failed: extern "C" fn (this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, short_channel_id: u64),
89 /// Handles updating channel penalties after a probe over the given path succeeded.
90 pub probe_successful: extern "C" fn (this_arg: *mut c_void, path: &crate::lightning::routing::router::Path),
91 /// Serialize the object into a byte array
92 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
93 /// Frees any resources associated with this object given its this_arg pointer.
94 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
95 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
97 unsafe impl Send for Score {}
98 unsafe impl Sync for Score {}
100 pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score {
102 this_arg: orig.this_arg,
103 channel_penalty_msat: Clone::clone(&orig.channel_penalty_msat),
104 payment_path_failed: Clone::clone(&orig.payment_path_failed),
105 payment_path_successful: Clone::clone(&orig.payment_path_successful),
106 probe_failed: Clone::clone(&orig.probe_failed),
107 probe_successful: Clone::clone(&orig.probe_successful),
108 write: Clone::clone(&orig.write),
109 free: Clone::clone(&orig.free),
112 impl lightning::util::ser::Writeable for Score {
113 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
114 let vec = (self.write)(self.this_arg);
115 w.write_all(vec.as_slice())
119 use lightning::routing::scoring::Score as rustScore;
120 impl rustScore for Score {
121 fn channel_penalty_msat(&self, mut short_channel_id: u64, mut source: &lightning::routing::gossip::NodeId, mut target: &lightning::routing::gossip::NodeId, mut usage: lightning::routing::scoring::ChannelUsage, mut score_params: &lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
122 let mut ret = (self.channel_penalty_msat)(self.this_arg, short_channel_id, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((source as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((target as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, crate::lightning::routing::scoring::ChannelUsage { inner: ObjOps::heap_alloc(usage), is_owned: true }, &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters { inner: unsafe { ObjOps::nonnull_ptr_to_inner((score_params as *const lightning::routing::scoring::ProbabilisticScoringFeeParameters<>) as *mut _) }, is_owned: false });
125 fn payment_path_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64) {
126 (self.payment_path_failed)(self.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false }, short_channel_id)
128 fn payment_path_successful(&mut self, mut path: &lightning::routing::router::Path) {
129 (self.payment_path_successful)(self.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false })
131 fn probe_failed(&mut self, mut path: &lightning::routing::router::Path, mut short_channel_id: u64) {
132 (self.probe_failed)(self.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false }, short_channel_id)
134 fn probe_successful(&mut self, mut path: &lightning::routing::router::Path) {
135 (self.probe_successful)(self.this_arg, &crate::lightning::routing::router::Path { inner: unsafe { ObjOps::nonnull_ptr_to_inner((path as *const lightning::routing::router::Path<>) as *mut _) }, is_owned: false })
139 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
140 // directly as a Deref trait in higher-level structs:
141 impl core::ops::Deref for Score {
143 fn deref(&self) -> &Self {
147 /// Calls the free function if one is set
149 pub extern "C" fn Score_free(this_ptr: Score) { }
150 impl Drop for Score {
152 if let Some(f) = self.free {
157 /// A scorer that is accessed under a lock.
159 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
160 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
161 /// implementations. Internal locking would be detrimental to route finding performance and could
162 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
164 /// [`find_route`]: crate::routing::router::find_route
166 pub struct LockableScore {
167 /// An opaque pointer which is passed to your function implementations as an argument.
168 /// This has no meaning in the LDK, and can be NULL or any other value.
169 pub this_arg: *mut c_void,
170 /// Returns the locked scorer.
171 pub lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::Score,
172 /// Frees any resources associated with this object given its this_arg pointer.
173 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
174 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
176 unsafe impl Send for LockableScore {}
177 unsafe impl Sync for LockableScore {}
179 pub(crate) extern "C" fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
181 this_arg: orig.this_arg,
182 lock: Clone::clone(&orig.lock),
183 free: Clone::clone(&orig.free),
187 use lightning::routing::scoring::LockableScore as rustLockableScore;
188 impl<'a> rustLockableScore<'a> for LockableScore {
189 type Locked = crate::lightning::routing::scoring::Score;
190 fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
191 let mut ret = (self.lock)(self.this_arg);
196 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
197 // directly as a Deref trait in higher-level structs:
198 impl core::ops::Deref for LockableScore {
200 fn deref(&self) -> &Self {
204 /// Calls the free function if one is set
206 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
207 impl Drop for LockableScore {
209 if let Some(f) = self.free {
214 /// Refers to a scorer that is accessible under lock and also writeable to disk
216 /// We need this trait to be able to pass in a scorer to `lightning-background-processor` that will enable us to
217 /// use the Persister to persist it.
219 pub struct WriteableScore {
220 /// An opaque pointer which is passed to your function implementations as an argument.
221 /// This has no meaning in the LDK, and can be NULL or any other value.
222 pub this_arg: *mut c_void,
223 /// Implementation of LockableScore for this object.
224 pub LockableScore: crate::lightning::routing::scoring::LockableScore,
225 /// Serialize the object into a byte array
226 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
227 /// Frees any resources associated with this object given its this_arg pointer.
228 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
229 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
231 unsafe impl Send for WriteableScore {}
232 unsafe impl Sync for WriteableScore {}
234 pub(crate) extern "C" fn WriteableScore_clone_fields(orig: &WriteableScore) -> WriteableScore {
236 this_arg: orig.this_arg,
237 LockableScore: crate::lightning::routing::scoring::LockableScore_clone_fields(&orig.LockableScore),
238 write: Clone::clone(&orig.write),
239 free: Clone::clone(&orig.free),
242 impl<'a> lightning::routing::scoring::LockableScore<'a> for WriteableScore {
243 type Locked = crate::lightning::routing::scoring::Score;
244 fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
245 let mut ret = (self.LockableScore.lock)(self.LockableScore.this_arg);
249 impl lightning::util::ser::Writeable for WriteableScore {
250 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
251 let vec = (self.write)(self.this_arg);
252 w.write_all(vec.as_slice())
256 use lightning::routing::scoring::WriteableScore as rustWriteableScore;
257 impl<'a> rustWriteableScore<'a> for WriteableScore {
260 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
261 // directly as a Deref trait in higher-level structs:
262 impl core::ops::Deref for WriteableScore {
264 fn deref(&self) -> &Self {
268 /// Calls the free function if one is set
270 pub extern "C" fn WriteableScore_free(this_ptr: WriteableScore) { }
271 impl Drop for WriteableScore {
273 if let Some(f) = self.free {
279 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
280 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
282 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
285 pub struct MultiThreadedLockableScore {
286 /// A pointer to the opaque Rust object.
288 /// Nearly everywhere, inner must be non-null, however in places where
289 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
290 pub inner: *mut nativeMultiThreadedLockableScore,
291 /// Indicates that this is the only struct which contains the same pointer.
293 /// Rust functions which take ownership of an object provided via an argument require
294 /// this to be true and invalidate the object pointed to by inner.
298 impl Drop for MultiThreadedLockableScore {
300 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
301 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
305 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
307 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
309 /// Used only if an object of this type is returned as a trait impl by a method
310 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
311 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore) };
314 impl MultiThreadedLockableScore {
315 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
316 unsafe { &*ObjOps::untweak_ptr(self.inner) }
318 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
319 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
321 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
322 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
323 assert!(self.is_owned);
324 let ret = ObjOps::untweak_ptr(self.inner);
325 self.inner = core::ptr::null_mut();
329 impl From<nativeMultiThreadedLockableScore> for crate::lightning::routing::scoring::LockableScore {
330 fn from(obj: nativeMultiThreadedLockableScore) -> Self {
331 let mut rust_obj = MultiThreadedLockableScore { inner: ObjOps::heap_alloc(obj), is_owned: true };
332 let mut ret = MultiThreadedLockableScore_as_LockableScore(&rust_obj);
333 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
334 rust_obj.inner = core::ptr::null_mut();
335 ret.free = Some(MultiThreadedLockableScore_free_void);
339 /// Constructs a new LockableScore which calls the relevant methods on this_arg.
340 /// This copies the `inner` pointer in this_arg and thus the returned LockableScore must be freed before this_arg is
342 pub extern "C" fn MultiThreadedLockableScore_as_LockableScore(this_arg: &MultiThreadedLockableScore) -> crate::lightning::routing::scoring::LockableScore {
343 crate::lightning::routing::scoring::LockableScore {
344 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
346 lock: MultiThreadedLockableScore_LockableScore_lock,
351 extern "C" fn MultiThreadedLockableScore_LockableScore_lock(this_arg: *const c_void) -> crate::lightning::routing::scoring::Score {
352 let mut ret = <nativeMultiThreadedLockableScore as lightning::routing::scoring::LockableScore<>>::lock(unsafe { &mut *(this_arg as *mut nativeMultiThreadedLockableScore) }, );
357 /// Serialize the MultiThreadedLockableScore object into a byte array which can be read by MultiThreadedLockableScore_read
358 pub extern "C" fn MultiThreadedLockableScore_write(obj: &crate::lightning::routing::scoring::MultiThreadedLockableScore) -> crate::c_types::derived::CVec_u8Z {
359 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
362 pub(crate) extern "C" fn MultiThreadedLockableScore_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
363 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedLockableScore) })
365 impl From<nativeMultiThreadedLockableScore> for crate::lightning::routing::scoring::WriteableScore {
366 fn from(obj: nativeMultiThreadedLockableScore) -> Self {
367 let mut rust_obj = MultiThreadedLockableScore { inner: ObjOps::heap_alloc(obj), is_owned: true };
368 let mut ret = MultiThreadedLockableScore_as_WriteableScore(&rust_obj);
369 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
370 rust_obj.inner = core::ptr::null_mut();
371 ret.free = Some(MultiThreadedLockableScore_free_void);
375 /// Constructs a new WriteableScore which calls the relevant methods on this_arg.
376 /// This copies the `inner` pointer in this_arg and thus the returned WriteableScore must be freed before this_arg is
378 pub extern "C" fn MultiThreadedLockableScore_as_WriteableScore(this_arg: &MultiThreadedLockableScore) -> crate::lightning::routing::scoring::WriteableScore {
379 crate::lightning::routing::scoring::WriteableScore {
380 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
382 LockableScore: crate::lightning::routing::scoring::LockableScore {
383 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
385 lock: MultiThreadedLockableScore_LockableScore_lock,
387 write: MultiThreadedLockableScore_write_void,
392 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
395 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore {
396 let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
397 crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
401 use lightning::routing::scoring::MultiThreadedScoreLock as nativeMultiThreadedScoreLockImport;
402 pub(crate) type nativeMultiThreadedScoreLock = nativeMultiThreadedScoreLockImport<'static, crate::lightning::routing::scoring::Score>;
404 /// A locked `MultiThreadedLockableScore`.
407 pub struct MultiThreadedScoreLock {
408 /// A pointer to the opaque Rust object.
410 /// Nearly everywhere, inner must be non-null, however in places where
411 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
412 pub inner: *mut nativeMultiThreadedScoreLock,
413 /// Indicates that this is the only struct which contains the same pointer.
415 /// Rust functions which take ownership of an object provided via an argument require
416 /// this to be true and invalidate the object pointed to by inner.
420 impl Drop for MultiThreadedScoreLock {
422 if self.is_owned && !<*mut nativeMultiThreadedScoreLock>::is_null(self.inner) {
423 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
427 /// Frees any resources used by the MultiThreadedScoreLock, if is_owned is set and inner is non-NULL.
429 pub extern "C" fn MultiThreadedScoreLock_free(this_obj: MultiThreadedScoreLock) { }
431 /// Used only if an object of this type is returned as a trait impl by a method
432 pub(crate) extern "C" fn MultiThreadedScoreLock_free_void(this_ptr: *mut c_void) {
433 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeMultiThreadedScoreLock) };
436 impl MultiThreadedScoreLock {
437 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedScoreLock {
438 unsafe { &*ObjOps::untweak_ptr(self.inner) }
440 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedScoreLock {
441 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
443 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
444 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedScoreLock {
445 assert!(self.is_owned);
446 let ret = ObjOps::untweak_ptr(self.inner);
447 self.inner = core::ptr::null_mut();
452 /// Serialize the MultiThreadedScoreLock object into a byte array which can be read by MultiThreadedScoreLock_read
453 pub extern "C" fn MultiThreadedScoreLock_write(obj: &crate::lightning::routing::scoring::MultiThreadedScoreLock) -> crate::c_types::derived::CVec_u8Z {
454 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
457 pub(crate) extern "C" fn MultiThreadedScoreLock_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
458 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedScoreLock) })
460 impl From<nativeMultiThreadedScoreLock> for crate::lightning::routing::scoring::Score {
461 fn from(obj: nativeMultiThreadedScoreLock) -> Self {
462 let mut rust_obj = MultiThreadedScoreLock { inner: ObjOps::heap_alloc(obj), is_owned: true };
463 let mut ret = MultiThreadedScoreLock_as_Score(&rust_obj);
464 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
465 rust_obj.inner = core::ptr::null_mut();
466 ret.free = Some(MultiThreadedScoreLock_free_void);
470 /// Constructs a new Score which calls the relevant methods on this_arg.
471 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
473 pub extern "C" fn MultiThreadedScoreLock_as_Score(this_arg: &MultiThreadedScoreLock) -> crate::lightning::routing::scoring::Score {
474 crate::lightning::routing::scoring::Score {
475 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
477 channel_penalty_msat: MultiThreadedScoreLock_Score_channel_penalty_msat,
478 payment_path_failed: MultiThreadedScoreLock_Score_payment_path_failed,
479 payment_path_successful: MultiThreadedScoreLock_Score_payment_path_successful,
480 probe_failed: MultiThreadedScoreLock_Score_probe_failed,
481 probe_successful: MultiThreadedScoreLock_Score_probe_successful,
482 write: MultiThreadedScoreLock_write_void,
487 extern "C" fn MultiThreadedScoreLock_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
488 let mut ret = <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) }, score_params.get_native_ref());
491 extern "C" fn MultiThreadedScoreLock_Score_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
492 <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, path.get_native_ref(), short_channel_id)
494 extern "C" fn MultiThreadedScoreLock_Score_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
495 <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, path.get_native_ref())
497 extern "C" fn MultiThreadedScoreLock_Score_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
498 <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, path.get_native_ref(), short_channel_id)
500 extern "C" fn MultiThreadedScoreLock_Score_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
501 <nativeMultiThreadedScoreLock as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeMultiThreadedScoreLock) }, path.get_native_ref())
505 use lightning::routing::scoring::ChannelUsage as nativeChannelUsageImport;
506 pub(crate) type nativeChannelUsage = nativeChannelUsageImport;
508 /// Proposed use of a channel passed as a parameter to [`Score::channel_penalty_msat`].
511 pub struct ChannelUsage {
512 /// A pointer to the opaque Rust object.
514 /// Nearly everywhere, inner must be non-null, however in places where
515 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
516 pub inner: *mut nativeChannelUsage,
517 /// Indicates that this is the only struct which contains the same pointer.
519 /// Rust functions which take ownership of an object provided via an argument require
520 /// this to be true and invalidate the object pointed to by inner.
524 impl Drop for ChannelUsage {
526 if self.is_owned && !<*mut nativeChannelUsage>::is_null(self.inner) {
527 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
531 /// Frees any resources used by the ChannelUsage, if is_owned is set and inner is non-NULL.
533 pub extern "C" fn ChannelUsage_free(this_obj: ChannelUsage) { }
535 /// Used only if an object of this type is returned as a trait impl by a method
536 pub(crate) extern "C" fn ChannelUsage_free_void(this_ptr: *mut c_void) {
537 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeChannelUsage) };
541 pub(crate) fn get_native_ref(&self) -> &'static nativeChannelUsage {
542 unsafe { &*ObjOps::untweak_ptr(self.inner) }
544 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelUsage {
545 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
547 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
548 pub(crate) fn take_inner(mut self) -> *mut nativeChannelUsage {
549 assert!(self.is_owned);
550 let ret = ObjOps::untweak_ptr(self.inner);
551 self.inner = core::ptr::null_mut();
555 /// The amount to send through the channel, denominated in millisatoshis.
557 pub extern "C" fn ChannelUsage_get_amount_msat(this_ptr: &ChannelUsage) -> u64 {
558 let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat;
561 /// The amount to send through the channel, denominated in millisatoshis.
563 pub extern "C" fn ChannelUsage_set_amount_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
564 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val;
566 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
567 /// as part of a multi-path payment.
569 pub extern "C" fn ChannelUsage_get_inflight_htlc_msat(this_ptr: &ChannelUsage) -> u64 {
570 let mut inner_val = &mut this_ptr.get_native_mut_ref().inflight_htlc_msat;
573 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
574 /// as part of a multi-path payment.
576 pub extern "C" fn ChannelUsage_set_inflight_htlc_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
577 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inflight_htlc_msat = val;
579 /// The effective capacity of the channel.
581 pub extern "C" fn ChannelUsage_get_effective_capacity(this_ptr: &ChannelUsage) -> crate::lightning::routing::gossip::EffectiveCapacity {
582 let mut inner_val = &mut this_ptr.get_native_mut_ref().effective_capacity;
583 crate::lightning::routing::gossip::EffectiveCapacity::from_native(inner_val)
585 /// The effective capacity of the channel.
587 pub extern "C" fn ChannelUsage_set_effective_capacity(this_ptr: &mut ChannelUsage, mut val: crate::lightning::routing::gossip::EffectiveCapacity) {
588 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.effective_capacity = val.into_native();
590 /// Constructs a new ChannelUsage given each field
593 pub extern "C" fn ChannelUsage_new(mut amount_msat_arg: u64, mut inflight_htlc_msat_arg: u64, mut effective_capacity_arg: crate::lightning::routing::gossip::EffectiveCapacity) -> ChannelUsage {
594 ChannelUsage { inner: ObjOps::heap_alloc(nativeChannelUsage {
595 amount_msat: amount_msat_arg,
596 inflight_htlc_msat: inflight_htlc_msat_arg,
597 effective_capacity: effective_capacity_arg.into_native(),
600 impl Clone for ChannelUsage {
601 fn clone(&self) -> Self {
603 inner: if <*mut nativeChannelUsage>::is_null(self.inner) { core::ptr::null_mut() } else {
604 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
610 /// Used only if an object of this type is returned as a trait impl by a method
611 pub(crate) extern "C" fn ChannelUsage_clone_void(this_ptr: *const c_void) -> *mut c_void {
612 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelUsage)).clone() })) as *mut c_void
615 /// Creates a copy of the ChannelUsage
616 pub extern "C" fn ChannelUsage_clone(orig: &ChannelUsage) -> ChannelUsage {
620 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
621 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
623 /// [`Score`] implementation that uses a fixed penalty.
626 pub struct FixedPenaltyScorer {
627 /// A pointer to the opaque Rust object.
629 /// Nearly everywhere, inner must be non-null, however in places where
630 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
631 pub inner: *mut nativeFixedPenaltyScorer,
632 /// Indicates that this is the only struct which contains the same pointer.
634 /// Rust functions which take ownership of an object provided via an argument require
635 /// this to be true and invalidate the object pointed to by inner.
639 impl Drop for FixedPenaltyScorer {
641 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
642 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
646 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
648 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
650 /// Used only if an object of this type is returned as a trait impl by a method
651 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
652 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer) };
655 impl FixedPenaltyScorer {
656 pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
657 unsafe { &*ObjOps::untweak_ptr(self.inner) }
659 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
660 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
662 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
663 pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
664 assert!(self.is_owned);
665 let ret = ObjOps::untweak_ptr(self.inner);
666 self.inner = core::ptr::null_mut();
670 impl Clone for FixedPenaltyScorer {
671 fn clone(&self) -> Self {
673 inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
674 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
680 /// Used only if an object of this type is returned as a trait impl by a method
681 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
682 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFixedPenaltyScorer)).clone() })) as *mut c_void
685 /// Creates a copy of the FixedPenaltyScorer
686 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
689 /// Creates a new scorer using `penalty_msat`.
692 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer {
693 let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
694 crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
697 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::Score {
698 fn from(obj: nativeFixedPenaltyScorer) -> Self {
699 let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
700 let mut ret = FixedPenaltyScorer_as_Score(&rust_obj);
701 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
702 rust_obj.inner = core::ptr::null_mut();
703 ret.free = Some(FixedPenaltyScorer_free_void);
707 /// Constructs a new Score which calls the relevant methods on this_arg.
708 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
710 pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score {
711 crate::lightning::routing::scoring::Score {
712 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
714 channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat,
715 payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed,
716 payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful,
717 probe_failed: FixedPenaltyScorer_Score_probe_failed,
718 probe_successful: FixedPenaltyScorer_Score_probe_successful,
719 write: FixedPenaltyScorer_write_void,
724 extern "C" fn FixedPenaltyScorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
725 let mut ret = <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) }, score_params.get_native_ref());
728 extern "C" fn FixedPenaltyScorer_Score_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
729 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), short_channel_id)
731 extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
732 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref())
734 extern "C" fn FixedPenaltyScorer_Score_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
735 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref(), short_channel_id)
737 extern "C" fn FixedPenaltyScorer_Score_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
738 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, path.get_native_ref())
742 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
743 pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
744 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
747 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
748 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
751 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
752 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
754 let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
755 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };
759 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
760 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>;
762 /// [`Score`] implementation using channel success probability distributions.
764 /// Channels are tracked with upper and lower liquidity bounds - when an HTLC fails at a channel,
765 /// we learn that the upper-bound on the available liquidity is lower than the amount of the HTLC.
766 /// When a payment is forwarded through a channel (but fails later in the route), we learn the
767 /// lower-bound on the channel's available liquidity must be at least the value of the HTLC.
769 /// These bounds are then used to determine a success probability using the formula from
770 /// *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
771 /// and Stefan Richter [[1]] (i.e. `(upper_bound - payment_amount) / (upper_bound - lower_bound)`).
773 /// This probability is combined with the [`liquidity_penalty_multiplier_msat`] and
774 /// [`liquidity_penalty_amount_multiplier_msat`] parameters to calculate a concrete penalty in
775 /// milli-satoshis. The penalties, when added across all hops, have the property of being linear in
776 /// terms of the entire path's success probability. This allows the router to directly compare
777 /// penalties for different paths. See the documentation of those parameters for the exact formulas.
779 /// The liquidity bounds are decayed by halving them every [`liquidity_offset_half_life`].
781 /// Further, we track the history of our upper and lower liquidity bounds for each channel,
782 /// allowing us to assign a second penalty (using [`historical_liquidity_penalty_multiplier_msat`]
783 /// and [`historical_liquidity_penalty_amount_multiplier_msat`]) based on the same probability
784 /// formula, but using the history of a channel rather than our latest estimates for the liquidity
789 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
792 /// [1]: https://arxiv.org/abs/2107.05322
793 /// [`liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_multiplier_msat
794 /// [`liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::liquidity_penalty_amount_multiplier_msat
795 /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
796 /// [`historical_liquidity_penalty_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_multiplier_msat
797 /// [`historical_liquidity_penalty_amount_multiplier_msat`]: ProbabilisticScoringFeeParameters::historical_liquidity_penalty_amount_multiplier_msat
800 pub struct ProbabilisticScorer {
801 /// A pointer to the opaque Rust object.
803 /// Nearly everywhere, inner must be non-null, however in places where
804 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
805 pub inner: *mut nativeProbabilisticScorer,
806 /// Indicates that this is the only struct which contains the same pointer.
808 /// Rust functions which take ownership of an object provided via an argument require
809 /// this to be true and invalidate the object pointed to by inner.
813 impl Drop for ProbabilisticScorer {
815 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
816 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
820 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
822 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
824 /// Used only if an object of this type is returned as a trait impl by a method
825 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
826 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScorer) };
829 impl ProbabilisticScorer {
830 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
831 unsafe { &*ObjOps::untweak_ptr(self.inner) }
833 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
834 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
836 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
837 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
838 assert!(self.is_owned);
839 let ret = ObjOps::untweak_ptr(self.inner);
840 self.inner = core::ptr::null_mut();
845 use lightning::routing::scoring::ProbabilisticScoringFeeParameters as nativeProbabilisticScoringFeeParametersImport;
846 pub(crate) type nativeProbabilisticScoringFeeParameters = nativeProbabilisticScoringFeeParametersImport;
848 /// Parameters for configuring [`ProbabilisticScorer`].
850 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
851 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
853 /// The penalty applied to any channel by the [`ProbabilisticScorer`] is the sum of each of the
857 pub struct ProbabilisticScoringFeeParameters {
858 /// A pointer to the opaque Rust object.
860 /// Nearly everywhere, inner must be non-null, however in places where
861 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
862 pub inner: *mut nativeProbabilisticScoringFeeParameters,
863 /// Indicates that this is the only struct which contains the same pointer.
865 /// Rust functions which take ownership of an object provided via an argument require
866 /// this to be true and invalidate the object pointed to by inner.
870 impl Drop for ProbabilisticScoringFeeParameters {
872 if self.is_owned && !<*mut nativeProbabilisticScoringFeeParameters>::is_null(self.inner) {
873 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
877 /// Frees any resources used by the ProbabilisticScoringFeeParameters, if is_owned is set and inner is non-NULL.
879 pub extern "C" fn ProbabilisticScoringFeeParameters_free(this_obj: ProbabilisticScoringFeeParameters) { }
881 /// Used only if an object of this type is returned as a trait impl by a method
882 pub(crate) extern "C" fn ProbabilisticScoringFeeParameters_free_void(this_ptr: *mut c_void) {
883 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScoringFeeParameters) };
886 impl ProbabilisticScoringFeeParameters {
887 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringFeeParameters {
888 unsafe { &*ObjOps::untweak_ptr(self.inner) }
890 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringFeeParameters {
891 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
893 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
894 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringFeeParameters {
895 assert!(self.is_owned);
896 let ret = ObjOps::untweak_ptr(self.inner);
897 self.inner = core::ptr::null_mut();
901 /// A fixed penalty in msats to apply to each channel.
903 /// Default value: 500 msat
905 pub extern "C" fn ProbabilisticScoringFeeParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
906 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
909 /// A fixed penalty in msats to apply to each channel.
911 /// Default value: 500 msat
913 pub extern "C" fn ProbabilisticScoringFeeParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
914 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
916 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
917 /// channel, in excess of the [`base_penalty_msat`].
919 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
920 /// fees plus penalty) for large payments. The penalty is computed as the product of this
921 /// multiplier and `2^30`ths of the payment amount.
923 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
925 /// Default value: 8,192 msat
927 /// [`base_penalty_msat`]: Self::base_penalty_msat
929 pub extern "C" fn ProbabilisticScoringFeeParameters_get_base_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
930 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_amount_multiplier_msat;
933 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
934 /// channel, in excess of the [`base_penalty_msat`].
936 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
937 /// fees plus penalty) for large payments. The penalty is computed as the product of this
938 /// multiplier and `2^30`ths of the payment amount.
940 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
942 /// Default value: 8,192 msat
944 /// [`base_penalty_msat`]: Self::base_penalty_msat
946 pub extern "C" fn ProbabilisticScoringFeeParameters_set_base_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
947 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_amount_multiplier_msat = val;
949 /// A multiplier used in conjunction with the negative `log10` of the channel's success
950 /// probability for a payment, as determined by our latest estimates of the channel's
951 /// liquidity, to determine the liquidity penalty.
953 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
954 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
955 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
956 /// lower bounding the success probability to `0.01`) when the amount falls within the
957 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
958 /// result in a `u64::max_value` penalty, however.
960 /// `-log10(success_probability) * liquidity_penalty_multiplier_msat`
962 /// Default value: 30,000 msat
964 /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
966 pub extern "C" fn ProbabilisticScoringFeeParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
967 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
970 /// A multiplier used in conjunction with the negative `log10` of the channel's success
971 /// probability for a payment, as determined by our latest estimates of the channel's
972 /// liquidity, to determine the liquidity penalty.
974 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
975 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
976 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
977 /// lower bounding the success probability to `0.01`) when the amount falls within the
978 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
979 /// result in a `u64::max_value` penalty, however.
981 /// `-log10(success_probability) * liquidity_penalty_multiplier_msat`
983 /// Default value: 30,000 msat
985 /// [`liquidity_offset_half_life`]: ProbabilisticScoringDecayParameters::liquidity_offset_half_life
987 pub extern "C" fn ProbabilisticScoringFeeParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
988 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
990 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
991 /// channel's success probability for the payment, as determined by our latest estimates of the
992 /// channel's liquidity, to determine the amount penalty.
994 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
995 /// fees plus penalty) for large payments. The penalty is computed as the product of this
996 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
997 /// success probability.
999 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
1001 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
1002 /// the amount will result in a penalty of the multiplier. And, as the success probability
1003 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
1004 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
1007 /// Default value: 192 msat
1009 pub extern "C" fn ProbabilisticScoringFeeParameters_get_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1010 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_amount_multiplier_msat;
1013 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
1014 /// channel's success probability for the payment, as determined by our latest estimates of the
1015 /// channel's liquidity, to determine the amount penalty.
1017 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
1018 /// fees plus penalty) for large payments. The penalty is computed as the product of this
1019 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
1020 /// success probability.
1022 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
1024 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
1025 /// the amount will result in a penalty of the multiplier. And, as the success probability
1026 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
1027 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
1030 /// Default value: 192 msat
1032 pub extern "C" fn ProbabilisticScoringFeeParameters_set_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1033 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_amount_multiplier_msat = val;
1035 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1036 /// probability for the payment, as determined based on the history of our estimates of the
1037 /// channel's available liquidity, to determine a penalty.
1039 /// This penalty is similar to [`liquidity_penalty_multiplier_msat`], however, instead of using
1040 /// only our latest estimate for the current liquidity available in the channel, it estimates
1041 /// success probability based on the estimated liquidity available in the channel through
1042 /// history. Specifically, every time we update our liquidity bounds on a given channel, we
1043 /// track which of several buckets those bounds fall into, exponentially decaying the
1044 /// probability of each bucket as new samples are added.
1046 /// Default value: 10,000 msat
1048 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1050 pub extern "C" fn ProbabilisticScoringFeeParameters_get_historical_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1051 let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_liquidity_penalty_multiplier_msat;
1054 /// A multiplier used in conjunction with the negative `log10` of the channel's success
1055 /// probability for the payment, as determined based on the history of our estimates of the
1056 /// channel's available liquidity, to determine a penalty.
1058 /// This penalty is similar to [`liquidity_penalty_multiplier_msat`], however, instead of using
1059 /// only our latest estimate for the current liquidity available in the channel, it estimates
1060 /// success probability based on the estimated liquidity available in the channel through
1061 /// history. Specifically, every time we update our liquidity bounds on a given channel, we
1062 /// track which of several buckets those bounds fall into, exponentially decaying the
1063 /// probability of each bucket as new samples are added.
1065 /// Default value: 10,000 msat
1067 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1069 pub extern "C" fn ProbabilisticScoringFeeParameters_set_historical_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1070 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_liquidity_penalty_multiplier_msat = val;
1072 /// A multiplier used in conjunction with the payment amount and the negative `log10` of the
1073 /// channel's success probability for the payment, as determined based on the history of our
1074 /// estimates of the channel's available liquidity, to determine a penalty.
1076 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost for
1077 /// large payments. The penalty is computed as the product of this multiplier and the `2^20`ths
1078 /// of the payment amount, weighted by the negative `log10` of the success probability.
1080 /// This penalty is similar to [`liquidity_penalty_amount_multiplier_msat`], however, instead
1081 /// of using only our latest estimate for the current liquidity available in the channel, it
1082 /// estimates success probability based on the estimated liquidity available in the channel
1083 /// through history. Specifically, every time we update our liquidity bounds on a given
1084 /// channel, we track which of several buckets those bounds fall into, exponentially decaying
1085 /// the probability of each bucket as new samples are added.
1087 /// Default value: 64 msat
1089 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1091 pub extern "C" fn ProbabilisticScoringFeeParameters_get_historical_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1092 let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_liquidity_penalty_amount_multiplier_msat;
1095 /// A multiplier used in conjunction with the payment amount and the negative `log10` of the
1096 /// channel's success probability for the payment, as determined based on the history of our
1097 /// estimates of the channel's available liquidity, to determine a penalty.
1099 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost for
1100 /// large payments. The penalty is computed as the product of this multiplier and the `2^20`ths
1101 /// of the payment amount, weighted by the negative `log10` of the success probability.
1103 /// This penalty is similar to [`liquidity_penalty_amount_multiplier_msat`], however, instead
1104 /// of using only our latest estimate for the current liquidity available in the channel, it
1105 /// estimates success probability based on the estimated liquidity available in the channel
1106 /// through history. Specifically, every time we update our liquidity bounds on a given
1107 /// channel, we track which of several buckets those bounds fall into, exponentially decaying
1108 /// the probability of each bucket as new samples are added.
1110 /// Default value: 64 msat
1112 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1114 pub extern "C" fn ProbabilisticScoringFeeParameters_set_historical_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1115 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_liquidity_penalty_amount_multiplier_msat = val;
1117 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1118 /// channel's capacity, (ie. htlc_maximum_msat ≥ 0.5 * channel_capacity) which makes us
1119 /// prefer nodes with a smaller `htlc_maximum_msat`. We treat such nodes preferentially
1120 /// as this makes balance discovery attacks harder to execute, thereby creating an incentive
1121 /// to restrict `htlc_maximum_msat` and improve privacy.
1123 /// Default value: 250 msat
1125 pub extern "C" fn ProbabilisticScoringFeeParameters_get_anti_probing_penalty_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1126 let mut inner_val = &mut this_ptr.get_native_mut_ref().anti_probing_penalty_msat;
1129 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
1130 /// channel's capacity, (ie. htlc_maximum_msat ≥ 0.5 * channel_capacity) which makes us
1131 /// prefer nodes with a smaller `htlc_maximum_msat`. We treat such nodes preferentially
1132 /// as this makes balance discovery attacks harder to execute, thereby creating an incentive
1133 /// to restrict `htlc_maximum_msat` and improve privacy.
1135 /// Default value: 250 msat
1137 pub extern "C" fn ProbabilisticScoringFeeParameters_set_anti_probing_penalty_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1138 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.anti_probing_penalty_msat = val;
1140 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
1141 /// current estimate of the channel's available liquidity.
1143 /// Note that in this case all other penalties, including the
1144 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1145 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1146 /// applicable, are still included in the overall penalty.
1148 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1149 /// `u64::max_value()` will guarantee that.
1151 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1153 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1154 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1155 /// [`base_penalty_msat`]: Self::base_penalty_msat
1156 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1158 pub extern "C" fn ProbabilisticScoringFeeParameters_get_considered_impossible_penalty_msat(this_ptr: &ProbabilisticScoringFeeParameters) -> u64 {
1159 let mut inner_val = &mut this_ptr.get_native_mut_ref().considered_impossible_penalty_msat;
1162 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
1163 /// current estimate of the channel's available liquidity.
1165 /// Note that in this case all other penalties, including the
1166 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
1167 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
1168 /// applicable, are still included in the overall penalty.
1170 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
1171 /// `u64::max_value()` will guarantee that.
1173 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
1175 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
1176 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
1177 /// [`base_penalty_msat`]: Self::base_penalty_msat
1178 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
1180 pub extern "C" fn ProbabilisticScoringFeeParameters_set_considered_impossible_penalty_msat(this_ptr: &mut ProbabilisticScoringFeeParameters, mut val: u64) {
1181 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.considered_impossible_penalty_msat = val;
1183 impl Clone for ProbabilisticScoringFeeParameters {
1184 fn clone(&self) -> Self {
1186 inner: if <*mut nativeProbabilisticScoringFeeParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1187 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1193 /// Used only if an object of this type is returned as a trait impl by a method
1194 pub(crate) extern "C" fn ProbabilisticScoringFeeParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1195 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringFeeParameters)).clone() })) as *mut c_void
1198 /// Creates a copy of the ProbabilisticScoringFeeParameters
1199 pub extern "C" fn ProbabilisticScoringFeeParameters_clone(orig: &ProbabilisticScoringFeeParameters) -> ProbabilisticScoringFeeParameters {
1202 /// Creates a "default" ProbabilisticScoringFeeParameters. See struct and individual field documentaiton for details on which values are used.
1205 pub extern "C" fn ProbabilisticScoringFeeParameters_default() -> ProbabilisticScoringFeeParameters {
1206 ProbabilisticScoringFeeParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1208 /// Marks the node with the given `node_id` as banned,
1209 /// i.e it will be avoided during path finding.
1211 pub extern "C" fn ProbabilisticScoringFeeParameters_add_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId) {
1212 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.add_banned(node_id.get_native_ref())
1215 /// Marks all nodes in the given list as banned, i.e.,
1216 /// they will be avoided during path finding.
1218 pub extern "C" fn ProbabilisticScoringFeeParameters_add_banned_from_list(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, mut node_ids: crate::c_types::derived::CVec_NodeIdZ) {
1219 let mut local_node_ids = Vec::new(); for mut item in node_ids.into_rust().drain(..) { local_node_ids.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
1220 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.add_banned_from_list(local_node_ids)
1223 /// Removes the node with the given `node_id` from the list of nodes to avoid.
1225 pub extern "C" fn ProbabilisticScoringFeeParameters_remove_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId) {
1226 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.remove_banned(node_id.get_native_ref())
1229 /// Sets a manual penalty for the given node.
1231 pub extern "C" fn ProbabilisticScoringFeeParameters_set_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId, mut penalty: u64) {
1232 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.set_manual_penalty(node_id.get_native_ref(), penalty)
1235 /// Removes the node with the given `node_id` from the list of manual penalties.
1237 pub extern "C" fn ProbabilisticScoringFeeParameters_remove_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters, node_id: &crate::lightning::routing::gossip::NodeId) {
1238 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.remove_manual_penalty(node_id.get_native_ref())
1241 /// Clears the list of manual penalties that are applied during path finding.
1243 pub extern "C" fn ProbabilisticScoringFeeParameters_clear_manual_penalties(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) {
1244 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringFeeParameters)) }.clear_manual_penalties()
1248 use lightning::routing::scoring::ProbabilisticScoringDecayParameters as nativeProbabilisticScoringDecayParametersImport;
1249 pub(crate) type nativeProbabilisticScoringDecayParameters = nativeProbabilisticScoringDecayParametersImport;
1251 /// Parameters for configuring [`ProbabilisticScorer`].
1253 /// Used to configure decay parameters that are static throughout the lifetime of the scorer.
1254 /// these decay parameters affect the score of the channel penalty and are not changed on a
1255 /// per-route penalty cost call.
1258 pub struct ProbabilisticScoringDecayParameters {
1259 /// A pointer to the opaque Rust object.
1261 /// Nearly everywhere, inner must be non-null, however in places where
1262 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
1263 pub inner: *mut nativeProbabilisticScoringDecayParameters,
1264 /// Indicates that this is the only struct which contains the same pointer.
1266 /// Rust functions which take ownership of an object provided via an argument require
1267 /// this to be true and invalidate the object pointed to by inner.
1271 impl Drop for ProbabilisticScoringDecayParameters {
1272 fn drop(&mut self) {
1273 if self.is_owned && !<*mut nativeProbabilisticScoringDecayParameters>::is_null(self.inner) {
1274 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
1278 /// Frees any resources used by the ProbabilisticScoringDecayParameters, if is_owned is set and inner is non-NULL.
1280 pub extern "C" fn ProbabilisticScoringDecayParameters_free(this_obj: ProbabilisticScoringDecayParameters) { }
1282 /// Used only if an object of this type is returned as a trait impl by a method
1283 pub(crate) extern "C" fn ProbabilisticScoringDecayParameters_free_void(this_ptr: *mut c_void) {
1284 let _ = unsafe { Box::from_raw(this_ptr as *mut nativeProbabilisticScoringDecayParameters) };
1287 impl ProbabilisticScoringDecayParameters {
1288 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringDecayParameters {
1289 unsafe { &*ObjOps::untweak_ptr(self.inner) }
1291 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringDecayParameters {
1292 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
1294 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
1295 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringDecayParameters {
1296 assert!(self.is_owned);
1297 let ret = ObjOps::untweak_ptr(self.inner);
1298 self.inner = core::ptr::null_mut();
1302 /// If we aren't learning any new datapoints for a channel, the historical liquidity bounds
1303 /// tracking can simply live on with increasingly stale data. Instead, when a channel has not
1304 /// seen a liquidity estimate update for this amount of time, the historical datapoints are
1305 /// decayed by half.
1306 /// For an example of historical_no_updates_half_life being used see [`historical_estimated_channel_liquidity_probabilities`]
1308 /// Note that after 16 or more half lives all historical data will be completely gone.
1310 /// Default value: 14 days
1312 /// [`historical_estimated_channel_liquidity_probabilities`]: ProbabilisticScorerUsingTime::historical_estimated_channel_liquidity_probabilities
1314 pub extern "C" fn ProbabilisticScoringDecayParameters_get_historical_no_updates_half_life(this_ptr: &ProbabilisticScoringDecayParameters) -> u64 {
1315 let mut inner_val = &mut this_ptr.get_native_mut_ref().historical_no_updates_half_life;
1318 /// If we aren't learning any new datapoints for a channel, the historical liquidity bounds
1319 /// tracking can simply live on with increasingly stale data. Instead, when a channel has not
1320 /// seen a liquidity estimate update for this amount of time, the historical datapoints are
1321 /// decayed by half.
1322 /// For an example of historical_no_updates_half_life being used see [`historical_estimated_channel_liquidity_probabilities`]
1324 /// Note that after 16 or more half lives all historical data will be completely gone.
1326 /// Default value: 14 days
1328 /// [`historical_estimated_channel_liquidity_probabilities`]: ProbabilisticScorerUsingTime::historical_estimated_channel_liquidity_probabilities
1330 pub extern "C" fn ProbabilisticScoringDecayParameters_set_historical_no_updates_half_life(this_ptr: &mut ProbabilisticScoringDecayParameters, mut val: u64) {
1331 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.historical_no_updates_half_life = core::time::Duration::from_secs(val);
1333 /// Whenever this amount of time elapses since the last update to a channel's liquidity bounds,
1334 /// the distance from the bounds to \"zero\" is cut in half. In other words, the lower-bound on
1335 /// the available liquidity is halved and the upper-bound moves half-way to the channel's total
1338 /// Because halving the liquidity bounds grows the uncertainty on the channel's liquidity,
1339 /// the penalty for an amount within the new bounds may change. See the [`ProbabilisticScorer`]
1340 /// struct documentation for more info on the way the liquidity bounds are used.
1342 /// For example, if the channel's capacity is 1 million sats, and the current upper and lower
1343 /// liquidity bounds are 200,000 sats and 600,000 sats, after this amount of time the upper
1344 /// and lower liquidity bounds will be decayed to 100,000 and 800,000 sats.
1346 /// Default value: 6 hours
1350 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
1351 /// liquidity knowledge will never decay except when the bounds cross.
1353 pub extern "C" fn ProbabilisticScoringDecayParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringDecayParameters) -> u64 {
1354 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
1357 /// Whenever this amount of time elapses since the last update to a channel's liquidity bounds,
1358 /// the distance from the bounds to \"zero\" is cut in half. In other words, the lower-bound on
1359 /// the available liquidity is halved and the upper-bound moves half-way to the channel's total
1362 /// Because halving the liquidity bounds grows the uncertainty on the channel's liquidity,
1363 /// the penalty for an amount within the new bounds may change. See the [`ProbabilisticScorer`]
1364 /// struct documentation for more info on the way the liquidity bounds are used.
1366 /// For example, if the channel's capacity is 1 million sats, and the current upper and lower
1367 /// liquidity bounds are 200,000 sats and 600,000 sats, after this amount of time the upper
1368 /// and lower liquidity bounds will be decayed to 100,000 and 800,000 sats.
1370 /// Default value: 6 hours
1374 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
1375 /// liquidity knowledge will never decay except when the bounds cross.
1377 pub extern "C" fn ProbabilisticScoringDecayParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringDecayParameters, mut val: u64) {
1378 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
1380 /// Constructs a new ProbabilisticScoringDecayParameters given each field
1383 pub extern "C" fn ProbabilisticScoringDecayParameters_new(mut historical_no_updates_half_life_arg: u64, mut liquidity_offset_half_life_arg: u64) -> ProbabilisticScoringDecayParameters {
1384 ProbabilisticScoringDecayParameters { inner: ObjOps::heap_alloc(nativeProbabilisticScoringDecayParameters {
1385 historical_no_updates_half_life: core::time::Duration::from_secs(historical_no_updates_half_life_arg),
1386 liquidity_offset_half_life: core::time::Duration::from_secs(liquidity_offset_half_life_arg),
1387 }), is_owned: true }
1389 impl Clone for ProbabilisticScoringDecayParameters {
1390 fn clone(&self) -> Self {
1392 inner: if <*mut nativeProbabilisticScoringDecayParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1393 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1399 /// Used only if an object of this type is returned as a trait impl by a method
1400 pub(crate) extern "C" fn ProbabilisticScoringDecayParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1401 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringDecayParameters)).clone() })) as *mut c_void
1404 /// Creates a copy of the ProbabilisticScoringDecayParameters
1405 pub extern "C" fn ProbabilisticScoringDecayParameters_clone(orig: &ProbabilisticScoringDecayParameters) -> ProbabilisticScoringDecayParameters {
1408 /// Creates a "default" ProbabilisticScoringDecayParameters. See struct and individual field documentaiton for details on which values are used.
1411 pub extern "C" fn ProbabilisticScoringDecayParameters_default() -> ProbabilisticScoringDecayParameters {
1412 ProbabilisticScoringDecayParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1414 /// Creates a new scorer using the given scoring parameters for sending payments from a node
1415 /// through a network graph.
1418 pub extern "C" fn ProbabilisticScorer_new(mut decay_params: crate::lightning::routing::scoring::ProbabilisticScoringDecayParameters, network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::routing::scoring::ProbabilisticScorer {
1419 let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(decay_params.take_inner()) }, network_graph.get_native_ref(), logger);
1420 crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
1423 /// Dump the contents of this scorer into the configured logger.
1425 /// Note that this writes roughly one line per channel for which we have a liquidity estimate,
1426 /// which may be a substantial amount of log output.
1428 pub extern "C" fn ProbabilisticScorer_debug_log_liquidity_stats(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer) {
1429 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.debug_log_liquidity_stats()
1432 /// Query the estimated minimum and maximum liquidity available for sending a payment over the
1433 /// channel with `scid` towards the given `target` node.
1436 pub extern "C" fn ProbabilisticScorer_estimated_channel_liquidity_range(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer, mut scid: u64, target: &crate::lightning::routing::gossip::NodeId) -> crate::c_types::derived::COption_C2Tuple_u64u64ZZ {
1437 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.estimated_channel_liquidity_range(scid, target.get_native_ref());
1438 let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_C2Tuple_u64u64ZZ::None } else { crate::c_types::derived::COption_C2Tuple_u64u64ZZ::Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (ret.unwrap()); let mut local_ret_0 = (orig_ret_0_0, orig_ret_0_1).into(); local_ret_0 }) };
1442 /// Query the historical estimated minimum and maximum liquidity available for sending a
1443 /// payment over the channel with `scid` towards the given `target` node.
1445 /// Returns two sets of 8 buckets. The first set describes the octiles for lower-bound
1446 /// liquidity estimates, the second set describes the octiles for upper-bound liquidity
1447 /// estimates. Each bucket describes the relative frequency at which we've seen a liquidity
1448 /// bound in the octile relative to the channel's total capacity, on an arbitrary scale.
1449 /// Because the values are slowly decayed, more recent data points are weighted more heavily
1450 /// than older datapoints.
1452 /// When scoring, the estimated probability that an upper-/lower-bound lies in a given octile
1453 /// relative to the channel's total capacity is calculated by dividing that bucket's value with
1454 /// the total of all buckets for the given bound.
1456 /// For example, a value of `[0, 0, 0, 0, 0, 0, 32]` indicates that we believe the probability
1457 /// of a bound being in the top octile to be 100%, and have never (recently) seen it in any
1458 /// other octiles. A value of `[31, 0, 0, 0, 0, 0, 0, 32]` indicates we've seen the bound being
1459 /// both in the top and bottom octile, and roughly with similar (recent) frequency.
1461 /// Because the datapoints are decayed slowly over time, values will eventually return to
1462 /// `Some(([0; 8], [0; 8]))`.
1465 pub extern "C" fn ProbabilisticScorer_historical_estimated_channel_liquidity_probabilities(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer, mut scid: u64, target: &crate::lightning::routing::gossip::NodeId) -> crate::c_types::derived::COption_C2Tuple_EightU16sEightU16sZZ {
1466 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.historical_estimated_channel_liquidity_probabilities(scid, target.get_native_ref());
1467 let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_C2Tuple_EightU16sEightU16sZZ::None } else { crate::c_types::derived::COption_C2Tuple_EightU16sEightU16sZZ::Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (ret.unwrap()); let mut local_ret_0 = (crate::c_types::EightU16s { data: orig_ret_0_0 }, crate::c_types::EightU16s { data: orig_ret_0_1 }).into(); local_ret_0 }) };
1471 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
1472 fn from(obj: nativeProbabilisticScorer) -> Self {
1473 let mut rust_obj = ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1474 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
1475 // We want to free rust_obj when ret gets drop()'d, not rust_obj, so wipe rust_obj's pointer and set ret's free() fn
1476 rust_obj.inner = core::ptr::null_mut();
1477 ret.free = Some(ProbabilisticScorer_free_void);
1481 /// Constructs a new Score which calls the relevant methods on this_arg.
1482 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
1484 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
1485 crate::lightning::routing::scoring::Score {
1486 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1488 channel_penalty_msat: ProbabilisticScorer_Score_channel_penalty_msat,
1489 payment_path_failed: ProbabilisticScorer_Score_payment_path_failed,
1490 payment_path_successful: ProbabilisticScorer_Score_payment_path_successful,
1491 probe_failed: ProbabilisticScorer_Score_probe_failed,
1492 probe_successful: ProbabilisticScorer_Score_probe_successful,
1493 write: ProbabilisticScorer_write_void,
1498 extern "C" fn ProbabilisticScorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage, score_params: &crate::lightning::routing::scoring::ProbabilisticScoringFeeParameters) -> u64 {
1499 let mut ret = <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) }, score_params.get_native_ref());
1502 extern "C" fn ProbabilisticScorer_Score_payment_path_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
1503 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), short_channel_id)
1505 extern "C" fn ProbabilisticScorer_Score_payment_path_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
1506 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref())
1508 extern "C" fn ProbabilisticScorer_Score_probe_failed(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path, mut short_channel_id: u64) {
1509 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref(), short_channel_id)
1511 extern "C" fn ProbabilisticScorer_Score_probe_successful(this_arg: *mut c_void, path: &crate::lightning::routing::router::Path) {
1512 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, path.get_native_ref())
1517 use alloc::str::FromStr;
1518 use core::ffi::c_void;
1519 use core::convert::Infallible;
1520 use bitcoin::hashes::Hash;
1521 use crate::c_types::*;
1522 #[cfg(feature="no-std")]
1523 use alloc::{vec::Vec, boxed::Box};
1527 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
1528 pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
1529 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1532 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1533 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
1536 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
1537 pub extern "C" fn ProbabilisticScorer_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::routing::scoring::ProbabilisticScoringDecayParameters, arg_b: &crate::lightning::routing::gossip::NetworkGraph, arg_c: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_ProbabilisticScorerDecodeErrorZ {
1538 let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
1539 let arg_b_conv = arg_b.get_native_ref();
1540 let arg_c_conv = arg_c;
1541 let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv);
1542 let res: Result<lightning::routing::scoring::ProbabilisticScorer<&lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
1543 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError::native_into(e) }).into() };