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 secp256k1;
19 //! # use lightning::routing::network_graph::NetworkGraph;
20 //! # use lightning::routing::router::{RouteParameters, find_route};
21 //! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters, Scorer, ScoringParameters};
22 //! # use lightning::chain::keysinterface::{KeysManager, KeysInterface};
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use secp256k1::key::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) {
31 //! # let logger = FakeLogger {};
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringParameters::default();
35 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
37 //! // Or use custom channel penalties.
38 //! let params = ProbabilisticScoringParameters {
39 //! liquidity_penalty_multiplier_msat: 2 * 1000,
40 //! ..ProbabilisticScoringParameters::default()
42 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
43 //! # let random_seed_bytes = [42u8; 32];
45 //! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer, &random_seed_bytes);
51 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
52 //! different types and thus is undefined.
54 //! [`find_route`]: crate::routing::router::find_route
56 use alloc::str::FromStr;
57 use core::ffi::c_void;
58 use core::convert::Infallible;
59 use bitcoin::hashes::Hash;
60 use crate::c_types::*;
61 #[cfg(feature="no-std")]
62 use alloc::{vec::Vec, boxed::Box};
64 /// An interface used to score payment channels for path finding.
66 ///\tScoring is in terms of fees willing to be paid in order to avoid routing through a channel.
69 /// An opaque pointer which is passed to your function implementations as an argument.
70 /// This has no meaning in the LDK, and can be NULL or any other value.
71 pub this_arg: *mut c_void,
72 /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
73 /// given channel in the direction from `source` to `target`.
75 /// The channel's capacity (less any other MPP parts that are also being considered for use in
76 /// the same payment) is given by `capacity_msat`. It may be determined from various sources
77 /// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near
78 /// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount.
79 /// Thus, implementations should be overflow-safe.
81 pub channel_penalty_msat: extern "C" fn (this_arg: *const c_void, short_channel_id: u64, send_amt_msat: u64, capacity_msat: u64, source: &crate::lightning::routing::network_graph::NodeId, target: &crate::lightning::routing::network_graph::NodeId) -> u64,
82 /// Handles updating channel penalties after failing to route through a channel.
83 pub payment_path_failed: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64),
84 /// Handles updating channel penalties after successfully routing along a path.
85 pub payment_path_successful: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ),
86 /// Serialize the object into a byte array
87 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
88 /// Frees any resources associated with this object given its this_arg pointer.
89 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
90 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
92 unsafe impl Send for Score {}
93 unsafe impl Sync for Score {}
95 pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score {
97 this_arg: orig.this_arg,
98 channel_penalty_msat: Clone::clone(&orig.channel_penalty_msat),
99 payment_path_failed: Clone::clone(&orig.payment_path_failed),
100 payment_path_successful: Clone::clone(&orig.payment_path_successful),
101 write: Clone::clone(&orig.write),
102 free: Clone::clone(&orig.free),
105 impl lightning::util::ser::Writeable for Score {
106 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
107 let vec = (self.write)(self.this_arg);
108 w.write_all(vec.as_slice())
112 use lightning::routing::scoring::Score as rustScore;
113 impl rustScore for Score {
114 fn channel_penalty_msat(&self, mut short_channel_id: u64, mut send_amt_msat: u64, mut capacity_msat: u64, mut source: &lightning::routing::network_graph::NodeId, mut target: &lightning::routing::network_graph::NodeId) -> u64 {
115 let mut ret = (self.channel_penalty_msat)(self.this_arg, short_channel_id, send_amt_msat, capacity_msat, &crate::lightning::routing::network_graph::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((source as *const lightning::routing::network_graph::NodeId<>) as *mut _) }, is_owned: false }, &crate::lightning::routing::network_graph::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((target as *const lightning::routing::network_graph::NodeId<>) as *mut _) }, is_owned: false });
118 fn payment_path_failed(&mut self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) {
119 let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); };
120 (self.payment_path_failed)(self.this_arg, local_path.into(), short_channel_id)
122 fn payment_path_successful(&mut self, mut path: &[&lightning::routing::router::RouteHop]) {
123 let mut local_path = Vec::new(); for item in path.iter() { local_path.push( { crate::lightning::routing::router::RouteHop { inner: unsafe { ObjOps::nonnull_ptr_to_inner(((*item) as *const lightning::routing::router::RouteHop<>) as *mut _) }, is_owned: false } }); };
124 (self.payment_path_successful)(self.this_arg, local_path.into())
128 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
129 // directly as a Deref trait in higher-level structs:
130 impl core::ops::Deref for Score {
132 fn deref(&self) -> &Self {
136 /// Calls the free function if one is set
138 pub extern "C" fn Score_free(this_ptr: Score) { }
139 impl Drop for Score {
141 if let Some(f) = self.free {
146 /// A scorer that is accessed under a lock.
148 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
149 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
150 /// implementations. Internal locking would be detrimental to route finding performance and could
151 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
153 /// [`find_route`]: crate::routing::router::find_route
155 pub struct LockableScore {
156 /// An opaque pointer which is passed to your function implementations as an argument.
157 /// This has no meaning in the LDK, and can be NULL or any other value.
158 pub this_arg: *mut c_void,
159 /// Returns the locked scorer.
161 pub lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::Score,
162 /// Frees any resources associated with this object given its this_arg pointer.
163 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
164 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
166 unsafe impl Send for LockableScore {}
167 unsafe impl Sync for LockableScore {}
169 pub(crate) extern "C" fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
171 this_arg: orig.this_arg,
172 lock: Clone::clone(&orig.lock),
173 free: Clone::clone(&orig.free),
177 use lightning::routing::scoring::LockableScore as rustLockableScore;
178 impl<'a> rustLockableScore<'a> for LockableScore {
179 type Locked = crate::lightning::routing::scoring::Score;
180 fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
181 let mut ret = (self.lock)(self.this_arg);
186 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
187 // directly as a Deref trait in higher-level structs:
188 impl core::ops::Deref for LockableScore {
190 fn deref(&self) -> &Self {
194 /// Calls the free function if one is set
196 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
197 impl Drop for LockableScore {
199 if let Some(f) = self.free {
205 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
206 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
208 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
211 pub struct MultiThreadedLockableScore {
212 /// A pointer to the opaque Rust object.
214 /// Nearly everywhere, inner must be non-null, however in places where
215 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
216 pub inner: *mut nativeMultiThreadedLockableScore,
217 /// Indicates that this is the only struct which contains the same pointer.
219 /// Rust functions which take ownership of an object provided via an argument require
220 /// this to be true and invalidate the object pointed to by inner.
224 impl Drop for MultiThreadedLockableScore {
226 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
227 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
231 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
233 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
235 /// Used only if an object of this type is returned as a trait impl by a method
236 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
237 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore); }
240 impl MultiThreadedLockableScore {
241 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
242 unsafe { &*ObjOps::untweak_ptr(self.inner) }
244 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
245 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
247 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
248 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
249 assert!(self.is_owned);
250 let ret = ObjOps::untweak_ptr(self.inner);
251 self.inner = core::ptr::null_mut();
255 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
258 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> MultiThreadedLockableScore {
259 let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
260 MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
264 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
265 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
267 /// [`Score`] implementation that uses a fixed penalty.
270 pub struct FixedPenaltyScorer {
271 /// A pointer to the opaque Rust object.
273 /// Nearly everywhere, inner must be non-null, however in places where
274 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
275 pub inner: *mut nativeFixedPenaltyScorer,
276 /// Indicates that this is the only struct which contains the same pointer.
278 /// Rust functions which take ownership of an object provided via an argument require
279 /// this to be true and invalidate the object pointed to by inner.
283 impl Drop for FixedPenaltyScorer {
285 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
286 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
290 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
292 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
294 /// Used only if an object of this type is returned as a trait impl by a method
295 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
296 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer); }
299 impl FixedPenaltyScorer {
300 pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
301 unsafe { &*ObjOps::untweak_ptr(self.inner) }
303 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
304 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
306 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
307 pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
308 assert!(self.is_owned);
309 let ret = ObjOps::untweak_ptr(self.inner);
310 self.inner = core::ptr::null_mut();
314 impl Clone for FixedPenaltyScorer {
315 fn clone(&self) -> Self {
317 inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
318 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
324 /// Used only if an object of this type is returned as a trait impl by a method
325 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
326 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFixedPenaltyScorer)).clone() })) as *mut c_void
329 /// Creates a copy of the FixedPenaltyScorer
330 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
333 /// Creates a new scorer using `penalty_msat`.
336 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> FixedPenaltyScorer {
337 let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
338 FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
341 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::Score {
342 fn from(obj: nativeFixedPenaltyScorer) -> Self {
343 let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
344 let mut ret = FixedPenaltyScorer_as_Score(&rust_obj);
345 // 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
346 rust_obj.inner = core::ptr::null_mut();
347 ret.free = Some(FixedPenaltyScorer_free_void);
351 /// Constructs a new Score which calls the relevant methods on this_arg.
352 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
354 pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score {
355 crate::lightning::routing::scoring::Score {
356 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
358 channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat,
359 payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed,
360 payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful,
361 write: FixedPenaltyScorer_write_void,
366 extern "C" fn FixedPenaltyScorer_Score_channel_penalty_msat(this_arg: *const c_void, unused_0: u64, unused_1: u64, unused_2: u64, unused_3: &crate::lightning::routing::network_graph::NodeId, unused_4: &crate::lightning::routing::network_graph::NodeId) -> u64 {
367 let mut ret = <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, unused_0, unused_1, unused_2, unused_3.get_native_ref(), unused_4.get_native_ref());
370 extern "C" fn FixedPenaltyScorer_Score_payment_path_failed(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ, mut _short_channel_id: u64) {
371 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
372 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..], _short_channel_id)
374 extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ) {
375 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
376 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..])
380 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
381 pub extern "C" fn FixedPenaltyScorer_write(obj: &FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
382 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
385 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
386 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
389 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
390 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
392 let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
393 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 { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
397 use lightning::routing::scoring::Scorer as nativeScorerImport;
398 pub(crate) type nativeScorer = nativeScorerImport;
400 /// [`Score`] implementation that provides reasonable default behavior.
402 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
403 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
405 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
409 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
412 /// [module-level documentation]: crate::routing::scoring
416 /// A pointer to the opaque Rust object.
418 /// Nearly everywhere, inner must be non-null, however in places where
419 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
420 pub inner: *mut nativeScorer,
421 /// Indicates that this is the only struct which contains the same pointer.
423 /// Rust functions which take ownership of an object provided via an argument require
424 /// this to be true and invalidate the object pointed to by inner.
428 impl Drop for Scorer {
430 if self.is_owned && !<*mut nativeScorer>::is_null(self.inner) {
431 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
435 /// Frees any resources used by the Scorer, if is_owned is set and inner is non-NULL.
437 pub extern "C" fn Scorer_free(this_obj: Scorer) { }
439 /// Used only if an object of this type is returned as a trait impl by a method
440 pub(crate) extern "C" fn Scorer_free_void(this_ptr: *mut c_void) {
441 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScorer); }
445 pub(crate) fn get_native_ref(&self) -> &'static nativeScorer {
446 unsafe { &*ObjOps::untweak_ptr(self.inner) }
448 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScorer {
449 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
451 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
452 pub(crate) fn take_inner(mut self) -> *mut nativeScorer {
453 assert!(self.is_owned);
454 let ret = ObjOps::untweak_ptr(self.inner);
455 self.inner = core::ptr::null_mut();
460 use lightning::routing::scoring::ScoringParameters as nativeScoringParametersImport;
461 pub(crate) type nativeScoringParameters = nativeScoringParametersImport;
463 /// Parameters for configuring [`Scorer`].
466 pub struct ScoringParameters {
467 /// A pointer to the opaque Rust object.
469 /// Nearly everywhere, inner must be non-null, however in places where
470 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
471 pub inner: *mut nativeScoringParameters,
472 /// Indicates that this is the only struct which contains the same pointer.
474 /// Rust functions which take ownership of an object provided via an argument require
475 /// this to be true and invalidate the object pointed to by inner.
479 impl Drop for ScoringParameters {
481 if self.is_owned && !<*mut nativeScoringParameters>::is_null(self.inner) {
482 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
486 /// Frees any resources used by the ScoringParameters, if is_owned is set and inner is non-NULL.
488 pub extern "C" fn ScoringParameters_free(this_obj: ScoringParameters) { }
490 /// Used only if an object of this type is returned as a trait impl by a method
491 pub(crate) extern "C" fn ScoringParameters_free_void(this_ptr: *mut c_void) {
492 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScoringParameters); }
495 impl ScoringParameters {
496 pub(crate) fn get_native_ref(&self) -> &'static nativeScoringParameters {
497 unsafe { &*ObjOps::untweak_ptr(self.inner) }
499 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScoringParameters {
500 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
502 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
503 pub(crate) fn take_inner(mut self) -> *mut nativeScoringParameters {
504 assert!(self.is_owned);
505 let ret = ObjOps::untweak_ptr(self.inner);
506 self.inner = core::ptr::null_mut();
510 /// A fixed penalty in msats to apply to each channel.
512 /// Default value: 500 msat
514 pub extern "C" fn ScoringParameters_get_base_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
515 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
518 /// A fixed penalty in msats to apply to each channel.
520 /// Default value: 500 msat
522 pub extern "C" fn ScoringParameters_set_base_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
523 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
525 /// A penalty in msats to apply to a channel upon failing to relay a payment.
527 /// This accumulates for each failure but may be reduced over time based on
528 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
530 /// Default value: 1,024,000 msat
532 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
534 pub extern "C" fn ScoringParameters_get_failure_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
535 let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_msat;
538 /// A penalty in msats to apply to a channel upon failing to relay a payment.
540 /// This accumulates for each failure but may be reduced over time based on
541 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
543 /// Default value: 1,024,000 msat
545 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
547 pub extern "C" fn ScoringParameters_set_failure_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
548 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_msat = val;
550 /// When the amount being sent over a channel is this many 1024ths of the total channel
551 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
553 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
555 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
557 pub extern "C" fn ScoringParameters_get_overuse_penalty_start_1024th(this_ptr: &ScoringParameters) -> u16 {
558 let mut inner_val = &mut this_ptr.get_native_mut_ref().overuse_penalty_start_1024th;
561 /// When the amount being sent over a channel is this many 1024ths of the total channel
562 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
564 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
566 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
568 pub extern "C" fn ScoringParameters_set_overuse_penalty_start_1024th(this_ptr: &mut ScoringParameters, mut val: u16) {
569 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.overuse_penalty_start_1024th = val;
571 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
572 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
574 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
575 /// to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
577 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
579 pub extern "C" fn ScoringParameters_get_overuse_penalty_msat_per_1024th(this_ptr: &ScoringParameters) -> u64 {
580 let mut inner_val = &mut this_ptr.get_native_mut_ref().overuse_penalty_msat_per_1024th;
583 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
584 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
586 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
587 /// to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
589 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
591 pub extern "C" fn ScoringParameters_set_overuse_penalty_msat_per_1024th(this_ptr: &mut ScoringParameters, mut val: u64) {
592 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.overuse_penalty_msat_per_1024th = val;
594 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
597 /// Successfully routing through a channel will immediately cut the penalty in half as well.
599 /// Default value: 1 hour
603 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
606 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
608 pub extern "C" fn ScoringParameters_get_failure_penalty_half_life(this_ptr: &ScoringParameters) -> u64 {
609 let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_half_life;
612 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
615 /// Successfully routing through a channel will immediately cut the penalty in half as well.
617 /// Default value: 1 hour
621 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
624 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
626 pub extern "C" fn ScoringParameters_set_failure_penalty_half_life(this_ptr: &mut ScoringParameters, mut val: u64) {
627 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_half_life = core::time::Duration::from_secs(val);
629 /// Constructs a new ScoringParameters given each field
632 pub extern "C" fn ScoringParameters_new(mut base_penalty_msat_arg: u64, mut failure_penalty_msat_arg: u64, mut overuse_penalty_start_1024th_arg: u16, mut overuse_penalty_msat_per_1024th_arg: u64, mut failure_penalty_half_life_arg: u64) -> ScoringParameters {
633 ScoringParameters { inner: ObjOps::heap_alloc(nativeScoringParameters {
634 base_penalty_msat: base_penalty_msat_arg,
635 failure_penalty_msat: failure_penalty_msat_arg,
636 overuse_penalty_start_1024th: overuse_penalty_start_1024th_arg,
637 overuse_penalty_msat_per_1024th: overuse_penalty_msat_per_1024th_arg,
638 failure_penalty_half_life: core::time::Duration::from_secs(failure_penalty_half_life_arg),
641 impl Clone for ScoringParameters {
642 fn clone(&self) -> Self {
644 inner: if <*mut nativeScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
645 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
651 /// Used only if an object of this type is returned as a trait impl by a method
652 pub(crate) extern "C" fn ScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
653 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeScoringParameters)).clone() })) as *mut c_void
656 /// Creates a copy of the ScoringParameters
657 pub extern "C" fn ScoringParameters_clone(orig: &ScoringParameters) -> ScoringParameters {
661 /// Serialize the ScoringParameters object into a byte array which can be read by ScoringParameters_read
662 pub extern "C" fn ScoringParameters_write(obj: &ScoringParameters) -> crate::c_types::derived::CVec_u8Z {
663 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
666 pub(crate) extern "C" fn ScoringParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
667 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScoringParameters) })
670 /// Read a ScoringParameters from a byte array, created by ScoringParameters_write
671 pub extern "C" fn ScoringParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScoringParametersDecodeErrorZ {
672 let res: Result<lightning::routing::scoring::ScoringParameters, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
673 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::ScoringParameters { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
676 /// Creates a new scorer using the given scoring parameters.
679 pub extern "C" fn Scorer_new(mut params: crate::lightning::routing::scoring::ScoringParameters) -> Scorer {
680 let mut ret = lightning::routing::scoring::Scorer::new(*unsafe { Box::from_raw(params.take_inner()) });
681 Scorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
684 /// Creates a "default" Scorer. See struct and individual field documentaiton for details on which values are used.
687 pub extern "C" fn Scorer_default() -> Scorer {
688 Scorer { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
690 /// Creates a "default" ScoringParameters. See struct and individual field documentaiton for details on which values are used.
693 pub extern "C" fn ScoringParameters_default() -> ScoringParameters {
694 ScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
696 impl From<nativeScorer> for crate::lightning::routing::scoring::Score {
697 fn from(obj: nativeScorer) -> Self {
698 let mut rust_obj = Scorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
699 let mut ret = Scorer_as_Score(&rust_obj);
700 // 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
701 rust_obj.inner = core::ptr::null_mut();
702 ret.free = Some(Scorer_free_void);
706 /// Constructs a new Score which calls the relevant methods on this_arg.
707 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
709 pub extern "C" fn Scorer_as_Score(this_arg: &Scorer) -> crate::lightning::routing::scoring::Score {
710 crate::lightning::routing::scoring::Score {
711 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
713 channel_penalty_msat: Scorer_Score_channel_penalty_msat,
714 payment_path_failed: Scorer_Score_payment_path_failed,
715 payment_path_successful: Scorer_Score_payment_path_successful,
716 write: Scorer_write_void,
721 extern "C" fn Scorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, mut send_amt_msat: u64, mut capacity_msat: u64, _source: &crate::lightning::routing::network_graph::NodeId, _target: &crate::lightning::routing::network_graph::NodeId) -> u64 {
722 let mut ret = <nativeScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeScorer) }, short_channel_id, send_amt_msat, capacity_msat, _source.get_native_ref(), _target.get_native_ref());
725 extern "C" fn Scorer_Score_payment_path_failed(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
726 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
727 <nativeScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeScorer) }, &local__path[..], short_channel_id)
729 extern "C" fn Scorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
730 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
731 <nativeScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeScorer) }, &local_path[..])
735 /// Serialize the Scorer object into a byte array which can be read by Scorer_read
736 pub extern "C" fn Scorer_write(obj: &Scorer) -> crate::c_types::derived::CVec_u8Z {
737 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
740 pub(crate) extern "C" fn Scorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
741 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScorer) })
744 /// Read a Scorer from a byte array, created by Scorer_write
745 pub extern "C" fn Scorer_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScorerDecodeErrorZ {
746 let res: Result<lightning::routing::scoring::Scorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
747 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::Scorer { inner: ObjOps::heap_alloc(o), is_owned: true } }).into(), Err(mut e) => crate::c_types::CResultTempl::err( { crate::lightning::ln::msgs::DecodeError { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
751 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
752 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::network_graph::NetworkGraph>;
754 /// [`Score`] implementation using channel success probability distributions.
756 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
757 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
758 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
759 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
760 /// specific HTLC amount through a channel.
762 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
763 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
764 /// [`ProbabilisticScoringParameters`] for details.
766 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
767 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
768 /// volume are more likely to experience failed payment paths, which would need to be retried.
772 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
775 /// [1]: https://arxiv.org/abs/2107.05322
778 pub struct ProbabilisticScorer {
779 /// A pointer to the opaque Rust object.
781 /// Nearly everywhere, inner must be non-null, however in places where
782 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
783 pub inner: *mut nativeProbabilisticScorer,
784 /// Indicates that this is the only struct which contains the same pointer.
786 /// Rust functions which take ownership of an object provided via an argument require
787 /// this to be true and invalidate the object pointed to by inner.
791 impl Drop for ProbabilisticScorer {
793 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
794 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
798 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
800 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
802 /// Used only if an object of this type is returned as a trait impl by a method
803 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
804 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScorer); }
807 impl ProbabilisticScorer {
808 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
809 unsafe { &*ObjOps::untweak_ptr(self.inner) }
811 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
812 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
814 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
815 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
816 assert!(self.is_owned);
817 let ret = ObjOps::untweak_ptr(self.inner);
818 self.inner = core::ptr::null_mut();
823 use lightning::routing::scoring::ProbabilisticScoringParameters as nativeProbabilisticScoringParametersImport;
824 pub(crate) type nativeProbabilisticScoringParameters = nativeProbabilisticScoringParametersImport;
826 /// Parameters for configuring [`ProbabilisticScorer`].
828 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
829 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
832 pub struct ProbabilisticScoringParameters {
833 /// A pointer to the opaque Rust object.
835 /// Nearly everywhere, inner must be non-null, however in places where
836 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
837 pub inner: *mut nativeProbabilisticScoringParameters,
838 /// Indicates that this is the only struct which contains the same pointer.
840 /// Rust functions which take ownership of an object provided via an argument require
841 /// this to be true and invalidate the object pointed to by inner.
845 impl Drop for ProbabilisticScoringParameters {
847 if self.is_owned && !<*mut nativeProbabilisticScoringParameters>::is_null(self.inner) {
848 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
852 /// Frees any resources used by the ProbabilisticScoringParameters, if is_owned is set and inner is non-NULL.
854 pub extern "C" fn ProbabilisticScoringParameters_free(this_obj: ProbabilisticScoringParameters) { }
856 /// Used only if an object of this type is returned as a trait impl by a method
857 pub(crate) extern "C" fn ProbabilisticScoringParameters_free_void(this_ptr: *mut c_void) {
858 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScoringParameters); }
861 impl ProbabilisticScoringParameters {
862 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringParameters {
863 unsafe { &*ObjOps::untweak_ptr(self.inner) }
865 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringParameters {
866 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
868 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
869 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringParameters {
870 assert!(self.is_owned);
871 let ret = ObjOps::untweak_ptr(self.inner);
872 self.inner = core::ptr::null_mut();
876 /// A fixed penalty in msats to apply to each channel.
878 /// Default value: 500 msat
880 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
881 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
884 /// A fixed penalty in msats to apply to each channel.
886 /// Default value: 500 msat
888 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
889 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
891 /// A multiplier used in conjunction with the negative `log10` of the channel's success
892 /// probability for a payment to determine the liquidity penalty.
894 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
895 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
896 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
897 /// lower bounding the success probability to `0.01`) when the amount falls within the
898 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
899 /// result in a `u64::max_value` penalty, however.
901 /// Default value: 40,000 msat
903 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
905 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
906 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
909 /// A multiplier used in conjunction with the negative `log10` of the channel's success
910 /// probability for a payment to determine the liquidity penalty.
912 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
913 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
914 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
915 /// lower bounding the success probability to `0.01`) when the amount falls within the
916 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
917 /// result in a `u64::max_value` penalty, however.
919 /// Default value: 40,000 msat
921 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
923 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
924 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
926 /// The time required to elapse before any knowledge learned about channel liquidity balances is
929 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
930 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
931 /// the certainty of the channel liquidity balance.
933 /// Default value: 1 hour
937 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
938 /// liquidity knowledge will never decay except when the bounds cross.
940 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 {
941 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
944 /// The time required to elapse before any knowledge learned about channel liquidity balances is
947 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
948 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
949 /// the certainty of the channel liquidity balance.
951 /// Default value: 1 hour
955 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
956 /// liquidity knowledge will never decay except when the bounds cross.
958 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
959 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
961 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
962 /// channel's success probability for the payment to determine the amount penalty.
964 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
965 /// fees plus penalty) for large payments. The penalty is computed as the product of this
966 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
967 /// success probability.
969 /// `-log10(success_probability) * amount_penalty_multiplier_msat * amount_msat / 2^20`
971 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
972 /// the amount will result in a penalty of the multiplier. And, as the success probability
973 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
974 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
977 /// Default value: 256 msat
979 pub extern "C" fn ProbabilisticScoringParameters_get_amount_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
980 let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_penalty_multiplier_msat;
983 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
984 /// channel's success probability for the payment to determine the amount penalty.
986 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
987 /// fees plus penalty) for large payments. The penalty is computed as the product of this
988 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
989 /// success probability.
991 /// `-log10(success_probability) * amount_penalty_multiplier_msat * amount_msat / 2^20`
993 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
994 /// the amount will result in a penalty of the multiplier. And, as the success probability
995 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
996 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
999 /// Default value: 256 msat
1001 pub extern "C" fn ProbabilisticScoringParameters_set_amount_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
1002 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_penalty_multiplier_msat = val;
1004 /// Constructs a new ProbabilisticScoringParameters given each field
1007 pub extern "C" fn ProbabilisticScoringParameters_new(mut base_penalty_msat_arg: u64, mut liquidity_penalty_multiplier_msat_arg: u64, mut liquidity_offset_half_life_arg: u64, mut amount_penalty_multiplier_msat_arg: u64) -> ProbabilisticScoringParameters {
1008 ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(nativeProbabilisticScoringParameters {
1009 base_penalty_msat: base_penalty_msat_arg,
1010 liquidity_penalty_multiplier_msat: liquidity_penalty_multiplier_msat_arg,
1011 liquidity_offset_half_life: core::time::Duration::from_secs(liquidity_offset_half_life_arg),
1012 amount_penalty_multiplier_msat: amount_penalty_multiplier_msat_arg,
1013 }), is_owned: true }
1015 impl Clone for ProbabilisticScoringParameters {
1016 fn clone(&self) -> Self {
1018 inner: if <*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
1019 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
1025 /// Used only if an object of this type is returned as a trait impl by a method
1026 pub(crate) extern "C" fn ProbabilisticScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
1027 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringParameters)).clone() })) as *mut c_void
1030 /// Creates a copy of the ProbabilisticScoringParameters
1031 pub extern "C" fn ProbabilisticScoringParameters_clone(orig: &ProbabilisticScoringParameters) -> ProbabilisticScoringParameters {
1034 /// Creates a new scorer using the given scoring parameters for sending payments from a node
1035 /// through a network graph.
1038 pub extern "C" fn ProbabilisticScorer_new(mut params: crate::lightning::routing::scoring::ProbabilisticScoringParameters, network_graph: &crate::lightning::routing::network_graph::NetworkGraph) -> ProbabilisticScorer {
1039 let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(params.take_inner()) }, network_graph.get_native_ref());
1040 ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
1043 /// Creates a "default" ProbabilisticScoringParameters. See struct and individual field documentaiton for details on which values are used.
1046 pub extern "C" fn ProbabilisticScoringParameters_default() -> ProbabilisticScoringParameters {
1047 ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
1049 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
1050 fn from(obj: nativeProbabilisticScorer) -> Self {
1051 let mut rust_obj = ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
1052 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
1053 // 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
1054 rust_obj.inner = core::ptr::null_mut();
1055 ret.free = Some(ProbabilisticScorer_free_void);
1059 /// Constructs a new Score which calls the relevant methods on this_arg.
1060 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
1062 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
1063 crate::lightning::routing::scoring::Score {
1064 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1066 channel_penalty_msat: ProbabilisticScorer_Score_channel_penalty_msat,
1067 payment_path_failed: ProbabilisticScorer_Score_payment_path_failed,
1068 payment_path_successful: ProbabilisticScorer_Score_payment_path_successful,
1069 write: ProbabilisticScorer_write_void,
1074 extern "C" fn ProbabilisticScorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, mut amount_msat: u64, mut capacity_msat: u64, source: &crate::lightning::routing::network_graph::NodeId, target: &crate::lightning::routing::network_graph::NodeId) -> u64 {
1075 let mut ret = <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, short_channel_id, amount_msat, capacity_msat, source.get_native_ref(), target.get_native_ref());
1078 extern "C" fn ProbabilisticScorer_Score_payment_path_failed(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
1079 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1080 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id)
1082 extern "C" fn ProbabilisticScorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
1083 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1084 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..])
1089 use alloc::str::FromStr;
1090 use core::ffi::c_void;
1091 use core::convert::Infallible;
1092 use bitcoin::hashes::Hash;
1093 use crate::c_types::*;
1094 #[cfg(feature="no-std")]
1095 use alloc::{vec::Vec, boxed::Box};
1099 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
1100 pub extern "C" fn ProbabilisticScorer_write(obj: &ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
1101 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1104 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1105 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
1108 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
1109 pub extern "C" fn ProbabilisticScorer_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::routing::scoring::ProbabilisticScoringParameters, arg_b: &crate::lightning::routing::network_graph::NetworkGraph) -> crate::c_types::derived::CResult_ProbabilisticScorerDecodeErrorZ {
1110 let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
1111 let arg_b_conv = arg_b.get_native_ref();
1112 let arg_conv = (arg_a_conv, arg_b_conv);
1113 let res: Result<lightning::routing::scoring::ProbabilisticScorer<&lightning::routing::network_graph::NetworkGraph>, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
1114 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 { inner: ObjOps::heap_alloc(e), is_owned: true } }).into() };
1119 use alloc::str::FromStr;
1120 use core::ffi::c_void;
1121 use core::convert::Infallible;
1122 use bitcoin::hashes::Hash;
1123 use crate::c_types::*;
1124 #[cfg(feature="no-std")]
1125 use alloc::{vec::Vec, boxed::Box};