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::util::logger::{Logger, Record};
23 //! # use secp256k1::key::PublicKey;
25 //! # struct FakeLogger {};
26 //! # impl Logger for FakeLogger {
27 //! # fn log(&self, record: &Record) { unimplemented!() }
29 //! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph) {
30 //! # let logger = FakeLogger {};
32 //! // Use the default channel penalties.
33 //! let params = ProbabilisticScoringParameters::default();
34 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
36 //! // Or use custom channel penalties.
37 //! let params = ProbabilisticScoringParameters {
38 //! liquidity_penalty_multiplier_msat: 2 * 1000,
39 //! ..ProbabilisticScoringParameters::default()
41 //! let scorer = ProbabilisticScorer::new(params, &network_graph);
43 //! let route = find_route(&payer, &route_params, &network_graph, None, &logger, &scorer);
49 //! Persisting when built with feature `no-std` and restoring without it, or vice versa, uses
50 //! different types and thus is undefined.
52 //! [`find_route`]: crate::routing::router::find_route
54 use alloc::str::FromStr;
55 use core::ffi::c_void;
56 use core::convert::Infallible;
57 use bitcoin::hashes::Hash;
58 use crate::c_types::*;
59 #[cfg(feature="no-std")]
60 use alloc::{vec::Vec, boxed::Box};
62 /// An interface used to score payment channels for path finding.
64 ///\tScoring is in terms of fees willing to be paid in order to avoid routing through a channel.
67 /// An opaque pointer which is passed to your function implementations as an argument.
68 /// This has no meaning in the LDK, and can be NULL or any other value.
69 pub this_arg: *mut c_void,
70 /// Returns the fee in msats willing to be paid to avoid routing `send_amt_msat` through the
71 /// given channel in the direction from `source` to `target`.
73 /// The channel's capacity (less any other MPP parts that are also being considered for use in
74 /// the same payment) is given by `capacity_msat`. It may be determined from various sources
75 /// such as a chain data, network gossip, or invoice hints. For invoice hints, a capacity near
76 /// [`u64::max_value`] is given to indicate sufficient capacity for the invoice's full amount.
77 /// Thus, implementations should be overflow-safe.
79 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,
80 /// Handles updating channel penalties after failing to route through a channel.
81 pub payment_path_failed: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64),
82 /// Handles updating channel penalties after successfully routing along a path.
83 pub payment_path_successful: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ),
84 /// Serialize the object into a byte array
85 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
86 /// Frees any resources associated with this object given its this_arg pointer.
87 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
88 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
90 unsafe impl Send for Score {}
91 unsafe impl Sync for Score {}
93 pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score {
95 this_arg: orig.this_arg,
96 channel_penalty_msat: Clone::clone(&orig.channel_penalty_msat),
97 payment_path_failed: Clone::clone(&orig.payment_path_failed),
98 payment_path_successful: Clone::clone(&orig.payment_path_successful),
99 write: Clone::clone(&orig.write),
100 free: Clone::clone(&orig.free),
103 impl lightning::util::ser::Writeable for Score {
104 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
105 let vec = (self.write)(self.this_arg);
106 w.write_all(vec.as_slice())
110 use lightning::routing::scoring::Score as rustScore;
111 impl rustScore for Score {
112 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 {
113 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 });
116 fn payment_path_failed(&mut self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) {
117 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 } }); };
118 (self.payment_path_failed)(self.this_arg, local_path.into(), short_channel_id)
120 fn payment_path_successful(&mut self, mut path: &[&lightning::routing::router::RouteHop]) {
121 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 } }); };
122 (self.payment_path_successful)(self.this_arg, local_path.into())
126 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
127 // directly as a Deref trait in higher-level structs:
128 impl core::ops::Deref for Score {
130 fn deref(&self) -> &Self {
134 /// Calls the free function if one is set
136 pub extern "C" fn Score_free(this_ptr: Score) { }
137 impl Drop for Score {
139 if let Some(f) = self.free {
144 /// A scorer that is accessed under a lock.
146 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
147 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
148 /// implementations. Internal locking would be detrimental to route finding performance and could
149 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
151 /// [`find_route`]: crate::routing::router::find_route
153 pub struct LockableScore {
154 /// An opaque pointer which is passed to your function implementations as an argument.
155 /// This has no meaning in the LDK, and can be NULL or any other value.
156 pub this_arg: *mut c_void,
157 /// Returns the locked scorer.
159 pub lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::Score,
160 /// Frees any resources associated with this object given its this_arg pointer.
161 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
162 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
164 unsafe impl Send for LockableScore {}
165 unsafe impl Sync for LockableScore {}
167 pub(crate) extern "C" fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
169 this_arg: orig.this_arg,
170 lock: Clone::clone(&orig.lock),
171 free: Clone::clone(&orig.free),
175 use lightning::routing::scoring::LockableScore as rustLockableScore;
176 impl<'a> rustLockableScore<'a> for LockableScore {
177 type Locked = crate::lightning::routing::scoring::Score;
178 fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
179 let mut ret = (self.lock)(self.this_arg);
184 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
185 // directly as a Deref trait in higher-level structs:
186 impl core::ops::Deref for LockableScore {
188 fn deref(&self) -> &Self {
192 /// Calls the free function if one is set
194 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
195 impl Drop for LockableScore {
197 if let Some(f) = self.free {
203 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
204 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
206 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
209 pub struct MultiThreadedLockableScore {
210 /// A pointer to the opaque Rust object.
212 /// Nearly everywhere, inner must be non-null, however in places where
213 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
214 pub inner: *mut nativeMultiThreadedLockableScore,
215 /// Indicates that this is the only struct which contains the same pointer.
217 /// Rust functions which take ownership of an object provided via an argument require
218 /// this to be true and invalidate the object pointed to by inner.
222 impl Drop for MultiThreadedLockableScore {
224 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
225 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
229 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
231 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
233 /// Used only if an object of this type is returned as a trait impl by a method
234 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
235 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore); }
238 impl MultiThreadedLockableScore {
239 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
240 unsafe { &*ObjOps::untweak_ptr(self.inner) }
242 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
243 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
245 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
246 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
247 assert!(self.is_owned);
248 let ret = ObjOps::untweak_ptr(self.inner);
249 self.inner = core::ptr::null_mut();
253 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
256 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> MultiThreadedLockableScore {
257 let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
258 MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
262 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
263 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
265 /// [`Score`] implementation that uses a fixed penalty.
268 pub struct FixedPenaltyScorer {
269 /// A pointer to the opaque Rust object.
271 /// Nearly everywhere, inner must be non-null, however in places where
272 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
273 pub inner: *mut nativeFixedPenaltyScorer,
274 /// Indicates that this is the only struct which contains the same pointer.
276 /// Rust functions which take ownership of an object provided via an argument require
277 /// this to be true and invalidate the object pointed to by inner.
281 impl Drop for FixedPenaltyScorer {
283 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
284 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
288 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
290 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
292 /// Used only if an object of this type is returned as a trait impl by a method
293 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
294 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer); }
297 impl FixedPenaltyScorer {
298 pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
299 unsafe { &*ObjOps::untweak_ptr(self.inner) }
301 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
302 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
304 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
305 pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
306 assert!(self.is_owned);
307 let ret = ObjOps::untweak_ptr(self.inner);
308 self.inner = core::ptr::null_mut();
313 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
314 pub extern "C" fn FixedPenaltyScorer_write(obj: &FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
315 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
318 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
319 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
322 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
323 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
324 let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
325 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() };
328 /// Creates a new scorer using `penalty_msat`.
331 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> FixedPenaltyScorer {
332 let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
333 FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
336 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::Score {
337 fn from(obj: nativeFixedPenaltyScorer) -> Self {
338 let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
339 let mut ret = FixedPenaltyScorer_as_Score(&rust_obj);
340 // 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
341 rust_obj.inner = core::ptr::null_mut();
342 ret.free = Some(FixedPenaltyScorer_free_void);
346 /// Constructs a new Score which calls the relevant methods on this_arg.
347 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
349 pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score {
350 crate::lightning::routing::scoring::Score {
351 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
353 channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat,
354 payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed,
355 payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful,
356 write: FixedPenaltyScorer_write_void,
361 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 {
362 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());
365 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) {
366 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
367 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..], _short_channel_id)
369 extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ) {
370 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
371 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..])
375 use lightning::routing::scoring::Scorer as nativeScorerImport;
376 pub(crate) type nativeScorer = nativeScorerImport;
378 /// [`Score`] implementation that provides reasonable default behavior.
380 /// Used to apply a fixed penalty to each channel, thus avoiding long paths when shorter paths with
381 /// slightly higher fees are available. Will further penalize channels that fail to relay payments.
383 /// See [module-level documentation] for usage and [`ScoringParameters`] for customization.
387 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
390 /// [module-level documentation]: crate::routing::scoring
394 /// A pointer to the opaque Rust object.
396 /// Nearly everywhere, inner must be non-null, however in places where
397 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
398 pub inner: *mut nativeScorer,
399 /// Indicates that this is the only struct which contains the same pointer.
401 /// Rust functions which take ownership of an object provided via an argument require
402 /// this to be true and invalidate the object pointed to by inner.
406 impl Drop for Scorer {
408 if self.is_owned && !<*mut nativeScorer>::is_null(self.inner) {
409 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
413 /// Frees any resources used by the Scorer, if is_owned is set and inner is non-NULL.
415 pub extern "C" fn Scorer_free(this_obj: Scorer) { }
417 /// Used only if an object of this type is returned as a trait impl by a method
418 pub(crate) extern "C" fn Scorer_free_void(this_ptr: *mut c_void) {
419 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScorer); }
423 pub(crate) fn get_native_ref(&self) -> &'static nativeScorer {
424 unsafe { &*ObjOps::untweak_ptr(self.inner) }
426 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScorer {
427 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
429 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
430 pub(crate) fn take_inner(mut self) -> *mut nativeScorer {
431 assert!(self.is_owned);
432 let ret = ObjOps::untweak_ptr(self.inner);
433 self.inner = core::ptr::null_mut();
438 use lightning::routing::scoring::ScoringParameters as nativeScoringParametersImport;
439 pub(crate) type nativeScoringParameters = nativeScoringParametersImport;
441 /// Parameters for configuring [`Scorer`].
444 pub struct ScoringParameters {
445 /// A pointer to the opaque Rust object.
447 /// Nearly everywhere, inner must be non-null, however in places where
448 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
449 pub inner: *mut nativeScoringParameters,
450 /// Indicates that this is the only struct which contains the same pointer.
452 /// Rust functions which take ownership of an object provided via an argument require
453 /// this to be true and invalidate the object pointed to by inner.
457 impl Drop for ScoringParameters {
459 if self.is_owned && !<*mut nativeScoringParameters>::is_null(self.inner) {
460 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
464 /// Frees any resources used by the ScoringParameters, if is_owned is set and inner is non-NULL.
466 pub extern "C" fn ScoringParameters_free(this_obj: ScoringParameters) { }
468 /// Used only if an object of this type is returned as a trait impl by a method
469 pub(crate) extern "C" fn ScoringParameters_free_void(this_ptr: *mut c_void) {
470 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeScoringParameters); }
473 impl ScoringParameters {
474 pub(crate) fn get_native_ref(&self) -> &'static nativeScoringParameters {
475 unsafe { &*ObjOps::untweak_ptr(self.inner) }
477 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeScoringParameters {
478 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
480 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
481 pub(crate) fn take_inner(mut self) -> *mut nativeScoringParameters {
482 assert!(self.is_owned);
483 let ret = ObjOps::untweak_ptr(self.inner);
484 self.inner = core::ptr::null_mut();
488 /// A fixed penalty in msats to apply to each channel.
490 /// Default value: 500 msat
492 pub extern "C" fn ScoringParameters_get_base_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
493 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
496 /// A fixed penalty in msats to apply to each channel.
498 /// Default value: 500 msat
500 pub extern "C" fn ScoringParameters_set_base_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
501 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
503 /// A penalty in msats to apply to a channel upon failing to relay a payment.
505 /// This accumulates for each failure but may be reduced over time based on
506 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
508 /// Default value: 1,024,000 msat
510 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
512 pub extern "C" fn ScoringParameters_get_failure_penalty_msat(this_ptr: &ScoringParameters) -> u64 {
513 let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_msat;
516 /// A penalty in msats to apply to a channel upon failing to relay a payment.
518 /// This accumulates for each failure but may be reduced over time based on
519 /// [`failure_penalty_half_life`] or when successfully routing through a channel.
521 /// Default value: 1,024,000 msat
523 /// [`failure_penalty_half_life`]: Self::failure_penalty_half_life
525 pub extern "C" fn ScoringParameters_set_failure_penalty_msat(this_ptr: &mut ScoringParameters, mut val: u64) {
526 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_msat = val;
528 /// When the amount being sent over a channel is this many 1024ths of the total channel
529 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
531 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
533 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
535 pub extern "C" fn ScoringParameters_get_overuse_penalty_start_1024th(this_ptr: &ScoringParameters) -> u16 {
536 let mut inner_val = &mut this_ptr.get_native_mut_ref().overuse_penalty_start_1024th;
539 /// When the amount being sent over a channel is this many 1024ths of the total channel
540 /// capacity, we begin applying [`overuse_penalty_msat_per_1024th`].
542 /// Default value: 128 1024ths (i.e. begin penalizing when an HTLC uses 1/8th of a channel)
544 /// [`overuse_penalty_msat_per_1024th`]: Self::overuse_penalty_msat_per_1024th
546 pub extern "C" fn ScoringParameters_set_overuse_penalty_start_1024th(this_ptr: &mut ScoringParameters, mut val: u16) {
547 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.overuse_penalty_start_1024th = val;
549 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
550 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
552 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
553 /// to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
555 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
557 pub extern "C" fn ScoringParameters_get_overuse_penalty_msat_per_1024th(this_ptr: &ScoringParameters) -> u64 {
558 let mut inner_val = &mut this_ptr.get_native_mut_ref().overuse_penalty_msat_per_1024th;
561 /// A penalty applied, per whole 1024ths of the channel capacity which the amount being sent
562 /// over the channel exceeds [`overuse_penalty_start_1024th`] by.
564 /// Default value: 20 msat (i.e. 2560 msat penalty to use 1/4th of a channel, 7680 msat penalty
565 /// to use half a channel, and 12,560 msat penalty to use 3/4ths of a channel)
567 /// [`overuse_penalty_start_1024th`]: Self::overuse_penalty_start_1024th
569 pub extern "C" fn ScoringParameters_set_overuse_penalty_msat_per_1024th(this_ptr: &mut ScoringParameters, mut val: u64) {
570 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.overuse_penalty_msat_per_1024th = val;
572 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
575 /// Successfully routing through a channel will immediately cut the penalty in half as well.
577 /// Default value: 1 hour
581 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
584 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
586 pub extern "C" fn ScoringParameters_get_failure_penalty_half_life(this_ptr: &ScoringParameters) -> u64 {
587 let mut inner_val = &mut this_ptr.get_native_mut_ref().failure_penalty_half_life;
590 /// The time required to elapse before any accumulated [`failure_penalty_msat`] penalties are
593 /// Successfully routing through a channel will immediately cut the penalty in half as well.
595 /// Default value: 1 hour
599 /// When built with the `no-std` feature, time will never elapse. Therefore, this penalty will
602 /// [`failure_penalty_msat`]: Self::failure_penalty_msat
604 pub extern "C" fn ScoringParameters_set_failure_penalty_half_life(this_ptr: &mut ScoringParameters, mut val: u64) {
605 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.failure_penalty_half_life = core::time::Duration::from_secs(val);
607 /// Constructs a new ScoringParameters given each field
610 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 {
611 ScoringParameters { inner: ObjOps::heap_alloc(nativeScoringParameters {
612 base_penalty_msat: base_penalty_msat_arg,
613 failure_penalty_msat: failure_penalty_msat_arg,
614 overuse_penalty_start_1024th: overuse_penalty_start_1024th_arg,
615 overuse_penalty_msat_per_1024th: overuse_penalty_msat_per_1024th_arg,
616 failure_penalty_half_life: core::time::Duration::from_secs(failure_penalty_half_life_arg),
620 /// Serialize the ScoringParameters object into a byte array which can be read by ScoringParameters_read
621 pub extern "C" fn ScoringParameters_write(obj: &ScoringParameters) -> crate::c_types::derived::CVec_u8Z {
622 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
625 pub(crate) extern "C" fn ScoringParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
626 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScoringParameters) })
629 /// Read a ScoringParameters from a byte array, created by ScoringParameters_write
630 pub extern "C" fn ScoringParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScoringParametersDecodeErrorZ {
631 let res: Result<lightning::routing::scoring::ScoringParameters, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
632 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() };
635 /// Creates a new scorer using the given scoring parameters.
638 pub extern "C" fn Scorer_new(mut params: crate::lightning::routing::scoring::ScoringParameters) -> Scorer {
639 let mut ret = lightning::routing::scoring::Scorer::new(*unsafe { Box::from_raw(params.take_inner()) });
640 Scorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
643 /// Creates a "default" Scorer. See struct and individual field documentaiton for details on which values are used.
646 pub extern "C" fn Scorer_default() -> Scorer {
647 Scorer { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
649 /// Creates a "default" ScoringParameters. See struct and individual field documentaiton for details on which values are used.
652 pub extern "C" fn ScoringParameters_default() -> ScoringParameters {
653 ScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
655 impl From<nativeScorer> for crate::lightning::routing::scoring::Score {
656 fn from(obj: nativeScorer) -> Self {
657 let mut rust_obj = Scorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
658 let mut ret = Scorer_as_Score(&rust_obj);
659 // 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
660 rust_obj.inner = core::ptr::null_mut();
661 ret.free = Some(Scorer_free_void);
665 /// Constructs a new Score which calls the relevant methods on this_arg.
666 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
668 pub extern "C" fn Scorer_as_Score(this_arg: &Scorer) -> crate::lightning::routing::scoring::Score {
669 crate::lightning::routing::scoring::Score {
670 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
672 channel_penalty_msat: Scorer_Score_channel_penalty_msat,
673 payment_path_failed: Scorer_Score_payment_path_failed,
674 payment_path_successful: Scorer_Score_payment_path_successful,
675 write: Scorer_write_void,
680 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 {
681 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());
684 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) {
685 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
686 <nativeScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeScorer) }, &local__path[..], short_channel_id)
688 extern "C" fn Scorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
689 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
690 <nativeScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeScorer) }, &local_path[..])
694 /// Serialize the Scorer object into a byte array which can be read by Scorer_read
695 pub extern "C" fn Scorer_write(obj: &Scorer) -> crate::c_types::derived::CVec_u8Z {
696 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
699 pub(crate) extern "C" fn Scorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
700 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeScorer) })
703 /// Read a Scorer from a byte array, created by Scorer_write
704 pub extern "C" fn Scorer_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ScorerDecodeErrorZ {
705 let res: Result<lightning::routing::scoring::Scorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
706 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() };
710 use lightning::routing::scoring::ProbabilisticScoringParameters as nativeProbabilisticScoringParametersImport;
711 pub(crate) type nativeProbabilisticScoringParameters = nativeProbabilisticScoringParametersImport;
713 /// Parameters for configuring [`ProbabilisticScorer`].
716 pub struct ProbabilisticScoringParameters {
717 /// A pointer to the opaque Rust object.
719 /// Nearly everywhere, inner must be non-null, however in places where
720 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
721 pub inner: *mut nativeProbabilisticScoringParameters,
722 /// Indicates that this is the only struct which contains the same pointer.
724 /// Rust functions which take ownership of an object provided via an argument require
725 /// this to be true and invalidate the object pointed to by inner.
729 impl Drop for ProbabilisticScoringParameters {
731 if self.is_owned && !<*mut nativeProbabilisticScoringParameters>::is_null(self.inner) {
732 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
736 /// Frees any resources used by the ProbabilisticScoringParameters, if is_owned is set and inner is non-NULL.
738 pub extern "C" fn ProbabilisticScoringParameters_free(this_obj: ProbabilisticScoringParameters) { }
740 /// Used only if an object of this type is returned as a trait impl by a method
741 pub(crate) extern "C" fn ProbabilisticScoringParameters_free_void(this_ptr: *mut c_void) {
742 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScoringParameters); }
745 impl ProbabilisticScoringParameters {
746 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringParameters {
747 unsafe { &*ObjOps::untweak_ptr(self.inner) }
749 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringParameters {
750 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
752 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
753 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringParameters {
754 assert!(self.is_owned);
755 let ret = ObjOps::untweak_ptr(self.inner);
756 self.inner = core::ptr::null_mut();
760 /// A multiplier used to determine the amount in msats willing to be paid to avoid routing
761 /// through a channel, as per multiplying by the negative `log10` of the channel's success
762 /// probability for a payment.
764 /// The success probability is determined by the effective channel capacity, the payment amount,
765 /// and knowledge learned from prior successful and unsuccessful payments. The lower bound of
766 /// the success probability is 0.01, effectively limiting the penalty to the range
767 /// `0..=2*liquidity_penalty_multiplier_msat`. The knowledge learned is decayed over time based
768 /// on [`liquidity_offset_half_life`].
770 /// Default value: 10,000 msat
772 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
774 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
775 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
778 /// A multiplier used to determine the amount in msats willing to be paid to avoid routing
779 /// through a channel, as per multiplying by the negative `log10` of the channel's success
780 /// probability for a payment.
782 /// The success probability is determined by the effective channel capacity, the payment amount,
783 /// and knowledge learned from prior successful and unsuccessful payments. The lower bound of
784 /// the success probability is 0.01, effectively limiting the penalty to the range
785 /// `0..=2*liquidity_penalty_multiplier_msat`. The knowledge learned is decayed over time based
786 /// on [`liquidity_offset_half_life`].
788 /// Default value: 10,000 msat
790 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
792 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
793 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
795 /// The time required to elapse before any knowledge learned about channel liquidity balances is
798 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
799 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
800 /// the certainty of the channel liquidity balance.
802 /// Default value: 1 hour
806 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
807 /// liquidity knowledge will never decay except when the bounds cross.
809 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 {
810 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
813 /// The time required to elapse before any knowledge learned about channel liquidity balances is
816 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
817 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
818 /// the certainty of the channel liquidity balance.
820 /// Default value: 1 hour
824 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
825 /// liquidity knowledge will never decay except when the bounds cross.
827 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
828 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
830 /// Constructs a new ProbabilisticScoringParameters given each field
833 pub extern "C" fn ProbabilisticScoringParameters_new(mut liquidity_penalty_multiplier_msat_arg: u64, mut liquidity_offset_half_life_arg: u64) -> ProbabilisticScoringParameters {
834 ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(nativeProbabilisticScoringParameters {
835 liquidity_penalty_multiplier_msat: liquidity_penalty_multiplier_msat_arg,
836 liquidity_offset_half_life: core::time::Duration::from_secs(liquidity_offset_half_life_arg),
839 impl Clone for ProbabilisticScoringParameters {
840 fn clone(&self) -> Self {
842 inner: if <*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
843 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
849 /// Used only if an object of this type is returned as a trait impl by a method
850 pub(crate) extern "C" fn ProbabilisticScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
851 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringParameters)).clone() })) as *mut c_void
854 /// Creates a copy of the ProbabilisticScoringParameters
855 pub extern "C" fn ProbabilisticScoringParameters_clone(orig: &ProbabilisticScoringParameters) -> ProbabilisticScoringParameters {
859 /// Serialize the ProbabilisticScoringParameters object into a byte array which can be read by ProbabilisticScoringParameters_read
860 pub extern "C" fn ProbabilisticScoringParameters_write(obj: &ProbabilisticScoringParameters) -> crate::c_types::derived::CVec_u8Z {
861 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
864 pub(crate) extern "C" fn ProbabilisticScoringParameters_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
865 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScoringParameters) })
868 /// Read a ProbabilisticScoringParameters from a byte array, created by ProbabilisticScoringParameters_write
869 pub extern "C" fn ProbabilisticScoringParameters_read(ser: crate::c_types::u8slice) -> crate::c_types::derived::CResult_ProbabilisticScoringParametersDecodeErrorZ {
870 let res: Result<lightning::routing::scoring::ProbabilisticScoringParameters, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj(ser);
871 let mut local_res = match res { Ok(mut o) => crate::c_types::CResultTempl::ok( { crate::lightning::routing::scoring::ProbabilisticScoringParameters { 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() };
874 /// Creates a "default" ProbabilisticScoringParameters. See struct and individual field documentaiton for details on which values are used.
877 pub extern "C" fn ProbabilisticScoringParameters_default() -> ProbabilisticScoringParameters {
878 ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
882 use alloc::str::FromStr;
883 use core::ffi::c_void;
884 use core::convert::Infallible;
885 use bitcoin::hashes::Hash;
886 use crate::c_types::*;
887 #[cfg(feature="no-std")]
888 use alloc::{vec::Vec, boxed::Box};