1 // This file is Copyright its original authors, visible in version control
2 // history and in the source files from which this was generated.
4 // This file is licensed under the license available in the LICENSE or LICENSE.md
5 // file in the root of this repository or, if no such file exists, the same
6 // license as that which applies to the original source files from which this
7 // source was automatically generated.
9 //! Utilities for scoring payment channels.
11 //! [`ProbabilisticScorer`] may be given to [`find_route`] to score payment channels during path
12 //! finding when a custom [`Score`] implementation is not needed.
17 //! # extern crate bitcoin;
19 //! # use lightning::routing::gossip::NetworkGraph;
20 //! # use lightning::routing::router::{RouteParameters, find_route};
21 //! # use lightning::routing::scoring::{ProbabilisticScorer, ProbabilisticScoringParameters};
22 //! # use lightning::chain::keysinterface::{KeysManager, KeysInterface};
23 //! # use lightning::util::logger::{Logger, Record};
24 //! # use bitcoin::secp256k1::PublicKey;
26 //! # struct FakeLogger {};
27 //! # impl Logger for FakeLogger {
28 //! # fn log(&self, record: &Record) { unimplemented!() }
30 //! # fn find_scored_route(payer: PublicKey, route_params: RouteParameters, network_graph: NetworkGraph<&FakeLogger>) {
31 //! # let logger = FakeLogger {};
33 //! // Use the default channel penalties.
34 //! let params = ProbabilisticScoringParameters::default();
35 //! let scorer = ProbabilisticScorer::new(params, &network_graph, &logger);
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, &logger);
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, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, usage: crate::lightning::routing::scoring::ChannelUsage) -> 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 /// Handles updating channel penalties after a probe over the given path failed.
87 pub probe_failed: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ, short_channel_id: u64),
88 /// Handles updating channel penalties after a probe over the given path succeeded.
89 pub probe_successful: extern "C" fn (this_arg: *mut c_void, path: crate::c_types::derived::CVec_RouteHopZ),
90 /// Serialize the object into a byte array
91 pub write: extern "C" fn (this_arg: *const c_void) -> crate::c_types::derived::CVec_u8Z,
92 /// Frees any resources associated with this object given its this_arg pointer.
93 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
94 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
96 unsafe impl Send for Score {}
97 unsafe impl Sync for Score {}
99 pub(crate) extern "C" fn Score_clone_fields(orig: &Score) -> Score {
101 this_arg: orig.this_arg,
102 channel_penalty_msat: Clone::clone(&orig.channel_penalty_msat),
103 payment_path_failed: Clone::clone(&orig.payment_path_failed),
104 payment_path_successful: Clone::clone(&orig.payment_path_successful),
105 probe_failed: Clone::clone(&orig.probe_failed),
106 probe_successful: Clone::clone(&orig.probe_successful),
107 write: Clone::clone(&orig.write),
108 free: Clone::clone(&orig.free),
111 impl lightning::util::ser::Writeable for Score {
112 fn write<W: lightning::util::ser::Writer>(&self, w: &mut W) -> Result<(), crate::c_types::io::Error> {
113 let vec = (self.write)(self.this_arg);
114 w.write_all(vec.as_slice())
118 use lightning::routing::scoring::Score as rustScore;
119 impl rustScore for Score {
120 fn channel_penalty_msat(&self, mut short_channel_id: u64, mut source: &lightning::routing::gossip::NodeId, mut target: &lightning::routing::gossip::NodeId, mut usage: lightning::routing::scoring::ChannelUsage) -> u64 {
121 let mut ret = (self.channel_penalty_msat)(self.this_arg, short_channel_id, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((source as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, &crate::lightning::routing::gossip::NodeId { inner: unsafe { ObjOps::nonnull_ptr_to_inner((target as *const lightning::routing::gossip::NodeId<>) as *mut _) }, is_owned: false }, crate::lightning::routing::scoring::ChannelUsage { inner: ObjOps::heap_alloc(usage), is_owned: true });
124 fn payment_path_failed(&mut self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) {
125 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 } }); };
126 (self.payment_path_failed)(self.this_arg, local_path.into(), short_channel_id)
128 fn payment_path_successful(&mut self, mut path: &[&lightning::routing::router::RouteHop]) {
129 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 } }); };
130 (self.payment_path_successful)(self.this_arg, local_path.into())
132 fn probe_failed(&mut self, mut path: &[&lightning::routing::router::RouteHop], mut short_channel_id: u64) {
133 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 } }); };
134 (self.probe_failed)(self.this_arg, local_path.into(), short_channel_id)
136 fn probe_successful(&mut self, mut path: &[&lightning::routing::router::RouteHop]) {
137 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 } }); };
138 (self.probe_successful)(self.this_arg, local_path.into())
142 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
143 // directly as a Deref trait in higher-level structs:
144 impl core::ops::Deref for Score {
146 fn deref(&self) -> &Self {
150 /// Calls the free function if one is set
152 pub extern "C" fn Score_free(this_ptr: Score) { }
153 impl Drop for Score {
155 if let Some(f) = self.free {
160 /// A scorer that is accessed under a lock.
162 /// Needed so that calls to [`Score::channel_penalty_msat`] in [`find_route`] can be made while
163 /// having shared ownership of a scorer but without requiring internal locking in [`Score`]
164 /// implementations. Internal locking would be detrimental to route finding performance and could
165 /// result in [`Score::channel_penalty_msat`] returning a different value for the same channel.
167 /// [`find_route`]: crate::routing::router::find_route
169 pub struct LockableScore {
170 /// An opaque pointer which is passed to your function implementations as an argument.
171 /// This has no meaning in the LDK, and can be NULL or any other value.
172 pub this_arg: *mut c_void,
173 /// Returns the locked scorer.
175 pub lock: extern "C" fn (this_arg: *const c_void) -> crate::lightning::routing::scoring::Score,
176 /// Frees any resources associated with this object given its this_arg pointer.
177 /// Does not need to free the outer struct containing function pointers and may be NULL is no resources need to be freed.
178 pub free: Option<extern "C" fn(this_arg: *mut c_void)>,
180 unsafe impl Send for LockableScore {}
181 unsafe impl Sync for LockableScore {}
183 pub(crate) extern "C" fn LockableScore_clone_fields(orig: &LockableScore) -> LockableScore {
185 this_arg: orig.this_arg,
186 lock: Clone::clone(&orig.lock),
187 free: Clone::clone(&orig.free),
191 use lightning::routing::scoring::LockableScore as rustLockableScore;
192 impl<'a> rustLockableScore<'a> for LockableScore {
193 type Locked = crate::lightning::routing::scoring::Score;
194 fn lock(&'a self) -> crate::lightning::routing::scoring::Score {
195 let mut ret = (self.lock)(self.this_arg);
200 // We're essentially a pointer already, or at least a set of pointers, so allow us to be used
201 // directly as a Deref trait in higher-level structs:
202 impl core::ops::Deref for LockableScore {
204 fn deref(&self) -> &Self {
208 /// Calls the free function if one is set
210 pub extern "C" fn LockableScore_free(this_ptr: LockableScore) { }
211 impl Drop for LockableScore {
213 if let Some(f) = self.free {
219 use lightning::routing::scoring::MultiThreadedLockableScore as nativeMultiThreadedLockableScoreImport;
220 pub(crate) type nativeMultiThreadedLockableScore = nativeMultiThreadedLockableScoreImport<crate::lightning::routing::scoring::Score>;
222 /// A concrete implementation of [`LockableScore`] which supports multi-threading.
225 pub struct MultiThreadedLockableScore {
226 /// A pointer to the opaque Rust object.
228 /// Nearly everywhere, inner must be non-null, however in places where
229 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
230 pub inner: *mut nativeMultiThreadedLockableScore,
231 /// Indicates that this is the only struct which contains the same pointer.
233 /// Rust functions which take ownership of an object provided via an argument require
234 /// this to be true and invalidate the object pointed to by inner.
238 impl Drop for MultiThreadedLockableScore {
240 if self.is_owned && !<*mut nativeMultiThreadedLockableScore>::is_null(self.inner) {
241 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
245 /// Frees any resources used by the MultiThreadedLockableScore, if is_owned is set and inner is non-NULL.
247 pub extern "C" fn MultiThreadedLockableScore_free(this_obj: MultiThreadedLockableScore) { }
249 /// Used only if an object of this type is returned as a trait impl by a method
250 pub(crate) extern "C" fn MultiThreadedLockableScore_free_void(this_ptr: *mut c_void) {
251 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeMultiThreadedLockableScore); }
254 impl MultiThreadedLockableScore {
255 pub(crate) fn get_native_ref(&self) -> &'static nativeMultiThreadedLockableScore {
256 unsafe { &*ObjOps::untweak_ptr(self.inner) }
258 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeMultiThreadedLockableScore {
259 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
261 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
262 pub(crate) fn take_inner(mut self) -> *mut nativeMultiThreadedLockableScore {
263 assert!(self.is_owned);
264 let ret = ObjOps::untweak_ptr(self.inner);
265 self.inner = core::ptr::null_mut();
270 /// Serialize the MultiThreadedLockableScore object into a byte array which can be read by MultiThreadedLockableScore_read
271 pub extern "C" fn MultiThreadedLockableScore_write(obj: &crate::lightning::routing::scoring::MultiThreadedLockableScore) -> crate::c_types::derived::CVec_u8Z {
272 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
275 pub(crate) extern "C" fn MultiThreadedLockableScore_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
276 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeMultiThreadedLockableScore) })
278 /// Creates a new [`MultiThreadedLockableScore`] given an underlying [`Score`].
281 pub extern "C" fn MultiThreadedLockableScore_new(mut score: crate::lightning::routing::scoring::Score) -> crate::lightning::routing::scoring::MultiThreadedLockableScore {
282 let mut ret = lightning::routing::scoring::MultiThreadedLockableScore::new(score);
283 crate::lightning::routing::scoring::MultiThreadedLockableScore { inner: ObjOps::heap_alloc(ret), is_owned: true }
287 use lightning::routing::scoring::ChannelUsage as nativeChannelUsageImport;
288 pub(crate) type nativeChannelUsage = nativeChannelUsageImport;
290 /// Proposed use of a channel passed as a parameter to [`Score::channel_penalty_msat`].
293 pub struct ChannelUsage {
294 /// A pointer to the opaque Rust object.
296 /// Nearly everywhere, inner must be non-null, however in places where
297 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
298 pub inner: *mut nativeChannelUsage,
299 /// Indicates that this is the only struct which contains the same pointer.
301 /// Rust functions which take ownership of an object provided via an argument require
302 /// this to be true and invalidate the object pointed to by inner.
306 impl Drop for ChannelUsage {
308 if self.is_owned && !<*mut nativeChannelUsage>::is_null(self.inner) {
309 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
313 /// Frees any resources used by the ChannelUsage, if is_owned is set and inner is non-NULL.
315 pub extern "C" fn ChannelUsage_free(this_obj: ChannelUsage) { }
317 /// Used only if an object of this type is returned as a trait impl by a method
318 pub(crate) extern "C" fn ChannelUsage_free_void(this_ptr: *mut c_void) {
319 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeChannelUsage); }
323 pub(crate) fn get_native_ref(&self) -> &'static nativeChannelUsage {
324 unsafe { &*ObjOps::untweak_ptr(self.inner) }
326 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeChannelUsage {
327 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
329 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
330 pub(crate) fn take_inner(mut self) -> *mut nativeChannelUsage {
331 assert!(self.is_owned);
332 let ret = ObjOps::untweak_ptr(self.inner);
333 self.inner = core::ptr::null_mut();
337 /// The amount to send through the channel, denominated in millisatoshis.
339 pub extern "C" fn ChannelUsage_get_amount_msat(this_ptr: &ChannelUsage) -> u64 {
340 let mut inner_val = &mut this_ptr.get_native_mut_ref().amount_msat;
343 /// The amount to send through the channel, denominated in millisatoshis.
345 pub extern "C" fn ChannelUsage_set_amount_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
346 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.amount_msat = val;
348 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
349 /// as part of a multi-path payment.
351 pub extern "C" fn ChannelUsage_get_inflight_htlc_msat(this_ptr: &ChannelUsage) -> u64 {
352 let mut inner_val = &mut this_ptr.get_native_mut_ref().inflight_htlc_msat;
355 /// Total amount, denominated in millisatoshis, already allocated to send through the channel
356 /// as part of a multi-path payment.
358 pub extern "C" fn ChannelUsage_set_inflight_htlc_msat(this_ptr: &mut ChannelUsage, mut val: u64) {
359 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.inflight_htlc_msat = val;
361 /// The effective capacity of the channel.
363 pub extern "C" fn ChannelUsage_get_effective_capacity(this_ptr: &ChannelUsage) -> crate::lightning::routing::gossip::EffectiveCapacity {
364 let mut inner_val = &mut this_ptr.get_native_mut_ref().effective_capacity;
365 crate::lightning::routing::gossip::EffectiveCapacity::from_native(inner_val)
367 /// The effective capacity of the channel.
369 pub extern "C" fn ChannelUsage_set_effective_capacity(this_ptr: &mut ChannelUsage, mut val: crate::lightning::routing::gossip::EffectiveCapacity) {
370 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.effective_capacity = val.into_native();
372 /// Constructs a new ChannelUsage given each field
375 pub extern "C" fn ChannelUsage_new(mut amount_msat_arg: u64, mut inflight_htlc_msat_arg: u64, mut effective_capacity_arg: crate::lightning::routing::gossip::EffectiveCapacity) -> ChannelUsage {
376 ChannelUsage { inner: ObjOps::heap_alloc(nativeChannelUsage {
377 amount_msat: amount_msat_arg,
378 inflight_htlc_msat: inflight_htlc_msat_arg,
379 effective_capacity: effective_capacity_arg.into_native(),
382 impl Clone for ChannelUsage {
383 fn clone(&self) -> Self {
385 inner: if <*mut nativeChannelUsage>::is_null(self.inner) { core::ptr::null_mut() } else {
386 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
392 /// Used only if an object of this type is returned as a trait impl by a method
393 pub(crate) extern "C" fn ChannelUsage_clone_void(this_ptr: *const c_void) -> *mut c_void {
394 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeChannelUsage)).clone() })) as *mut c_void
397 /// Creates a copy of the ChannelUsage
398 pub extern "C" fn ChannelUsage_clone(orig: &ChannelUsage) -> ChannelUsage {
402 use lightning::routing::scoring::FixedPenaltyScorer as nativeFixedPenaltyScorerImport;
403 pub(crate) type nativeFixedPenaltyScorer = nativeFixedPenaltyScorerImport;
405 /// [`Score`] implementation that uses a fixed penalty.
408 pub struct FixedPenaltyScorer {
409 /// A pointer to the opaque Rust object.
411 /// Nearly everywhere, inner must be non-null, however in places where
412 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
413 pub inner: *mut nativeFixedPenaltyScorer,
414 /// Indicates that this is the only struct which contains the same pointer.
416 /// Rust functions which take ownership of an object provided via an argument require
417 /// this to be true and invalidate the object pointed to by inner.
421 impl Drop for FixedPenaltyScorer {
423 if self.is_owned && !<*mut nativeFixedPenaltyScorer>::is_null(self.inner) {
424 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
428 /// Frees any resources used by the FixedPenaltyScorer, if is_owned is set and inner is non-NULL.
430 pub extern "C" fn FixedPenaltyScorer_free(this_obj: FixedPenaltyScorer) { }
432 /// Used only if an object of this type is returned as a trait impl by a method
433 pub(crate) extern "C" fn FixedPenaltyScorer_free_void(this_ptr: *mut c_void) {
434 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeFixedPenaltyScorer); }
437 impl FixedPenaltyScorer {
438 pub(crate) fn get_native_ref(&self) -> &'static nativeFixedPenaltyScorer {
439 unsafe { &*ObjOps::untweak_ptr(self.inner) }
441 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeFixedPenaltyScorer {
442 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
444 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
445 pub(crate) fn take_inner(mut self) -> *mut nativeFixedPenaltyScorer {
446 assert!(self.is_owned);
447 let ret = ObjOps::untweak_ptr(self.inner);
448 self.inner = core::ptr::null_mut();
452 impl Clone for FixedPenaltyScorer {
453 fn clone(&self) -> Self {
455 inner: if <*mut nativeFixedPenaltyScorer>::is_null(self.inner) { core::ptr::null_mut() } else {
456 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
462 /// Used only if an object of this type is returned as a trait impl by a method
463 pub(crate) extern "C" fn FixedPenaltyScorer_clone_void(this_ptr: *const c_void) -> *mut c_void {
464 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeFixedPenaltyScorer)).clone() })) as *mut c_void
467 /// Creates a copy of the FixedPenaltyScorer
468 pub extern "C" fn FixedPenaltyScorer_clone(orig: &FixedPenaltyScorer) -> FixedPenaltyScorer {
471 /// Creates a new scorer using `penalty_msat`.
474 pub extern "C" fn FixedPenaltyScorer_with_penalty(mut penalty_msat: u64) -> crate::lightning::routing::scoring::FixedPenaltyScorer {
475 let mut ret = lightning::routing::scoring::FixedPenaltyScorer::with_penalty(penalty_msat);
476 crate::lightning::routing::scoring::FixedPenaltyScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
479 impl From<nativeFixedPenaltyScorer> for crate::lightning::routing::scoring::Score {
480 fn from(obj: nativeFixedPenaltyScorer) -> Self {
481 let mut rust_obj = FixedPenaltyScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
482 let mut ret = FixedPenaltyScorer_as_Score(&rust_obj);
483 // 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
484 rust_obj.inner = core::ptr::null_mut();
485 ret.free = Some(FixedPenaltyScorer_free_void);
489 /// Constructs a new Score which calls the relevant methods on this_arg.
490 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
492 pub extern "C" fn FixedPenaltyScorer_as_Score(this_arg: &FixedPenaltyScorer) -> crate::lightning::routing::scoring::Score {
493 crate::lightning::routing::scoring::Score {
494 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
496 channel_penalty_msat: FixedPenaltyScorer_Score_channel_penalty_msat,
497 payment_path_failed: FixedPenaltyScorer_Score_payment_path_failed,
498 payment_path_successful: FixedPenaltyScorer_Score_payment_path_successful,
499 probe_failed: FixedPenaltyScorer_Score_probe_failed,
500 probe_successful: FixedPenaltyScorer_Score_probe_successful,
501 write: FixedPenaltyScorer_write_void,
506 extern "C" fn FixedPenaltyScorer_Score_channel_penalty_msat(this_arg: *const c_void, unused_0: u64, unused_1: &crate::lightning::routing::gossip::NodeId, unused_2: &crate::lightning::routing::gossip::NodeId, unused_3: crate::lightning::routing::scoring::ChannelUsage) -> u64 {
507 let mut ret = <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, unused_0, unused_1.get_native_ref(), unused_2.get_native_ref(), *unsafe { Box::from_raw(unused_3.take_inner()) });
510 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) {
511 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
512 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..], _short_channel_id)
514 extern "C" fn FixedPenaltyScorer_Score_payment_path_successful(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ) {
515 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
516 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..])
518 extern "C" fn FixedPenaltyScorer_Score_probe_failed(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ, mut _short_channel_id: u64) {
519 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
520 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..], _short_channel_id)
522 extern "C" fn FixedPenaltyScorer_Score_probe_successful(this_arg: *mut c_void, mut _path: crate::c_types::derived::CVec_RouteHopZ) {
523 let mut local__path = Vec::new(); for mut item in _path.as_slice().iter() { local__path.push( { item.get_native_ref() }); };
524 <nativeFixedPenaltyScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeFixedPenaltyScorer) }, &local__path[..])
528 /// Serialize the FixedPenaltyScorer object into a byte array which can be read by FixedPenaltyScorer_read
529 pub extern "C" fn FixedPenaltyScorer_write(obj: &crate::lightning::routing::scoring::FixedPenaltyScorer) -> crate::c_types::derived::CVec_u8Z {
530 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
533 pub(crate) extern "C" fn FixedPenaltyScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
534 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeFixedPenaltyScorer) })
537 /// Read a FixedPenaltyScorer from a byte array, created by FixedPenaltyScorer_write
538 pub extern "C" fn FixedPenaltyScorer_read(ser: crate::c_types::u8slice, arg: u64) -> crate::c_types::derived::CResult_FixedPenaltyScorerDecodeErrorZ {
540 let res: Result<lightning::routing::scoring::FixedPenaltyScorer, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
541 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() };
545 use lightning::routing::scoring::ProbabilisticScorer as nativeProbabilisticScorerImport;
546 pub(crate) type nativeProbabilisticScorer = nativeProbabilisticScorerImport<&'static lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>;
548 /// [`Score`] implementation using channel success probability distributions.
550 /// Based on *Optimally Reliable & Cheap Payment Flows on the Lightning Network* by Rene Pickhardt
551 /// and Stefan Richter [[1]]. Given the uncertainty of channel liquidity balances, probability
552 /// distributions are defined based on knowledge learned from successful and unsuccessful attempts.
553 /// Then the negative `log10` of the success probability is used to determine the cost of routing a
554 /// specific HTLC amount through a channel.
556 /// Knowledge about channel liquidity balances takes the form of upper and lower bounds on the
557 /// possible liquidity. Certainty of the bounds is decreased over time using a decay function. See
558 /// [`ProbabilisticScoringParameters`] for details.
560 /// Since the scorer aims to learn the current channel liquidity balances, it works best for nodes
561 /// with high payment volume or that actively probe the [`NetworkGraph`]. Nodes with low payment
562 /// volume are more likely to experience failed payment paths, which would need to be retried.
566 /// Mixing the `no-std` feature between serialization and deserialization results in undefined
569 /// [1]: https://arxiv.org/abs/2107.05322
572 pub struct ProbabilisticScorer {
573 /// A pointer to the opaque Rust object.
575 /// Nearly everywhere, inner must be non-null, however in places where
576 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
577 pub inner: *mut nativeProbabilisticScorer,
578 /// Indicates that this is the only struct which contains the same pointer.
580 /// Rust functions which take ownership of an object provided via an argument require
581 /// this to be true and invalidate the object pointed to by inner.
585 impl Drop for ProbabilisticScorer {
587 if self.is_owned && !<*mut nativeProbabilisticScorer>::is_null(self.inner) {
588 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
592 /// Frees any resources used by the ProbabilisticScorer, if is_owned is set and inner is non-NULL.
594 pub extern "C" fn ProbabilisticScorer_free(this_obj: ProbabilisticScorer) { }
596 /// Used only if an object of this type is returned as a trait impl by a method
597 pub(crate) extern "C" fn ProbabilisticScorer_free_void(this_ptr: *mut c_void) {
598 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScorer); }
601 impl ProbabilisticScorer {
602 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScorer {
603 unsafe { &*ObjOps::untweak_ptr(self.inner) }
605 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScorer {
606 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
608 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
609 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScorer {
610 assert!(self.is_owned);
611 let ret = ObjOps::untweak_ptr(self.inner);
612 self.inner = core::ptr::null_mut();
617 use lightning::routing::scoring::ProbabilisticScoringParameters as nativeProbabilisticScoringParametersImport;
618 pub(crate) type nativeProbabilisticScoringParameters = nativeProbabilisticScoringParametersImport;
620 /// Parameters for configuring [`ProbabilisticScorer`].
622 /// Used to configure base, liquidity, and amount penalties, the sum of which comprises the channel
623 /// penalty (i.e., the amount in msats willing to be paid to avoid routing through the channel).
625 /// The penalty applied to any channel by the [`ProbabilisticScorer`] is the sum of each of the
629 pub struct ProbabilisticScoringParameters {
630 /// A pointer to the opaque Rust object.
632 /// Nearly everywhere, inner must be non-null, however in places where
633 /// the Rust equivalent takes an Option, it may be set to null to indicate None.
634 pub inner: *mut nativeProbabilisticScoringParameters,
635 /// Indicates that this is the only struct which contains the same pointer.
637 /// Rust functions which take ownership of an object provided via an argument require
638 /// this to be true and invalidate the object pointed to by inner.
642 impl Drop for ProbabilisticScoringParameters {
644 if self.is_owned && !<*mut nativeProbabilisticScoringParameters>::is_null(self.inner) {
645 let _ = unsafe { Box::from_raw(ObjOps::untweak_ptr(self.inner)) };
649 /// Frees any resources used by the ProbabilisticScoringParameters, if is_owned is set and inner is non-NULL.
651 pub extern "C" fn ProbabilisticScoringParameters_free(this_obj: ProbabilisticScoringParameters) { }
653 /// Used only if an object of this type is returned as a trait impl by a method
654 pub(crate) extern "C" fn ProbabilisticScoringParameters_free_void(this_ptr: *mut c_void) {
655 unsafe { let _ = Box::from_raw(this_ptr as *mut nativeProbabilisticScoringParameters); }
658 impl ProbabilisticScoringParameters {
659 pub(crate) fn get_native_ref(&self) -> &'static nativeProbabilisticScoringParameters {
660 unsafe { &*ObjOps::untweak_ptr(self.inner) }
662 pub(crate) fn get_native_mut_ref(&self) -> &'static mut nativeProbabilisticScoringParameters {
663 unsafe { &mut *ObjOps::untweak_ptr(self.inner) }
665 /// When moving out of the pointer, we have to ensure we aren't a reference, this makes that easy
666 pub(crate) fn take_inner(mut self) -> *mut nativeProbabilisticScoringParameters {
667 assert!(self.is_owned);
668 let ret = ObjOps::untweak_ptr(self.inner);
669 self.inner = core::ptr::null_mut();
673 /// A fixed penalty in msats to apply to each channel.
675 /// Default value: 500 msat
677 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
678 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_msat;
681 /// A fixed penalty in msats to apply to each channel.
683 /// Default value: 500 msat
685 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
686 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_msat = val;
688 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
689 /// channel, in excess of the [`base_penalty_msat`].
691 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
692 /// fees plus penalty) for large payments. The penalty is computed as the product of this
693 /// multiplier and `2^30`ths of the payment amount.
695 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
697 /// Default value: 8,192 msat
699 /// [`base_penalty_msat`]: Self::base_penalty_msat
701 pub extern "C" fn ProbabilisticScoringParameters_get_base_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
702 let mut inner_val = &mut this_ptr.get_native_mut_ref().base_penalty_amount_multiplier_msat;
705 /// A multiplier used with the payment amount to calculate a fixed penalty applied to each
706 /// channel, in excess of the [`base_penalty_msat`].
708 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
709 /// fees plus penalty) for large payments. The penalty is computed as the product of this
710 /// multiplier and `2^30`ths of the payment amount.
712 /// ie `base_penalty_amount_multiplier_msat * amount_msat / 2^30`
714 /// Default value: 8,192 msat
716 /// [`base_penalty_msat`]: Self::base_penalty_msat
718 pub extern "C" fn ProbabilisticScoringParameters_set_base_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
719 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.base_penalty_amount_multiplier_msat = val;
721 /// A multiplier used in conjunction with the negative `log10` of the channel's success
722 /// probability for a payment to determine the liquidity penalty.
724 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
725 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
726 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
727 /// lower bounding the success probability to `0.01`) when the amount falls within the
728 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
729 /// result in a `u64::max_value` penalty, however.
731 /// Default value: 40,000 msat
733 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
735 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
736 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_multiplier_msat;
739 /// A multiplier used in conjunction with the negative `log10` of the channel's success
740 /// probability for a payment to determine the liquidity penalty.
742 /// The penalty is based in part on the knowledge learned from prior successful and unsuccessful
743 /// payments. This knowledge is decayed over time based on [`liquidity_offset_half_life`]. The
744 /// penalty is effectively limited to `2 * liquidity_penalty_multiplier_msat` (corresponding to
745 /// lower bounding the success probability to `0.01`) when the amount falls within the
746 /// uncertainty bounds of the channel liquidity balance. Amounts above the upper bound will
747 /// result in a `u64::max_value` penalty, however.
749 /// Default value: 40,000 msat
751 /// [`liquidity_offset_half_life`]: Self::liquidity_offset_half_life
753 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
754 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_multiplier_msat = val;
756 /// The time required to elapse before any knowledge learned about channel liquidity balances is
759 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
760 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
761 /// the certainty of the channel liquidity balance.
763 /// Default value: 1 hour
767 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
768 /// liquidity knowledge will never decay except when the bounds cross.
770 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_offset_half_life(this_ptr: &ProbabilisticScoringParameters) -> u64 {
771 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_offset_half_life;
774 /// The time required to elapse before any knowledge learned about channel liquidity balances is
777 /// The bounds are defined in terms of offsets and are initially zero. Increasing the offsets
778 /// gives tighter bounds on the channel liquidity balance. Thus, halving the offsets decreases
779 /// the certainty of the channel liquidity balance.
781 /// Default value: 1 hour
785 /// When built with the `no-std` feature, time will never elapse. Therefore, the channel
786 /// liquidity knowledge will never decay except when the bounds cross.
788 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_offset_half_life(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
789 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_offset_half_life = core::time::Duration::from_secs(val);
791 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
792 /// channel's success probability for the payment to determine the amount penalty.
794 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
795 /// fees plus penalty) for large payments. The penalty is computed as the product of this
796 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
797 /// success probability.
799 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
801 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
802 /// the amount will result in a penalty of the multiplier. And, as the success probability
803 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
804 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
807 /// Default value: 256 msat
809 pub extern "C" fn ProbabilisticScoringParameters_get_liquidity_penalty_amount_multiplier_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
810 let mut inner_val = &mut this_ptr.get_native_mut_ref().liquidity_penalty_amount_multiplier_msat;
813 /// A multiplier used in conjunction with a payment amount and the negative `log10` of the
814 /// channel's success probability for the payment to determine the amount penalty.
816 /// The purpose of the amount penalty is to avoid having fees dominate the channel cost (i.e.,
817 /// fees plus penalty) for large payments. The penalty is computed as the product of this
818 /// multiplier and `2^20`ths of the payment amount, weighted by the negative `log10` of the
819 /// success probability.
821 /// `-log10(success_probability) * liquidity_penalty_amount_multiplier_msat * amount_msat / 2^20`
823 /// In practice, this means for 0.1 success probability (`-log10(0.1) == 1`) each `2^20`th of
824 /// the amount will result in a penalty of the multiplier. And, as the success probability
825 /// decreases, the negative `log10` weighting will increase dramatically. For higher success
826 /// probabilities, the multiplier will have a decreasing effect as the negative `log10` will
829 /// Default value: 256 msat
831 pub extern "C" fn ProbabilisticScoringParameters_set_liquidity_penalty_amount_multiplier_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
832 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.liquidity_penalty_amount_multiplier_msat = val;
834 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
835 /// channel's capacity, which makes us prefer nodes with a smaller `htlc_maximum_msat`. We
836 /// treat such nodes preferentially as this makes balance discovery attacks harder to execute,
837 /// thereby creating an incentive to restrict `htlc_maximum_msat` and improve privacy.
839 /// Default value: 250 msat
841 pub extern "C" fn ProbabilisticScoringParameters_get_anti_probing_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
842 let mut inner_val = &mut this_ptr.get_native_mut_ref().anti_probing_penalty_msat;
845 /// This penalty is applied when `htlc_maximum_msat` is equal to or larger than half of the
846 /// channel's capacity, which makes us prefer nodes with a smaller `htlc_maximum_msat`. We
847 /// treat such nodes preferentially as this makes balance discovery attacks harder to execute,
848 /// thereby creating an incentive to restrict `htlc_maximum_msat` and improve privacy.
850 /// Default value: 250 msat
852 pub extern "C" fn ProbabilisticScoringParameters_set_anti_probing_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
853 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.anti_probing_penalty_msat = val;
855 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
856 /// current estimate of the channel's available liquidity.
858 /// Note that in this case all other penalties, including the
859 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
860 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
861 /// applicable, are still included in the overall penalty.
863 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
864 /// `u64::max_value()` will guarantee that.
866 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
868 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
869 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
870 /// [`base_penalty_msat`]: Self::base_penalty_msat
871 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
873 pub extern "C" fn ProbabilisticScoringParameters_get_considered_impossible_penalty_msat(this_ptr: &ProbabilisticScoringParameters) -> u64 {
874 let mut inner_val = &mut this_ptr.get_native_mut_ref().considered_impossible_penalty_msat;
877 /// This penalty is applied when the amount we're attempting to send over a channel exceeds our
878 /// current estimate of the channel's available liquidity.
880 /// Note that in this case all other penalties, including the
881 /// [`liquidity_penalty_multiplier_msat`] and [`liquidity_penalty_amount_multiplier_msat`]-based
882 /// penalties, as well as the [`base_penalty_msat`] and the [`anti_probing_penalty_msat`], if
883 /// applicable, are still included in the overall penalty.
885 /// If you wish to avoid creating paths with such channels entirely, setting this to a value of
886 /// `u64::max_value()` will guarantee that.
888 /// Default value: 1_0000_0000_000 msat (1 Bitcoin)
890 /// [`liquidity_penalty_multiplier_msat`]: Self::liquidity_penalty_multiplier_msat
891 /// [`liquidity_penalty_amount_multiplier_msat`]: Self::liquidity_penalty_amount_multiplier_msat
892 /// [`base_penalty_msat`]: Self::base_penalty_msat
893 /// [`anti_probing_penalty_msat`]: Self::anti_probing_penalty_msat
895 pub extern "C" fn ProbabilisticScoringParameters_set_considered_impossible_penalty_msat(this_ptr: &mut ProbabilisticScoringParameters, mut val: u64) {
896 unsafe { &mut *ObjOps::untweak_ptr(this_ptr.inner) }.considered_impossible_penalty_msat = val;
898 impl Clone for ProbabilisticScoringParameters {
899 fn clone(&self) -> Self {
901 inner: if <*mut nativeProbabilisticScoringParameters>::is_null(self.inner) { core::ptr::null_mut() } else {
902 ObjOps::heap_alloc(unsafe { &*ObjOps::untweak_ptr(self.inner) }.clone()) },
908 /// Used only if an object of this type is returned as a trait impl by a method
909 pub(crate) extern "C" fn ProbabilisticScoringParameters_clone_void(this_ptr: *const c_void) -> *mut c_void {
910 Box::into_raw(Box::new(unsafe { (*(this_ptr as *mut nativeProbabilisticScoringParameters)).clone() })) as *mut c_void
913 /// Creates a copy of the ProbabilisticScoringParameters
914 pub extern "C" fn ProbabilisticScoringParameters_clone(orig: &ProbabilisticScoringParameters) -> ProbabilisticScoringParameters {
917 /// Creates a new scorer using the given scoring parameters for sending payments from a node
918 /// through a network graph.
921 pub extern "C" fn ProbabilisticScorer_new(mut params: crate::lightning::routing::scoring::ProbabilisticScoringParameters, network_graph: &crate::lightning::routing::gossip::NetworkGraph, mut logger: crate::lightning::util::logger::Logger) -> crate::lightning::routing::scoring::ProbabilisticScorer {
922 let mut ret = lightning::routing::scoring::ProbabilisticScorer::new(*unsafe { Box::from_raw(params.take_inner()) }, network_graph.get_native_ref(), logger);
923 crate::lightning::routing::scoring::ProbabilisticScorer { inner: ObjOps::heap_alloc(ret), is_owned: true }
926 /// Dump the contents of this scorer into the configured logger.
928 /// Note that this writes roughly one line per channel for which we have a liquidity estimate,
929 /// which may be a substantial amount of log output.
931 pub extern "C" fn ProbabilisticScorer_debug_log_liquidity_stats(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer) {
932 unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.debug_log_liquidity_stats()
935 /// Query the estimated minimum and maximum liquidity available for sending a payment over the
936 /// channel with `scid` towards the given `target` node.
939 pub extern "C" fn ProbabilisticScorer_estimated_channel_liquidity_range(this_arg: &crate::lightning::routing::scoring::ProbabilisticScorer, mut scid: u64, target: &crate::lightning::routing::gossip::NodeId) -> crate::c_types::derived::COption_C2Tuple_u64u64ZZ {
940 let mut ret = unsafe { &*ObjOps::untweak_ptr(this_arg.inner) }.estimated_channel_liquidity_range(scid, target.get_native_ref());
941 let mut local_ret = if ret.is_none() { crate::c_types::derived::COption_C2Tuple_u64u64ZZ::None } else { crate::c_types::derived::COption_C2Tuple_u64u64ZZ::Some( { let (mut orig_ret_0_0, mut orig_ret_0_1) = (ret.unwrap()); let mut local_ret_0 = (orig_ret_0_0, orig_ret_0_1).into(); local_ret_0 }) };
945 /// Marks the node with the given `node_id` as banned, i.e.,
946 /// it will be avoided during path finding.
948 pub extern "C" fn ProbabilisticScorer_add_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
949 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.add_banned(node_id.get_native_ref())
952 /// Removes the node with the given `node_id` from the list of nodes to avoid.
954 pub extern "C" fn ProbabilisticScorer_remove_banned(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
955 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.remove_banned(node_id.get_native_ref())
958 /// Sets a manual penalty for the given node.
960 pub extern "C" fn ProbabilisticScorer_set_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId, mut penalty: u64) {
961 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.set_manual_penalty(node_id.get_native_ref(), penalty)
964 /// Removes the node with the given `node_id` from the list of manual penalties.
966 pub extern "C" fn ProbabilisticScorer_remove_manual_penalty(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer, node_id: &crate::lightning::routing::gossip::NodeId) {
967 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.remove_manual_penalty(node_id.get_native_ref())
970 /// Clears the list of manual penalties that are applied during path finding.
972 pub extern "C" fn ProbabilisticScorer_clear_manual_penalties(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScorer) {
973 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScorer)) }.clear_manual_penalties()
976 /// Marks all nodes in the given list as banned, i.e.,
977 /// they will be avoided during path finding.
979 pub extern "C" fn ProbabilisticScoringParameters_add_banned_from_list(this_arg: &mut crate::lightning::routing::scoring::ProbabilisticScoringParameters, mut node_ids: crate::c_types::derived::CVec_NodeIdZ) {
980 let mut local_node_ids = Vec::new(); for mut item in node_ids.into_rust().drain(..) { local_node_ids.push( { *unsafe { Box::from_raw(item.take_inner()) } }); };
981 unsafe { &mut (*ObjOps::untweak_ptr(this_arg.inner as *mut crate::lightning::routing::scoring::nativeProbabilisticScoringParameters)) }.add_banned_from_list(local_node_ids)
984 /// Creates a "default" ProbabilisticScoringParameters. See struct and individual field documentaiton for details on which values are used.
987 pub extern "C" fn ProbabilisticScoringParameters_default() -> ProbabilisticScoringParameters {
988 ProbabilisticScoringParameters { inner: ObjOps::heap_alloc(Default::default()), is_owned: true }
990 impl From<nativeProbabilisticScorer> for crate::lightning::routing::scoring::Score {
991 fn from(obj: nativeProbabilisticScorer) -> Self {
992 let mut rust_obj = ProbabilisticScorer { inner: ObjOps::heap_alloc(obj), is_owned: true };
993 let mut ret = ProbabilisticScorer_as_Score(&rust_obj);
994 // 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
995 rust_obj.inner = core::ptr::null_mut();
996 ret.free = Some(ProbabilisticScorer_free_void);
1000 /// Constructs a new Score which calls the relevant methods on this_arg.
1001 /// This copies the `inner` pointer in this_arg and thus the returned Score must be freed before this_arg is
1003 pub extern "C" fn ProbabilisticScorer_as_Score(this_arg: &ProbabilisticScorer) -> crate::lightning::routing::scoring::Score {
1004 crate::lightning::routing::scoring::Score {
1005 this_arg: unsafe { ObjOps::untweak_ptr((*this_arg).inner) as *mut c_void },
1007 channel_penalty_msat: ProbabilisticScorer_Score_channel_penalty_msat,
1008 payment_path_failed: ProbabilisticScorer_Score_payment_path_failed,
1009 payment_path_successful: ProbabilisticScorer_Score_payment_path_successful,
1010 probe_failed: ProbabilisticScorer_Score_probe_failed,
1011 probe_successful: ProbabilisticScorer_Score_probe_successful,
1012 write: ProbabilisticScorer_write_void,
1017 extern "C" fn ProbabilisticScorer_Score_channel_penalty_msat(this_arg: *const c_void, mut short_channel_id: u64, source: &crate::lightning::routing::gossip::NodeId, target: &crate::lightning::routing::gossip::NodeId, mut usage: crate::lightning::routing::scoring::ChannelUsage) -> u64 {
1018 let mut ret = <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::channel_penalty_msat(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, short_channel_id, source.get_native_ref(), target.get_native_ref(), *unsafe { Box::from_raw(usage.take_inner()) });
1021 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) {
1022 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1023 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id)
1025 extern "C" fn ProbabilisticScorer_Score_payment_path_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
1026 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1027 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::payment_path_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..])
1029 extern "C" fn ProbabilisticScorer_Score_probe_failed(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ, mut short_channel_id: u64) {
1030 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1031 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_failed(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..], short_channel_id)
1033 extern "C" fn ProbabilisticScorer_Score_probe_successful(this_arg: *mut c_void, mut path: crate::c_types::derived::CVec_RouteHopZ) {
1034 let mut local_path = Vec::new(); for mut item in path.as_slice().iter() { local_path.push( { item.get_native_ref() }); };
1035 <nativeProbabilisticScorer as lightning::routing::scoring::Score<>>::probe_successful(unsafe { &mut *(this_arg as *mut nativeProbabilisticScorer) }, &local_path[..])
1040 use alloc::str::FromStr;
1041 use core::ffi::c_void;
1042 use core::convert::Infallible;
1043 use bitcoin::hashes::Hash;
1044 use crate::c_types::*;
1045 #[cfg(feature="no-std")]
1046 use alloc::{vec::Vec, boxed::Box};
1050 /// Serialize the ProbabilisticScorer object into a byte array which can be read by ProbabilisticScorer_read
1051 pub extern "C" fn ProbabilisticScorer_write(obj: &crate::lightning::routing::scoring::ProbabilisticScorer) -> crate::c_types::derived::CVec_u8Z {
1052 crate::c_types::serialize_obj(unsafe { &*obj }.get_native_ref())
1055 pub(crate) extern "C" fn ProbabilisticScorer_write_void(obj: *const c_void) -> crate::c_types::derived::CVec_u8Z {
1056 crate::c_types::serialize_obj(unsafe { &*(obj as *const nativeProbabilisticScorer) })
1059 /// Read a ProbabilisticScorer from a byte array, created by ProbabilisticScorer_write
1060 pub extern "C" fn ProbabilisticScorer_read(ser: crate::c_types::u8slice, arg_a: crate::lightning::routing::scoring::ProbabilisticScoringParameters, arg_b: &crate::lightning::routing::gossip::NetworkGraph, arg_c: crate::lightning::util::logger::Logger) -> crate::c_types::derived::CResult_ProbabilisticScorerDecodeErrorZ {
1061 let arg_a_conv = *unsafe { Box::from_raw(arg_a.take_inner()) };
1062 let arg_b_conv = arg_b.get_native_ref();
1063 let arg_c_conv = arg_c;
1064 let arg_conv = (arg_a_conv, arg_b_conv, arg_c_conv);
1065 let res: Result<lightning::routing::scoring::ProbabilisticScorer<&lightning::routing::gossip::NetworkGraph<crate::lightning::util::logger::Logger>, crate::lightning::util::logger::Logger>, lightning::ln::msgs::DecodeError> = crate::c_types::deserialize_obj_arg(ser, arg_conv);
1066 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() };